0

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 ?

onkar_247
  • 9
  • 1
  • I've seen this same question posted on stackoverflow.com dozens of times. The correct way to do this does not need to use any other array or vector. Just a single loop, and a pair of variables. Maybe seven or eight lines of code. The shown code is overly complex, and complicated, and should simply be rewritten from scratch. See many other questions here that basically give the same formula answer. – Sam Varshavchik Sep 10 '20 at 18:57
  • Just for fun, I tried it. I found I needed a `while` loop when subtracting. https://ideone.com/f3nlNg – 001 Sep 10 '20 at 19:19
  • @JohnnyMopp - `while (end < n || (start < end && running_total > s))`, then make some wise decisions whether to increment `start` or `end`, on each iteration of the loop. One loop. – Sam Varshavchik Sep 10 '20 at 19:30
  • @SamVarshavchik Ah, I see. Thanks. Slightly modified: https://ideone.com/0WRlJv – 001 Sep 10 '20 at 19:54

0 Answers0