Subarray with Given Sum

Find subarray with given sum.

Given an array of unsorted integers (Positive integers), We have to write a code to find a subarray whose sum is equal to a given sum.

We have to return subarray indexes (start and end index).

For Example –

  Example 1 :

Input : arr = {10, 2, 4, 7, 5}, sum = 13

Output: {1, 3}

The numbers present from the 1st to 3rd indexes are 2, 4, 7. When we add (2 + 4 + 7) it is 13.

Example 2 :

Input : arr = {1, 4, 20, 3, 10, 5}, sum = 33

  Output: {2, 4}

Example 3 :

  Input : arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, sum = 15

   Output: {0, 4}

Subarray with Given Sum

We will start with the easiest approach and then we will improve our solution to solve this problem efficiently.

Programming Video Tutorials

Subarray with given sum video tutorial

Find Subarray with Given Sum | Brute Force Approach

Let’s start with the easiest approach. The easiest approach to solve this problem is by using two for loops.

We run two for loops to make all possible subarrays sum. In the inner loop, we check if the value of the sum is equal to k. If it is equal we return its indexes. If no subarray is found whose sum is equal to k then we return -1.

Maximum of all subarrays of size k

Minimum size subarray sum

The time complexity of this approach is O(n^2).

Subarray with Given Sum | Two Pointers | Java Code

In our last example, we have solved this problem using two for loops. Let’s think about how we can improve our solution to solve this problem in a single traversal.

In this example, I am explaining two pointer approach for solving this problem in a  single traversal. Two pointer approach is also known as a sliding window.

The idea here is to declare two variables start and end. Initially, Both pointers point at the 0th index. Keep start pointer as it is and start moving end pointer until the value of sum is less than k. If the sum is equal to k then return the indexes.

If the value of sum is greater than k then move the start pointer and also subtract the value present at the start index from the sum variable. Keep repeating this process until the value of the sum is greater than k.

The time complexity of this approach is O(n).

Programming questions on sliding window

Subarray with given sum video tutorial

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.