Find subarray with given sum - (Handles Negative Numbers) in C++


In this problem, we are given an array arr[] consisting of N integers stored in unsorted order. Our task is to find a subarray with a given sum.

Let's take an example to understand the problem,

Input : arr[] = {2, 5, -1, 4, 6, -9, 5} sum = 14
Output : subarray = {5, -1, 4, 6}

Explanation

Subarray sum = 5 - 1 + 4 + 6 = 14

Solution Approach

A simple solution to the problem is using nested loops. We will loop through the array and using an inner loop, we will find subarray. For each subarray we will find the sum of all elements and compare it with the given sum value. If it's equal, print the subarray. If all elements of the array are traversed, print no such array found.

Algorithm

  • Step 1 − Loop through the array, i -> 0 to (n-1).

    • Step 1.1 − For each element, find the sum of each subarray for all possible subarrays.

    • Step 1.2 − if the sum of current sum array elements is equal to the given subarray, print the subarray.

  • Step 2 − If all elements of the array are traversed and no subarray is found. Print "No subarray with the given sum found!".

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
void printSubArray(int arr[], int i, int j){
   cout<<"{ ";
      for(; i < j; i++)
      cout<<arr[i]<<" ";
   cout<<"}";
}
int findSubArrayWithSum(int arr[], int n, int sum) {
   int currSum;
   for (int i = 0; i < n; i++) {
      currSum = arr[i];
      for (int j = i + 1; j <= n; j++) {
         if (currSum == sum) {
            cout<<"Subarray with given sum : ";
            printSumArray(arr, i, j);
            return 1;
         }
         if (currSum >sum || j == n)
         break;
         currSum = currSum + arr[j];
      }
   }
   cout<<"No subarray found";
   return 0;
}
int main() {
   int arr[] = { 2, 5, -1, 4, 6, -9, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   int sum = 14;
   findSubArrayWithSum(arr, n, sum);
   return 0;
}

Output

Subarray with given sum : { 5 -1 4 6 }

A better approach to solve the problem is using hashmap. The hashmap will store the prefix sum till the current index. And for any index, check if there exists a subarray with sum. We will check if there is a prefix with sum = sum - value.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
void printSubArray(int arr[], int i, int j){
   cout<<"{ ";
      for(; i <= j; i++)
      cout<<arr[i]<<" ";
   cout<<"}";
}
void findSubArrayWithSum(int arr[], int n, int sum) {
   unordered_map<int, int> map;
   int curr_sum = 0;
   for (int i = 0; i < n; i++){
      curr_sum = curr_sum + arr[i];
      if (curr_sum == sum) {
         cout<<"SubArray with the given sum :";
         printSubArray(arr, 0, i);
         return;
      }
      if (map.find(curr_sum - sum) != map.end()) {
         cout<<"SubArray with the given sum : ";
         printSubArray(arr, map[curr_sum - sum] + 1 , i);
         return;
      }
      map[curr_sum] = i;
   }
   cout<<"No subarray found!";
}
int main() {
   int arr[] = { 2, 5, -1, 4, 6, 9, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   int sum = 14;
   findSubArrayWithSum(arr, n, sum);
   return 0;
}

Output

SubArray with the given sum : { 5 -1 4 6 }

Updated on: 25-Jan-2022

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements