Given an Array of non negative Integers and a number. You need to print all the starting and ending indices of Subarrays having their sum equal to the given integer.
For example :
Explanation :
[3, 6] [9],
[9,0] These all are the subarrays with their sum equal to 9
Solution
Naive Method:
The basic brute force approach to this problem would be generating all the subarrays of the given array, then loop through the generated subarray and calculate the sum and if this sum is equal to the given sum then printing this subarray as it is the part of our solution.
Now we know, An Array with n elements has n*(n+1)/2 subarrays.
HOW?
Consider an array,Now,
int[] arr = {a1, a2, a3, a4…, an};
Subarrays starting with 0th index,
a1
a1, a2
a1, a2, a3
a1, a2, a3, a4
.
.
.
a1, a2, a3, a4…, an
Subarrays starting with 1st index,
a2
a2, a3
a2, a3, a4
.
.
.
a2, a3, a4…, an
subarrays starting with 2nd index,
a3
a3, a4
.
.
.
a3, a4…, an
Subarrays starting with last i.e. 3rd index,
a4
.
.
.
a4…, an
Total subarrays = subarrays starting with 0th idx + subarrays starting with 1st idx +
subarrays starting with 2nd idx + . . . + subarrays starting with nth idx
Sn = n + (n-1) + (n-2) + (n-3) + ... + 1
Sn = n(n+1)/2
There, generating all the subarrays and calculating the answer will cost us the worst time complexity of O(n(n+1)/2) which is of the order O(n^2).
O(n) as the worst time complexity.We can maintain two pointers, start and end pointers which basically represents a subarray and also we have to take a variable which stores the current sum of the subarray starting from start pointer and ending at end pointer.
-  we keep on incrementing endpointer while adding the element in thecurrent sumuntil we reach a point where our current running sum is more than required target sum, this basically means that the current subarray whose sum we’ve calculated is not the right answer.
- So now we alter our subarray by moving the startpointer, that is shortening the subarray and hence the current sum in the hope that we achieve the current sum equal to the required target sum.
- At every point we check if our current sum is equal to target sum or not, if this is the case we print our pointers.
- So basically we are altering the subarray by increasing startandendpointers and changing the current sum depending on its value as compared to target sum.

 
 
