Given an integer array, find subarrays with a given sum in it.

For example,

Input:
 
nums[] = { 3, 4, -7, 1, 3, 3, 1, -4 }
target = 7
 
Output:
 
Subarrays with the given sum are
 
{ 3, 4 }
{ 3, 4, -7, 1, 3, 3 }
{ 1, 3, 3 }
{ 3, 3, 1 }

Practice this problem

Please note that the problem specifically targets subarrays that are contiguous (i.e., occupy consecutive positions) and inherently maintains the order of elements.

1. Brute-Force Solution

A simple solution is to consider all subarrays and calculate the sum of their elements. If the sum of the subarray is equal to the given sum, print it. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

[0…1] —— { 3 4 }
[0…5] —— { 3 4 -7 1 3 3 }
[3…5] —— { 1 3 3 }
[4…6] —— { 3 3 1 }

Java


Download  Run Code

Output:

[3, 4]
[3, 4, -7, 1, 3, 3]
[1, 3, 3]
[3, 3, 1]

Python


Download  Run Code

Output:

[3, 4]
[3, 4, -7, 1, 3, 3]
[1, 3, 3]
[3, 3, 1]

This approach takes O(n3) time as the subarray sum is calculated in O(1) time for each of n2 subarrays of an array of size n, and it takes O(n) time to print a subarray.

2. Hashing

We can also use hashing to find subarrays with the given sum in an array by using a map of lists or a multimap for storing the end index of all subarrays having a given sum. The idea is to traverse the given array and maintain the sum of elements seen so far. At any index, i, let k be the difference between the sum of elements seen so far and the given sum. If key k is present on the map, at least one subarray has the given sum ending at the current index i, and we print all such subarrays.

Following is the implementation of the above algorithm in C++, Java, and Python:

C++


Download  Run Code

Output:

[0…1] —— { 3 4 }
[0…5] —— { 3 4 -7 1 3 3 }
[3…5] —— { 1 3 3 }
[4…6] —— { 3 3 1 }

Java


Download  Run Code

Output:

[3, 4]
[3, 4, -7, 1, 3, 3]
[1, 3, 3]
[3, 3, 1]

Python


Download  Run Code

Output:

[3, 4] [3, 4, -7, 1, 3, 3] [1, 3, 3] [3, 3, 1]

The time complexity of the above solution is O(n2) and requires O(n) extra space, where n is the size of the input.