Arrays January 13 ,2026

Subarray with Given Sum

Problem Statement

Given an array of integers and a target sum S, find a contiguous subarray whose elements add up to S.

You need to:

  • Print the starting and ending indices
    OR
  • Print the subarray itself (as per problem requirement)

If no such subarray exists, print "No subarray found".

Key Difference from Two Sum

Two SumSubarray Sum
Elements can be anywhereElements must be continuous
Uses hashing directlyUses sliding window / prefix sum
Pair of numbersRange of numbers

Example 1 (Positive Numbers)

Input

arr = [1, 4, 20, 3, 10, 5]
S = 33

Output

Subarray found from index 2 to 4

Explanation

20 + 3 + 10 = 33

Example 2

Input

arr = [1, 2, 3, 7, 5]
S = 12

Output

Subarray found from index 1 to 3

Important Observation

The approach depends on array type:

  1. Only Positive Numbers → Sliding Window
  2. Contains Negative Numbers → Prefix Sum + Hash Map

Approach 1: Sliding Window (For Positive Numbers Only)

Core Idea

  • Expand window by moving end
  • If sum becomes greater than target, shrink window from start
  • Stop when sum equals target

Algorithm

  1. Initialize:
    • start = 0
    • currentSum = 0
  2. Traverse array using end
  3. Add arr[end] to currentSum
  4. While currentSum > S, subtract arr[start] and increment start
  5. If currentSum == S, print indices

Time and Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Below are the Subarray with Given Sum solutions, given one by one, clearly separated.

C Implementation

#include<stdio.h>

int main() {
    int arr[] = {1, 4, 20, 3, 10, 5};
    int n = 6;
    int S = 33;

    int start = 0, currSum = 0;

    for (int end = 0; end < n; end++) {
        currSum += arr[end];

        while (currSum > S && start <= end) {
            currSum -= arr[start];
            start++;
        }

        if (currSum == S) {
            printf("Subarray found from index %d to %d", start, end);
            return 0;
        }
    }

    printf("No subarray found");
    return 0;
}

Output

Subarray found from index 2 to 4

C++ Implementation

#include<iostream>
using namespace std;

int main() {
    int arr[] = {1, 4, 20, 3, 10, 5};
    int n = 6, S = 33;

    int start = 0, currSum = 0;

    for (int end = 0; end < n; end++) {
        currSum += arr[end];

        while (currSum > S && start <= end) {
            currSum -= arr[start++];
        }

        if (currSum == S) {
            cout << "Subarray found from index " << start << " to " << end;
            return 0;
        }
    }

    cout << "No subarray found";
    return 0;
}

Output

Subarray found from index 2 to 4

Java Implementation

public class SubarraySlidingWindow {
    public static void main(String[] args) {
        int[] arr = {1, 4, 20, 3, 10, 5};
        int S = 33;

        int start = 0, currSum = 0;

        for (int end = 0; end < arr.length; end++) {
            currSum += arr[end];

            while (currSum > S && start <= end) {
                currSum -= arr[start++];
            }

            if (currSum == S) {
                System.out.println("Subarray found from index " + start + " to " + end);
                return;
            }
        }

        System.out.println("No subarray found");
    }
}

Python Implementation

arr = [1, 4, 20, 3, 10, 5]
S = 33

start = 0
curr_sum = 0

for end in range(len(arr)):
    curr_sum += arr[end]

    while curr_sum > S and start <= end:
        curr_sum -= arr[start]
        start += 1

    if curr_sum == S:
        print("Subarray found from index", start, "to", end)
        break

JavaScript Implementation

let arr = [1, 4, 20, 3, 10, 5];
let S = 33;

let start = 0, currSum = 0;

for (let end = 0; end < arr.length; end++) {
    currSum += arr[end];

    while (currSum > S && start <= end) {
        currSum -= arr[start++];
    }

    if (currSum === S) {
        console.log("Subarray found from index", start, "to", end);
        break;
    }
}
.

Dry Run (Sliding Window)

arr = [1, 4, 20, 3, 10, 5], S = 33

end=0 → sum=1
end=1 → sum=5
end=2 → sum=25
end=3 → sum=28
end=4 → sum=38 (greater than 33)
Remove arr[0]=1 → sum=37
Remove arr[1]=4 → sum=33 → FOUND

Approach 2: Prefix Sum + Hash Map (Handles Negative Numbers)

When to Use

  • Array contains negative numbers
  • Sliding window fails because sum may decrease unexpectedly

Core Idea

If:

prefixSum[j] - prefixSum[i] = S

Then:

prefixSum[i] = prefixSum[j] - S

Store prefix sums in a hash map.

Algorithm

  1. Initialize:
    • sum = 0
    • Hash map to store prefix sum and index
  2. Traverse array:
    • Add current element to sum
  3. If sum == S, subarray found from 0 to i
  4. If (sum - S) exists in map:
    • Subarray exists from map[sum-S]+1 to i
  5. Store sum in map if not already present

Time and Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

C++ Implementation

#include<iostream>
#include<unordered_map>
using namespace std;

int main() {
    int arr[] = {10, 2, -2, -20, 10};
    int n = 5, S = -10;

    unordered_map<int,int> mp;
    int sum = 0;

    for (int i = 0; i < n; i++) {
        sum += arr[i];

        if (sum == S) {
            cout << "Subarray found from index 0 to " << i;
            return 0;
        }

        if (mp.find(sum - S) != mp.end()) {
            cout << "Subarray found from index "
                 << mp[sum - S] + 1 << " to " << i;
            return 0;
        }

        mp[sum] = i;
    }

    cout << "No subarray found";
    return 0;
}

Output

Subarray found from index 0 to 3

Java Implementation

import java.util.*;

public class SubarrayPrefixSum {
    public static void main(String[] args) {
        int[] arr = {10, 2, -2, -20, 10};
        int S = -10;

        Map<Integer, Integer> map = new HashMap<>();
        int sum = 0;

        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];

            if (sum == S) {
                System.out.println("Subarray found from index 0 to " + i);
                return;
            }

            if (map.containsKey(sum - S)) {
                System.out.println("Subarray found from index " +
                        (map.get(sum - S) + 1) + " to " + i);
                return;
            }

            map.put(sum, i);
        }

        System.out.println("No subarray found");
    }
}

Python Implementation

arr = [10, 2, -2, -20, 10]
S = -10

mp = {}
sum_val = 0

for i, num in enumerate(arr):
    sum_val += num

    if sum_val == S:
        print("Subarray found from index 0 to", i)
        break

    if (sum_val - S) in mp:
        print("Subarray found from index", mp[sum_val - S] + 1, "to", i)
        break

    mp[sum_val] = i

JavaScript Implementation

let arr = [10, 2, -2, -20, 10];
let S = -10;

let map = new Map();
let sum = 0;

for (let i = 0; i < arr.length; i++) {
    sum += arr[i];

    if (sum === S) {
        console.log("Subarray found from index 0 to", i);
        break;
    }

    if (map.has(sum - S)) {
        console.log(
            "Subarray found from index",
            map.get(sum - S) + 1,
            "to",
            i
        );
        break;
    }

    map.set(sum, i);
}

 

Summary

CaseBest Approach
Only positive numbersSliding Window
Negative numbers allowedPrefix Sum + Hash Map

Key Takeaways

  • Subarray means continuous
  • Sliding window is fastest but limited
  • Prefix sum handles all cases
  • Common interview problem after Two Sum & Kadane

Next Problems in the Series

Longest Subarray with Sum K

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com