Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Arrays

Subarray with a Given Sum

Medium · Arrays · Asked at Amazon, Google, Microsoft, Visa, TCS

All elements are positive. Find a contiguous subarray whose sum is exactly S. If several exist, choose the one that ends earliest. Print its start and end positions (1-based), or -1 if there is none.

Input

First line: n S. Second line: n positive integers.

Output

l r, or -1.

Constraints

With positive numbers, a sliding window works: extend the right end, and while the window sum is larger than S, drop elements from the left. The first time the sum equals S, that window ends earliest — and for a fixed end only one start can work.

Example 1

Input

5 12
1 2 3 7 5

Output

2 4

Example 2

Input

3 100
1 2 3

Output

-1

Hints

  1. All numbers are positive, so a longer window always has a bigger sum.
  2. Grow the window on the right; shrink it from the left while the sum is too big.
  3. The first time the sum equals S, that window ends earliest.

Approach

Keep a window [l, r] and its sum. For each r, add a[r]; while the sum exceeds S, subtract a[l] and move l right. If the sum now equals S, print l + 1 and r + 1 and stop. With positive numbers, for a fixed right end only one left end can give exactly S, so the answer is unique. If the loop finishes, print −1.

Complexity: O(n) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    long long S;
    cin >> n >> S;
    vector<long long> a(n);
    for (auto &x : a) cin >> x;
    long long sum = 0;
    int l = 0;
    for (int r = 0; r < n; r++) {
        sum += a[r];
        while (sum > S) sum -= a[l++];
        if (sum == S) {
            cout << l + 1 << " " << r + 1 << "\n";
            return 0;
        }
    }
    cout << -1 << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n, S = data[0], data[1]
a = data[2 : 2 + n]
total = l = 0
answer = "-1"
for r in range(n):
    total += a[r]
    while total > S:
        total -= a[l]
        l += 1
    if total == S:
        answer = f"{l + 1} {r + 1}"
        break
print(answer)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        long S = (long) in.nval;
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
        }
        long sum = 0;
        int l = 0;
        for (int r = 0; r < n; r++) {
            sum += a[r];
            while (sum > S) sum -= a[l++];
            if (sum == S) {
                System.out.println((l + 1) + " " + (r + 1));
                return;
            }
        }
        System.out.println(-1);
    }
}

Solve Subarray with a Given Sum online · All practice problems