Find a subarray with a given sum.

Srajan Gupta
The Startup
Published in
2 min readSep 25, 2019

--

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 test case, in a new line, print the starting and ending positions(1 indexing) of first such occurring subarray from the left if sum equals to subarray, else print -1.

This problem has been previously asked in Adobe, Amazon, and Facebook.

In this problem, we need to find in an array of the integers of any sub-array adds to the given sum.

We will be using the Sliding Window method to solve this problem.

Sliding Window method states that we take a fixed size sub-array called a window and slide it over the given array. During the process, if at any instant the sum of the integers covered by the window equals the given sum, we return otherwise we keep on sliding the window till we reach the end of the given array.

--

--