Given an integer array, find a subarray having a given sum in it.

For example,

Input:  nums[] = {2, 6, 0, 9, 7, 3, 1, 4, 1, 10}, target = 15
Output: {6, 0, 9}
 
 
Input:  nums[] = {0, 5, -7, 1, -4, 7, 6, 1, 4, 1, 10}, target = 15
Output: {1, -4, 7, 6, 1, 4} or {4, 1, 10}
 
 
Input:  nums[] = {0, 5, -7, 1, -4, 7, 6, 1, 4, 1, 10}, target = -3
Output: {1, -4} or {-7, 1, -4, 7}

Practice this problem

1. Using Sliding Window

We can solve this problem by using a sliding window. The idea is to maintain a window that starts from the current element, and the sum of its elements is more than or equal to the given sum. If the current window’s sum becomes less than the given sum, then the window is unstable, and we keep on adding elements to the current window from its right till the window becomes stable again. Print the window if its sum is equal to the given sum at any point. Note this approach will only work with an array of positive integers.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Subarray found [1–3]

Java


Download  Run Code

Output:

Subarray found [1–3]

Python


Download  Run Code

Output:

Sublist found (1, 3)

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.

2. Using Hashing

The above solution will fail for negative numbers. We can use hashing to check if a subarray with the given sum exists in the array or not. The idea is to traverse the given array and maintain the sum of elements seen so far. If the difference between the current sum and the given sum is seen before (i.e., the difference exists in the set), return true as there is at least one subarray with the given sum that ends at the current index; otherwise, insert the sum into the set.

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

C++


Download  Run Code

Output:

Subarray with the given sum exists

Java


Download  Run Code

Output:

Subarray with the given sum exists

Python


Download  Run Code

Output:

Sublist with the given sum exists

We can also print the subarray using hashing. The idea is to use a map instead of a set that stores the ending index of the subarray and its sum.

C++


Download  Run Code

Output:

Subarray found [3–8]

Java


Download  Run Code

Output:

Subarray found [3–8]

Python


Download  Run Code

Output:

Sublist found (3, 8)

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