Subarray with given sum | Practice | GeeksforGeeks

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.
In case of multiple subarrays, return the subarray which comes first on moving from left to right.
 
Example 1:
Input:
N = 5, S = 12
A[] = {1,2,3,7,5}
Output: 2 4
Explanation: The sum of elements 
from 2nd position to 4th position 
is 12.
 
Example 2:
Input:
N = 10, S = 15
A[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1 5
Explanation: The sum of elements 
from 1st position to 5th position
is 15.

 
Your Task:
You don't need to read input or print anything. The task is to complete the function subarraySum() which takes arr, N and S as input parameters and returns an arraylist containing the starting and ending positions of the first such occurring subarray from the left where sum equals to S. The two indexes in the array should be according to 1-based indexing. If no such subarray is found, return an array consisting only one element that is -1.
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
 
Constraints:
1 <= N <= 105
1 <= Ai <= 109
 
0
abhinayabhi141in 7 hours
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> list=new ArrayList<>();     int sum = 0 , index = 0, count = 0;     for(int i = index ; i < n ; i++){         sum += arr[i];         if(sum == s){             list.add(index+1);             list.add(i+1);             count++;             break;         }         if(sum > s){             i=index++;             sum=0;         }     }     if(count != 0){         return list;     }     else{         list.add(-1);         return list;     }   }}
0
royabhisek
This comment was deleted.
0
parvezrahaman1219in 4 hours
// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;

class Main{
	public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

        for (int i = 0; i < t; i++) {
            int n = sc.nextInt();
            int s = sc.nextInt();

            int[] m = new int[n];
            for (int j = 0; j < n; j++) {
                m[j] = sc.nextInt();
            }
            
            Solution obj = new Solution();
            ArrayList<Integer> res = obj.subarraySum(m, n, s);
            for(int ii = 0;ii<res.size();ii++)
                System.out.print(res.get(ii) + " ");
            System.out.println();
        }
    }

}// } Driver Code Ends


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) 
    {
        //in this code 62 tc pass cz of time limit
        /*int i,j,sum,eidx;
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for(i=0;i<n;i++){
            sum=arr[i];
            for(j=i+1;j<=n;j++){
                if(sum==s){
                    eidx=j;
                    numbers.add(i+1);
                    numbers.add(eidx);
                }
                if(numbers.size()>0 || sum>s || j==n){
                   break; 
                }
                sum+=arr[j];
            }
        }
        if(numbers.isEmpty()){
            numbers.add(-1);
        }
        return numbers;*/
        
        //in this code 72 tc pass cz of time limit
        int i,sum=0,index=0;
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for(i=index;i<n;i++){
            sum+=arr[i];
            if(sum==s){
                numbers.add(index+1);
                numbers.add(i+1);
                break;
            }
            if(sum>s){
                i=index++;
                sum=0;
            }
        }
        if(numbers.size()!=0){
            return numbers;
        }
        else{
            numbers.add(-1);
            return numbers;
        }
    }
}
0
shivampathak12aps
This comment was deleted.
0
akarshbarar5 hours ago
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> list=new ArrayList<>();      int sum = 0 , index = 0, count = 0;      for(int i = index ; i < n ; i++){          sum += arr[i];          if(sum == s){              list.add(index+1);              list.add(i+1);              count++;              break;          }          if(sum > s){              i=index++;              sum=0;          }      }      if(count != 0){          return list;      }      else{          list.add(-1);          return list;      }        }} 
0
saikriteja13 hours ago
C++ Solution
vector<int> subarraySum(int arr[], int n, long long s)
    {
       int i=0,j=0;
       long long sum=arr[0];
       vector<int> v;
       for(int i=0;i<n;i++){
           if(sum<s){
            j++;
            sum+=arr[j];
            i--;
           }
           else if(sum>s){
               j=i+1;
               sum=arr[j];
           }
           else if(sum==s){
            v.push_back(i+1);
            v.push_back(j+1);
            return v;
           }
       }
       v.push_back(-1);
       return v;
    }
0
alycentra14 hours ago
I don't why it turn error 
class Solution:

    def subArraySum(self,arr, n, s):

        

        

       #Write your code here

        for i in range(n):

            sum1=0



            x=i+1

            while x<=n :

                

                sum1=sum(arr[i:x])

                if sum1 == s:

                    return str(i+1)+ str(x) 

                

                else:    

                    x+=1

        return -1         



 
-1
prateekgoyal217 hours ago
How do we think through this problem? Explained simply here:- 
0
siddharthsingh11801 day ago
class Solution:   def subArraySum(self,arr, n, s):       i=0       j=0       sum=0       for i in range(n):           sum=arr[i]           j=i+1           while j<=n:               if sum==s:                   return [i+1,j]               elif sum>s:                   sum-=arr[i]                   i=i+1                              else:                   sum+=arr[j]                   j=j+1                                         
-10
ndenkala2 days ago
python
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.