876268. Subarray with Given Sum

Easy

Subarray with Given Sum

Summary

Given an array of integers and a target sum, find all subarrays that have a sum equal to the given target sum. This problem can be approached using the sliding window technique.

Detailed Explanation

The main idea is to maintain two pointers, start and end, which represent the start and end indices of the current window. Initialize the start pointer at the beginning of the array and set the sum variable to zero.

  1. Iterate through the array using the end pointer.
  2. For each element, add its value to the sum.
  3. If the sum equals the target sum, then we have found a subarray that sums up to the target sum.
  4. To find all such subarrays, maintain a set of unique subarrays and update it with each new subarray found.
  5. Continue the process until the end pointer reaches the end of the array.

The time complexity for this algorithm is O(n), where n is the number of elements in the array. The space complexity is also O(n) for storing all the unique subarrays.

Here is an ASCII art diagram representing the sliding window:

0 1 2 3 4 5
|---|---|
start end

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class SubarrayWithGivenSum {
    public static List<List<Integer>> subarrays(int[] arr, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Map<Integer, Integer> sumIndexMap = new HashMap<>();
        int start = 0;
        int currentSum = 0;

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

            if (currentSum == target) {
                List<Integer> subarray = new ArrayList<>();
                for (int i = start; i <= end; i++) {
                    subarray.add(arr[i]);
                }
                result.add(subarray);
            } else if (sumIndexMap.containsKey(currentSum - target)) {
                start = sumIndexMap.get(currentSum - target) + 1;
                currentSum -= arr[start];
            }

            sumIndexMap.put(currentSum, end);
        }

        return result;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.