In this post, we will see how to find subarrays with given sum in an array.

## Problem

Given an Array of non negative Integers and a number. You need to print all the starting and ending indices of Subarrays having their sum equal to the given integer.

For Example :-

**Input**-int[] arr = {2, 3, 6, 4, 9, 0, 11};

int num = 9

**Output-**

starting index : 1, Ending index : 2

starting index : 5, Ending index : 5

starting index : 5, Ending index : 6

Explanation :

[3, 6]

[9],

[9,0]

These all are the subarrays with their sum equal to 9.

## Solution

**Naive Method:**

The basic brute force approach to this problem would be generating all the subarrays of the given array, then loop through the generated subarray and calculate the sum and if this sum is equal to the given sum then printing this subarray as it is the part of our solution.

Now we know, An Array with n elements has **n*(n+1)/2 subarrays**.

**HOW?**

Consider an array,

**int[] arr = {a1, a2, a3, a4…, an};**Subarrays starting with

**0th**index,

a1

a1, a2

a1, a2, a3

a1, a2, a3, a4

.

.

.

a1, a2, a3, a4…, anSubarrays starting with

**1st**index,

a2

a2, a3

a2, a3, a4

.

.

.

a2, a3, a4…, an

subarrays starting with **2nd** index,

a3

a3, a4

.

.

.

a3, a4…, an

Subarrays starting with last i.e. **3rd** index,

a4

.

.

.

a4…, an

Now,

**Total subarrays** = subarrays starting with 0th idx **+** subarrays starting with 1st idx **+**

subarrays starting with 2nd idx + . . . + subarrays starting with nth idx

Sn = n + (n-1) + (n-2) + (n-3) + … + 1

**Sn = n(n+1)/2**

There, generating all the subarrays and calculating the answer will cost us the worst time complexity of O(n(n+1)/2) which is of the order** O(n^2)**.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package Arrays; import java.util.Scanner; public class targetsumSubarr { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int[] arr = new int[scn.nextInt()]; int target = scn.nextInt(); for (int i = 0; i < arr.length; i++) { arr[i] = scn.nextInt(); } solve(arr, target); } public static void solve(int[] arr, int target) { for(int start = 0; start < arr.length; start++) { // initialize the sum of the current subarray to 0. int currSum = 0; for(int end = start; end < arr.length; end++) { // add every element of the current subarray // to the current running sum. currSum += arr[end]; // print the starting and ending indices once we get // subarray with given sum if(currSum == target) { System.out.println("starting index : " + start + ", " + "Ending index : " + end); } } } } } |

**Efficient Approach:**

We can solve this problem in linear time i.e. in **O(n)** as the worst time complexity.

We can maintain two pointers, **start** and **end** pointers which basically represents a subarray and also we have to take a variable which stores the **current sum** of the subarray starting from start pointer and ending at end pointer.

- we keep on incrementing end pointer while adding the element in the current sum until we reach a point where our current running sum is more than required target sum, this basically means that the current subarray whose sum we’ve calculated is not the right answer.
- So now we alter our subarray by moving the start pointer, that is shortening the subarray and hence the current sum in the hope that we achieve the current sum equal to the required target sum.
- At every point we check if our current sum is equal to target sum or not, if this is the case we print our pointers.
- So basically we are altering the subarray by increasing start and end pointers and changing the current sum depending on its value as compared to target sum.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
package org.arpit.java2blog; import java.util.Scanner; public class TargetsumSubarr { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int[] arr = new int[scn.nextInt()]; int target = scn.nextInt(); for (int i = 0; i < arr.length; i++) { arr[i] = scn.nextInt(); } System.out.print("arr[]: {"); for (int i = 0; i < arr.length; i++) { System.out.print(" "+arr[i]); } System.out.println(" }"); solveEfficient(arr, target); } public static void solveEfficient(int[] arr, int target) { int start = 0, end = 0; int currSum = 0; while (start < arr.length && end <= arr.length) { if (currSum == target) { /* as the currSum is equal to target sum, print the * result with end as end-1. * because when we added the element at end we * increased the pointer there only, * so now we need to subtract 1 because the * subarray constituting that sum has * its last pointer one index where end is currently at. */ System.out.println("starting index : " + start + ", " + "Ending index : " + (int) (end - 1)); if (end <= arr.length - 1) { currSum += arr[end]; } end++; } else { /* if the currSum becomes more than required, * we keep on subtracting the start element * until it is less than or equal to required target sum. */ if (currSum > target) { currSum -= arr[start]; start++; } else { /* we add the last element to our * currSum until our * sum becomes greater than or * equal to target sum. */ if (end <= arr.length - 1) { currSum += arr[end]; } end++; } } } } } |

When you run above program, you will get below output:

9

2 3 6 4 9 0 11

arr[]: { 2 3 6 4 9 0 11 }

starting index : 1, Ending index : 2

starting index : 4, Ending index : 4

starting index : 4, Ending index : 5

Doubts? Edits? Suggestions? Comment below. Happy Learning 🙂

#### Latest posts by Ayush Kumar (see all)

- Coin Change Problem in java – December 8, 2018
- Bellman Ford Algorithm in java – November 30, 2018
- Serialize and Deserialize n-ary tree – November 20, 2018

#### Join Our News Letter – Stay Updated

**Subscribe to Awesome Java Content**.