Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array that adds to a given number S. In case of multiple subarrays, return the subarray which comes first on moving from left to right.
So in this we need to use two pointer low and high and if sum of num up till i'th is less than the number then high++ and add to the sum and if it is greater than the number we need to do subtract arr[low] and low++ than we will get the answer. it is 2 pointer iterating from the same point high for the upper bound and low for the lower bound.
Example 1:
Input:
N = 5, S = 12
A[] = {1,2,3,7,5}
Output: 2 4
Explanation: The sum of elements
from 2nd position to 4th position
is 12.
Example 2:
Input:
N = 10, S = 15
A[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1 5
Explanation: The sum of elements
from 1st position to 5th position
is 15.
#include <bits/stdc++.h>
using namespace std;
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)
{
// Your code here
long long sum=arr[0];
int low=0,high=0;
while((low<n) && (high<n))
{
if(sum==s)
{
return {low+1,high+1};
}
else if(sum<s)
{
high++;
sum+=arr[high];
}
else
{
sum-=arr[low];
low++;
}
}
return {-1};
}
};
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
long long s;
cin>>n>>s;
int arr[n];
const int mx = 1e9;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
Solution ob;
vector<int>res;
res = ob.subarraySum(arr, n, s);
for(int i = 0;i<res.size();i++)
cout<<res[i]<<" ";
cout<<endl;
}
return 0;
}