Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array which adds to a given number S and return the left and right index of that subarray.
In case of multiple subarrays, return the subarray indexes which comes first on moving from left to right.
Subarray with given sum Solution In Java:
class Solution { //Function to find a continuous sub-array which adds up to a given number. static ArrayList<Integer> subarraySum(int[] arr, int n, int s) { // Your code here ArrayList<Integer> al=new ArrayList<Integer>(); int i=1; int j=0; int sum=arr[0]; for(i=1;i<=n;i++){ while(sum>s&& j<i-1){ sum-=arr[j]; j++; } if(sum==s) { al.add(j+1); al.add(i); break; } if(i<n){ sum+=arr[i]; } } if(al.size()==0) al.add(-1); return al; } }
Disclaimer: This problem(Subarray with given Sum) is originally created by GeeksforGeeks. Codesagar only provides a solution for it. This solution is only for Educational and learning purposes.