user11675948
user11675948

Reputation:

Subarray with given sum

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

Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum. The second line of each test case contains N space separated integers denoting the array elements.

Output:
For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1.

Constraints:

1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1010

Example:
Input:

2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10

Output:

2 4
1 5

My Code:

#include <iostream>

using namespace std;

int main() {
    int t, n, s, a[1000], result[1000];
    cin >> t;
    for (int i = 0; i < t; i++) {
        result[i * 2] = -1;
        cin >> n >> s;
        for (int j = 0; j < n; j++) {
            cin >> a[j];
        }
        int flag = 0;
        for (int j = 0; j < n; j++) {
            if (flag == 0) {
                int sum = 0;
                for (int k = j; k < n && sum < s; k++) {
                    sum += a[k];
                    if (sum == s) {
                        result[i * 2] = j + 1;
                        result[(i * 2) + 1] = k + 1;
                        flag = 1;
                        break;
                    }
                }
            }
        }
    }
    for (int i = 0; i < t * 2; i += 2) {
        if (result[i] != -1) {
            cout << result[i] << " " << result[i + 1] << endl;
        } else {
            cout << result[i];
        }
    }
}

Result:
Wrong Answer. !!!Wrong Answer

Possibly your code doesn't work correctly for multiple test-cases (TCs).

The first test case where your code failed:

Input:

4 225
9 45 10 190

Its Correct output is:

-1

And Your Code's output is:

-1-1-1-138 42

Upvotes: 1

Views: 497

Answers (1)

Imre
Imre

Reputation: 332

I've just found this: https://www.youtube.com/watch?v=G0ocgTgW464 However I believe that the time complexity is O(n*log(n)) given the fact that map::find is O(log(n))

Upvotes: 0

Related Questions