Find subarray with given sum | Set 1 (Nonnegative Numbers)
- Difficulty Level : Medium
- Last Updated : 15 Jul, 2022
Given an unsorted array arr of nonnegative integers and an integer sum, find a continuous subarray which adds to a given sum. There may be more than one subarrays with sum as the given sum, print first such subarray.
Examples :
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Output: Sum found between indexes 2 and 4
Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Output: Sum found between indexes 1 and 4
Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7Input: arr[] = {1, 4}, sum = 0
Output: No subarray found
There is no subarray with 0 sumRecommended PracticeSimple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.
Algorithm:
- Traverse the array from start to end.
- From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.
- For every index in inner loop update sum = sum + array[j]
- If the sum is equal to the given sum then print the subarray.
C++
/* A simple program to print subarraywith sum as given sum */#include <bits/stdc++.h>usingnamespacestd;/* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */intsubArraySum(intarr[],intn,intsum){intcurr_sum, i, j;// Pick a starting pointfor(i = 0; i < n; i++) {curr_sum = arr[i];// try all subarrays starting with 'i'for(j = i + 1; j <= n; j++) {if(curr_sum == sum) {cout <<"Sum found between indexes "<< i <<" and "<< j - 1;return1;}if(curr_sum > sum || j == n)break;curr_sum = curr_sum + arr[j];}}cout <<"No subarray found";return0;}// Driver Codeintmain(){intarr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };intn =sizeof(arr) /sizeof(arr[0]);intsum = 23;subArraySum(arr, n, sum);return0;}// This code is contributed// by rathbhupendraC
/* A simple program to printsubarray with sum as given sum */#include <stdio.h>/* Returns true if the there is a subarrayof arr[] with a sum equal to 'sum'otherwise returns false. Also, printsthe result */intsubArraySum(intarr[],intn,intsum){intcurr_sum, i, j;// Pick a starting pointfor(i = 0; i < n; i++) {curr_sum = arr[i];// try all subarrays starting with 'i'for(j = i + 1; j <= n; j++) {if(curr_sum == sum) {printf("Sum found between indexes %d and %d",i, j - 1);return1;}if(curr_sum > sum || j == n)break;curr_sum = curr_sum + arr[j];}}printf("No subarray found");return0;}// Driver program to test above functionintmain(){intarr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };intn =sizeof(arr) /sizeof(arr[0]);intsum = 23;subArraySum(arr, n, sum);return0;}Java
classSubarraySum {/* Returns true if the there is asubarray of arr[] with a sum equal to'sum' otherwise returns false.Also, prints the result */intsubArraySum(intarr[],intn,intsum){intcurr_sum, i, j;// Pick a starting pointfor(i =0; i < n; i++) {curr_sum = arr[i];// try all subarrays starting with 'i'for(j = i +1; j <= n; j++) {if(curr_sum == sum) {intp = j -1;System.out.println("Sum found between indexes "+ i+" and "+ p);return1;}if(curr_sum > sum || j == n)break;curr_sum = curr_sum + arr[j];}}System.out.println("No subarray found");return0;}publicstaticvoidmain(String[] args){SubarraySum arraysum =newSubarraySum();intarr[] = {15,2,4,8,9,5,10,23};intn = arr.length;intsum =23;arraysum.subArraySum(arr, n, sum);}}// This code has been contributed by Mayank Jaiswal(mayank_24)Python3
# Returns true if the# there is a subarray# of arr[] with sum# equal to 'sum'# otherwise returns# false. Also, prints# the resultdefsubArraySum(arr, n, sum_):# Pick a starting# pointforiinrange(n):curr_sum=arr[i]# try all subarrays# starting with 'i'j=i+1whilej <=n:ifcurr_sum==sum_:("Sum found between")("indexes % d and % d"%( i, j-1))return1ifcurr_sum > sum_orj==n:breakcurr_sum=curr_sum+arr[j]j+=1("No subarray found")return0# Driver programarr=[15,2,4,8,9,5,10,23]n=len(arr)sum_=23subArraySum(arr, n, sum_)# This code is Contributed by shreyanshi_arun.C#
// C# code to Find subarray// with given sumusingSystem;classGFG {// Returns true if the there is a// subarray of arr[] with sum// equal to 'sum' otherwise returns// false. Also, prints the resultintsubArraySum(int[] arr,intn,intsum){intcurr_sum, i, j;// Pick a starting pointfor(i = 0; i < n; i++) {curr_sum = arr[i];// try all subarrays// starting with 'i'for(j = i + 1; j <= n; j++) {if(curr_sum == sum) {intp = j - 1;Console.Write("Sum found between "+"indexes "+ i +" and "+ p);return1;}if(curr_sum > sum || j == n)break;curr_sum = curr_sum + arr[j];}}Console.Write("No subarray found");return0;}// Driver CodepublicstaticvoidMain(){GFG arraysum =newGFG();int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 };intn = arr.Length;intsum = 23;arraysum.subArraySum(arr, n, sum);}}// This code has been contributed// by nitin mittalPHP
<?php// A simple program to print subarray// with sum as given sum/* Returns true if the there isa subarray of arr[] withsum equal to 'sum'otherwise returns false.Also, prints the result */functionsubArraySum($arr,$n,$sum){$curr_sum;$i;$j;// Pick a starting pointfor($i= 0;$i<$n;$i++){$curr_sum=$arr[$i];// try all subarrays// starting with 'i'for($j=$i+ 1;$j<=$n;$j++){if($curr_sum==$sum){echo"Sum found between indexes ",$i," and ",$j-1 ;return1;}if($curr_sum>$sum||$j==$n)break;$curr_sum=$curr_sum+$arr[$j];}}echo"No subarray found";return0;}// Driver Code$arr=array(15, 2, 4, 8, 9, 5, 10, 23);$n= sizeof($arr);$sum= 23;subArraySum($arr,$n,$sum);return0;// This code is contributed by AJit?>Javascript
<script>/* A simple program to print subarraywith sum as given sum *//* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */functionsubArraySum(arr, n, sum){let curr_sum=0;// Pick a starting pointfor(let i = 0; i < n; i++) {curr_sum = arr[i];// try all subarrays starting with 'i'for(let j = i + 1; j <= n; j++) {if(curr_sum == sum) {document.write("Sum found between indexes "+i+" and "+(j - 1));return;}if(curr_sum > sum || j == n)break;curr_sum = curr_sum + arr[j];}}document.write("No subarray found");return;}// Driver Codelet arr= [15, 2, 4, 8, 9, 5, 10, 23];let n = arr.length;let sum = 23;subArraySum(arr, n, sum);</script>OutputSum found between indexes 1 and 4Complexity Analysis:
- Time Complexity: O(n^2) in worst case.
Nested loop is used to traverse the array so the time complexity is O(n^2)- Space Complexity: O(1).
As constant extra space is required.Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.
Algorithm:
- Create two variables, l=0, sum = 0
- Traverse the array from start to end.
- Update the variable sum by adding current element, sum = sum + array[i]
- If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.
- If the sum is equal to given sum, print the subarray and break the loop.
C++
/* An efficient program to printsubarray with sum as given sum */#include <iostream>usingnamespacestd;/* Returns true if the there is a subarray ofarr[] with a sum equal to 'sum' otherwisereturns false. Also, prints the result */intsubArraySum(intarr[],intn,intsum){/* Initialize curr_sum as value offirst element and starting point as 0 */intcurr_sum = arr[0], start = 0, i;/* Add elements one by one to curr_sum andif the curr_sum exceeds the sum,then remove starting element */for(i = 1; i <= n; i++) {// If curr_sum exceeds the sum,// then remove the starting elementswhile(curr_sum > sum && start < i - 1) {curr_sum = curr_sum - arr[start];start++;}// If curr_sum becomes equal to sum,// then return trueif(curr_sum == sum) {cout <<"Sum found between indexes "<< start <<" and "<< i - 1;return1;}// Add this element to curr_sumif(i < n)curr_sum = curr_sum + arr[i];}// If we reach here, then no subarraycout <<"No subarray found";return0;}// Driver Codeintmain(){intarr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };intn =sizeof(arr) /sizeof(arr[0]);intsum = 23;subArraySum(arr, n, sum);return0;}// This code is contributed by SHUBHAMSINGH10C
/* An efficient program to printsubarray with sum as given sum */#include <stdio.h>/* Returns true if the there is asubarray of arr[] with a sumequal to 'sum' otherwise returnsfalse. Also, prints the result */intsubArraySum(intarr[],intn,intsum){/* Initialize curr_sum asvalue of first element andstarting point as 0 */intcurr_sum = arr[0], start = 0, i;/* Add elements one by one tocurr_sum and if the curr_sumexceeds the sum, then removestarting element */for(i = 1; i <= n; i++) {// If curr_sum exceeds the sum,// then remove the starting elementswhile(curr_sum > sum && start < i - 1) {curr_sum = curr_sum - arr[start];start++;}// If curr_sum becomes equal to sum,// then return trueif(curr_sum == sum) {printf("Sum found between indexes %d and %d",start, i - 1);return1;}// Add this element to curr_sumif(i < n)curr_sum = curr_sum + arr[i];}// If we reach here, then no subarrayprintf("No subarray found");return0;}// Driver program to test above functionintmain(){intarr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };intn =sizeof(arr) /sizeof(arr[0]);intsum = 23;subArraySum(arr, n, sum);return0;}Java
classSubarraySum {/* Returns true if the there isa subarray of arr[] with sum equal to'sum' otherwise returns false.Also, prints the result */intsubArraySum(intarr[],intn,intsum){intcurr_sum = arr[0], start =0, i;// Pick a starting pointfor(i =1; i <= n; i++) {// If curr_sum exceeds the sum,// then remove the starting elementswhile(curr_sum > sum && start < i -1) {curr_sum = curr_sum - arr[start];start++;}// If curr_sum becomes equal to sum,// then return trueif(curr_sum == sum) {intp = i -1;System.out.println("Sum found between indexes "+ start+" and "+ p);return1;}// Add this element to curr_sumif(i < n)curr_sum = curr_sum + arr[i];}System.out.println("No subarray found");return0;}publicstaticvoidmain(String[] args){SubarraySum arraysum =newSubarraySum();intarr[] = {15,2,4,8,9,5,10,23};intn = arr.length;intsum =23;arraysum.subArraySum(arr, n, sum);}}// This code has been contributed by Mayank Jaiswal(mayank_24)Python3
# An efficient program# to print subarray# with sum as given sum# Returns true if the# there is a subarray# of arr[] with sum# equal to 'sum'# otherwise returns# false. Also, prints# the result.defsubArraySum(arr, n, sum_):# Initialize curr_sum as# value of first element# and starting point as 0curr_sum=arr[0]start=0# Add elements one by# one to curr_sum and# if the curr_sum exceeds# the sum, then remove# starting elementi=1whilei <=n:# If curr_sum exceeds# the sum, then remove# the starting elementswhilecurr_sum > sum_andstart < i-1:curr_sum=curr_sum-arr[start]start+=1# If curr_sum becomes# equal to sum, then# return trueifcurr_sum==sum_:("Sum found between indexes")("% d and % d"%(start, i-1))return1# Add this element# to curr_sumifi < n:curr_sum=curr_sum+arr[i]i+=1# If we reach here,# then no subarray("No subarray found")return0# Driver programarr=[15,2,4,8,9,5,10,23]n=len(arr)sum_=23subArraySum(arr, n, sum_)# This code is Contributed by shreyanshi_arun.C#
// An efficient C# program to print// subarray with sum as given sumusingSystem;classGFG {// Returns true if the// there is a subarray of// arr[] with sum equal to// 'sum' otherwise returns false.// Also, prints the resultintsubArraySum(int[] arr,intn,intsum){intcurr_sum = arr[0],start = 0, i;// Pick a starting pointfor(i = 1; i <= n; i++) {// If curr_sum exceeds// the sum, then remove// the starting elementswhile(curr_sum > sum && start < i - 1) {curr_sum = curr_sum - arr[start];start++;}// If curr_sum becomes equal to// sum, then return trueif(curr_sum == sum) {intp = i - 1;Console.WriteLine("Sum found between "+"indexes "+ start +" and "+ p);return1;}// Add this element to curr_sumif(i < n)curr_sum = curr_sum + arr[i];}Console.WriteLine("No subarray found");return0;}// Driver codepublicstaticvoidMain(){GFG arraysum =newGFG();int[] arr =newint[] { 15, 2, 4, 8,9, 5, 10, 23 };intn = arr.Length;intsum = 23;arraysum.subArraySum(arr, n, sum);}}// This code has been contributed by KRV.PHP
<?php/* An efficient program to printsubarray with sum as given sum *//* Returns true if the there is asubarray of arr[] with sum equalto 'sum' otherwise returns false.Also, prints the result */functionsubArraySum($arr,$n,$sum){/* Initialize curr_sum asvalue of first elementand starting point as 0 */$curr_sum=$arr[0];$start= 0;$i;/* Add elements one by one tocurr_sum and if the curr_sumexceeds the sum, then removestarting element */for($i= 1;$i<=$n;$i++){// If curr_sum exceeds the sum,// then remove the starting elementswhile($curr_sum>$sumand$start<$i- 1){$curr_sum=$curr_sum-$arr[$start];$start++;}// If curr_sum becomes equal// to sum, then return trueif($curr_sum==$sum){echo"Sum found between indexes"," ",$start," ","and "," ",$i- 1;return1;}// Add this element// to curr_sumif($i<$n)$curr_sum=$curr_sum+$arr[$i];}// If we reach here,// then no subarrayecho"No subarray found";return0;}// Driver Code$arr=array(15, 2, 4, 8,9, 5, 10, 23);$n=count($arr);$sum= 23;subArraySum($arr,$n,$sum);// This code has been// contributed by anuj_67.?>Javascript
<script>/* Returns true if the there isa subarray of arr[] with sum equal to'sum' otherwise returns false.Also, prints the result */functionsubArraySum(arr,n,sum){let curr_sum = arr[0], start = 0, i;// Pick a starting pointfor(i = 1; i <= n; i++) {// If curr_sum exceeds the sum,// then remove the starting elementswhile(curr_sum > sum && start < i - 1) {curr_sum = curr_sum - arr[start];start++;}// If curr_sum becomes equal to sum,// then return trueif(curr_sum == sum) {let p = i - 1;document.write("Sum found between indexes "+ start+" and "+ p+"<br>");return1;}// Add this element to curr_sumif(i < n)curr_sum = curr_sum + arr[i];}document.write("No subarray found");return0;}let arr=[15, 2, 4, 8, 9, 5, 10, 23 ];let n = arr.length;let sum = 23;subArraySum(arr, n, sum);// This code is contributed by unknown2108</script>OutputSum found between indexes 1 and 4Complexity Analysis:
- Time Complexity: O(n).
- The Array is traversed only once to insert elements into the window. It will take O(N) time
- The Array is traversed again once to remove elements from the window. It will also take O(N) time.
- So the total time will be O(N) + O(N) = O(2*N), which is similar to O(N)
- Space Complexity: O(1).
As constant extra space is required.The above solution doesn’t handle negative numbers. We can use hashing to handle negative numbers. See below set 2.
- Find subarray with given sum | Set 2 (Handles Negative Numbers)
- Find subarray with given sum with negatives allowed in constant space
My Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :Article Tags :



.png)
.png)