Problem Statement:
Given an unsorted array arr of size n of non-negative integers, find a continuous sub-array which adds to a given number s.
I have used sliding window technique to compute the sum of sub-array and then to compare it with the given number (s).
Here's my code that takes an array arr of size n, required sum s from the user and returns the starting and ending position of the subarray if it exist or -1 if it doesn't:
Note: Position of array elements is starting from 1 in the required output. Hence, for index say i=0, position will be (i+1)
vector<int> subarraySum(int arr[], int n, int s){
int l=0,r=0;
vector<int>v;
long long sum=0;
while(r<n)
{
sum=sum+arr[r];
if(sum==s)
{
v.push_back(l+1);
v.push_back(r+1);
break;
}
else if(sum<s)
{
r++;
}
else{
sum-=arr[l];
l++;
if(sum==s)
{
v.push_back(l+1);
v.push_back(r+1);
break;
}
r++;
}
}
if(v.empty())
{
v.push_back(-1);
}
return v;
}
The first test case where this code fails is
Input:
42 468 //n=42,s=468 and rest of the values are the array elements
135 101 170 125 79 159 163 65 106 146 82 28 162 92 196 143 28 37 192 5 103 154 93 183 22 117 119 96 48 127 172 139 70 113 68 100 36 95 104 12 123 134
Its Correct output is:
38 42
And above Code's output is:
-1
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints: 1 <= N <= 10^5, 1 <= Ai <= 10^10
Can someone please enlighten me with this and where I'm getting wrong ? And also what is the best approach to solve such questions ?