GFG App
Open App
Browser
Continue

# Javascript Program For Finding Subarray With Given Sum – Set 1 (Nonnegative Numbers)

Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number.Â
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 = 33

Input: 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 = 7

Input: arr[] = {1, 4}, sum = 0
Output: No subarray found
There is no subarray with 0 sum

There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray.Â

Simple 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:Â Â

1. Traverse the array from start to end.
2. 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.
3. For every index in inner loop update sum = sum + array[j]
4. If the sum is equal to the given sum then print the subarray.

## Javascript



Output :

Sum found between indexes 1 and 4

Complexity 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:Â Â

1. Create three variables, l=0, sum = 0
2. Traverse the array from start to end.
3. Update the variable sum by adding current element, sum = sum + array[i]
4. If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.
5. If the sum is equal to given sum, print the subarray and break the loop.

## Javascript



Output :

Sum found between indexes 1 and 4

Complexity Analysis:Â Â

• Time Complexity : O(n).Â
Only one traversal of the array is required. So the time complexity is O(n).
• Space Complexity: O(1).Â
As constant extra space is required.

Please refer complete article on Find subarray with given sum | Set 1 (Nonnegative Numbers) for more details!

My Personal Notes arrow_drop_up