[Geeks for Geeks] Subarray with given sum

Subarray with given sum

Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array which adds to a given number S.

In case of multiple subarrays, return the subarray which comes first on moving from left to right.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution
{
public:
//Function to find a continuous sub-array which adds up to a given number.
vector<int> subarraySum(int arr[], int n, long long s)
{
int l = 0, r = 0;
long long sum = 0;
while(r < n) {
if(sum > s) {
sum -= arr[l++];
} else if(sum < s) {
sum += arr[r++];
}
if(sum == s) return {l + 1, r};
}
while(sum != s and l < n) {
sum -= arr[l++];
}
if(sum == s) return {l + 1, r};

return {-1};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/subarray-with-given-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.