# Find subarray with given sum | Set 2 (Handles Negative Numbers)

Given an unsorted array of integers, find a subarray which adds to a given number. If there are more than one subarrays with the sum as the given number, print any of them.

Examples:

```Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Output: Sum found between indexes 2 and 4
Explantion: Sum of elements between indices
2 and 4 is 20 + 3 + 10 = 33

Input: arr[] = {10, 2, -2, -20, 10}, sum = -10
Output: Sum found between indexes 0 to 3
Explantion: Sum of elements between indices
0 and 3 is 10 + 2 - 2 - 20 = -10

Input: arr[] = {-10, 0, 2, -2, -20, 10}, sum = 20
Output: No subarray with given sum exists
Explantion: There is no subarray with the given sum
```

## Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Note: We have discussed a solution that do not handles negative integers here. In this post, negative integers are also handled.

Approach: The idea is to store the sum of elements of every prefix of the array in a hashmap, i.e for every index store the sum of elements upto that index hashmap. So to check if there is a subarray with sum equal to s, check for every index i, and sum upto that index as x. If there is a prefix with sum equal to x – s, then the subarray with given sum is found.

Algorithm:

1. create a Hashmap (hm) to store key value pair, i.e, key = prefix sum and value = its index and a variable to store the current sum (sum = 0) and the sum of subarray as s
2. Traverse through the array from start to end.
3. For every element update the sum, i.e sum = sum + array[i]
4. If sum is equal to s then print that the subarray with given sum is from 0 to i
5. If there is any key in the HashMap which is equal to sum – s then print that the subarray with given sum is from hm[sum – s] to i
6. Put the sum and index in the hashmap as key-value pair.

Dry-run of the above approach: Implementation:

## C++

 `// C++ program to print subarray with sum as given sum ` `#include ` `using` `namespace` `std; ` ` `  `// Function to print subarray with sum as given sum ` `void` `subArraySum(``int` `arr[], ``int` `n, ``int` `sum) ` `{ ` `    ``// create an empty map ` `    ``unordered_map<``int``, ``int``> map; ` ` `  `    ``// Maintains sum of elements so far ` `    ``int` `curr_sum = 0; ` ` `  `    ``for` `(``int` `i = 0; i < n; i++) ` `    ``{ ` `        ``// add current element to curr_sum ` `        ``curr_sum = curr_sum + arr[i]; ` ` `  `        ``// if curr_sum is equal to target sum ` `        ``// we found a subarray starting from index 0 ` `        ``// and ending at index i ` `        ``if` `(curr_sum == sum) ` `        ``{ ` `            ``cout << ``"Sum found between indexes "` `                 ``<< 0 << ``" to "` `<< i << endl; ` `            ``return``; ` `        ``} ` ` `  `        ``// If curr_sum - sum already exists in map ` `        ``// we have found a subarray with target sum ` `        ``if` `(map.find(curr_sum - sum) != map.end()) ` `        ``{ ` `            ``cout << ``"Sum found between indexes "` `                 ``<< map[curr_sum - sum] + 1 ` `                 ``<< ``" to "` `<< i << endl; ` `            ``return``; ` `        ``} ` ` `  `        ``map[curr_sum] = i; ` `    ``} ` ` `  `    ``// If we reach here, then no subarray exists ` `    ``cout << ``"No subarray with given sum exists"``; ` `} ` ` `  `// Driver program to test above function ` `int` `main() ` `{ ` `    ``int` `arr[] = {10, 2, -2, -20, 10}; ` `    ``int` `n = ``sizeof``(arr)/``sizeof``(arr); ` `    ``int` `sum = -10; ` ` `  `    ``subArraySum(arr, n, sum); ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java program to print subarray with sum as given sum ` `import` `java.util.*; ` ` `  `class` `GFG { ` ` `  `    ``public` `static` `void` `subArraySum(``int``[] arr, ``int` `n, ``int` `sum) { ` `        ``//cur_sum to keep track of cummulative sum till that point ` `        ``int` `cur_sum = ``0``; ` `        ``int` `start = ``0``; ` `        ``int` `end = -``1``; ` `        ``HashMap hashMap = ``new` `HashMap<>(); ` ` `  `        ``for` `(``int` `i = ``0``; i < n; i++) { ` `            ``cur_sum = cur_sum + arr[i]; ` `            ``//check whether cur_sum - sum = 0, if 0 it means ` `            ``//the sub array is starting from index 0- so stop ` `            ``if` `(cur_sum - sum == ``0``) { ` `                ``start = ``0``; ` `                ``end = i; ` `                ``break``; ` `            ``} ` `            ``//if hashMap already has the value, means we already  ` `            ``// have subarray with the sum - so stop ` `            ``if` `(hashMap.containsKey(cur_sum - sum)) { ` `                ``start = hashMap.get(cur_sum - sum) + ``1``; ` `                ``end = i; ` `                ``break``; ` `            ``} ` `            ``//if value is not present then add to hashmap ` `            ``hashMap.put(cur_sum, i); ` ` `  `        ``} ` `        ``// if end is -1 : means we have reached end without the sum ` `        ``if` `(end == -``1``) { ` `            ``System.out.println(``"No subarray with given sum exists"``); ` `        ``} ``else` `{ ` `            ``System.out.println(``"Sum found between indexes "`  `                            ``+ start + ``" to "` `+ end); ` `        ``} ` ` `  `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `main(String[] args) { ` `        ``int``[] arr = {``10``, ``2``, -``2``, -``20``, ``10``}; ` `        ``int` `n = arr.length; ` `        ``int` `sum = -``10``; ` `        ``subArraySum(arr, n, sum); ` ` `  `    ``} ` `} `

## Python3

 `# Python3 program to print subarray with sum as given sum  ` ` `  `# Function to print subarray with sum as given sum  ` `def` `subArraySum(arr, n, ``Sum``):  ` `  `  `    ``# create an empty map  ` `    ``Map` `=` `{}  ` `   `  `    ``# Maintains sum of elements so far  ` `    ``curr_sum ``=` `0`  `   `  `    ``for` `i ``in` `range``(``0``,n):  ` `      `  `        ``# add current element to curr_sum  ` `        ``curr_sum ``=` `curr_sum ``+` `arr[i]  ` `   `  `        ``# if curr_sum is equal to target sum  ` `        ``# we found a subarray starting from index 0  ` `        ``# and ending at index i  ` `        ``if` `curr_sum ``=``=` `Sum``:  ` `          `  `            ``print``(``"Sum found between indexes 0 to"``, i) ` `            ``return`  `          `  `   `  `        ``# If curr_sum - sum already exists in map  ` `        ``# we have found a subarray with target sum  ` `        ``if` `(curr_sum ``-` `Sum``) ``in` `Map``:  ` `          `  `            ``print``(``"Sum found between indexes"``, \ ` `                   ``Map``[curr_sum ``-` `Sum``] ``+` `1``, ``"to"``, i)  ` `             `  `            ``return`  `   `  `        ``Map``[curr_sum] ``=` `i  ` `   `  `    ``# If we reach here, then no subarray exists  ` `    ``print``(``"No subarray with given sum exists"``)  ` `  `  `   `  `# Driver program to test above function  ` `if` `__name__ ``=``=` `"__main__"``:  ` `  `  `    ``arr ``=` `[``10``, ``2``, ``-``2``, ``-``20``, ``10``]  ` `    ``n ``=` `len``(arr)  ` `    ``Sum` `=` `-``10`  `   `  `    ``subArraySum(arr, n, ``Sum``)  ` `   `  `# This code is contributed by Rituraj Jain `

## C#

 `using` `System; ` `using` `System.Collections.Generic; ` ` `  `// C# program to print subarray with sum as given sum  ` ` `  `public` `class` `GFG ` `{ ` ` `  `    ``public` `static` `void` `subArraySum(``int``[] arr, ``int` `n, ``int` `sum) ` `    ``{ ` `        ``//cur_sum to keep track of cummulative sum till that point  ` `        ``int` `cur_sum = 0; ` `        ``int` `start = 0; ` `        ``int` `end = -1; ` `        ``Dictionary<``int``, ``int``> hashMap = ``new` `Dictionary<``int``, ``int``>(); ` ` `  `        ``for` `(``int` `i = 0; i < n; i++) ` `        ``{ ` `            ``cur_sum = cur_sum + arr[i]; ` `            ``//check whether cur_sum - sum = 0, if 0 it means  ` `            ``//the sub array is starting from index 0- so stop  ` `            ``if` `(cur_sum - sum == 0) ` `            ``{ ` `                ``start = 0; ` `                ``end = i; ` `                ``break``; ` `            ``} ` `            ``//if hashMap already has the value, means we already   ` `            ``// have subarray with the sum - so stop  ` `            ``if` `(hashMap.ContainsKey(cur_sum - sum)) ` `            ``{ ` `                ``start = hashMap[cur_sum - sum] + 1; ` `                ``end = i; ` `                ``break``; ` `            ``} ` `            ``//if value is not present then add to hashmap  ` `            ``hashMap[cur_sum] = i; ` ` `  `        ``} ` `        ``// if end is -1 : means we have reached end without the sum  ` `        ``if` `(end == -1) ` `        ``{ ` `            ``Console.WriteLine(``"No subarray with given sum exists"``); ` `        ``} ` `        ``else` `        ``{ ` `            ``Console.WriteLine(``"Sum found between indexes "` `+ start + ``" to "` `+ end); ` `        ``} ` ` `  `    ``} ` ` `  `    ``// Driver code  ` `    ``public` `static` `void` `Main(``string``[] args) ` `    ``{ ` `        ``int``[] arr = ``new` `int``[] {10, 2, -2, -20, 10}; ` `        ``int` `n = arr.Length; ` `        ``int` `sum = -10; ` `        ``subArraySum(arr, n, sum); ` ` `  `    ``} ` `} ` ` `  `// This code is contributed by Shrikant13 `

Output:

```Sum found between indexes 0 to 3
```

Complexity Analysis:

• Time complexity: O(N).
If hashing is performed with the help of an array then this the time complexity. In case the elements cannot be hashed in an array a hash map can also be used as shown in the above code.
• Auxiliary space: O(n).
As a HashMap is needed, this takes a linear space.

Find subarray with given sum with negatives allowed in constant space

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

70

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
{"ft_lang_label":"__label__en","ft_lang_prob":0.72718525,"math_prob":0.98407066,"size":8936,"snap":"2020-45-2020-50","text_gpt3_token_len":2553,"char_repetition_ratio":0.15797134,"word_repetition_ratio":0.2793867,"special_character_ratio":0.30572963,"punctuation_ratio":0.12644342,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9999391,"pos_list":[0,1,2],"im_url_duplicate_count":[null,10,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-10-28T12:17:26Z\",\"WARC-Record-ID\":\"<urn:uuid:d254d09c-7d18-4a68-a39a-7e960fe7a981>\",\"Content-Length\":\"151768\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:a19bd218-c01d-46ef-952a-294f25a9d023>\",\"WARC-Concurrent-To\":\"<urn:uuid:74c67288-fbba-462b-9236-4bcd917b6305>\",\"WARC-IP-Address\":\"23.221.74.65\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/find-subarray-with-given-sum-in-array-of-integers/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:I6YSON2ZPOER64A4AE3UWKWDSALLSTK6\",\"WARC-Block-Digest\":\"sha1:EBGF54ZRS37ISMMOW62GMGMJTVWDE62Z\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-45/CC-MAIN-2020-45_segments_1603107898499.49_warc_CC-MAIN-20201028103215-20201028133215-00213.warc.gz\"}"}