881453. Subarray sum

Medium

Subarray Sum

Summary

Given an array of integers, find all subarrays whose sum is equal to a given target value. This problem involves understanding the concept of subarrays and how to efficiently calculate their sums.

Detailed Explanation

To solve this problem, we will use a simple and intuitive approach. We iterate through the array and for each element, we calculate the sum of all subarrays ending at that element. If the calculated sum is equal to the target value, we add it to our result list.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty list result to store the subarrays with the desired sum.
  2. Iterate through the array using two pointers start and end.
  3. Calculate the sum of all elements between start and end (inclusive) and store it in a variable current_sum.
  4. If current_sum is equal to the target value, add the subarray from start to end to the result list.
  5. Move the start pointer one step forward and update current_sum by subtracting the element at the previous start position and adding the current element at the end position.
  6. Repeat steps 3-5 until end reaches the end of the array.

Time complexity: O(n), where n is the length of the array, since we only need to iterate through the array once. Space complexity: O(1), as we only use a constant amount of space to store the result list and other variables.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.ArrayList;
import java.util.List;

public class SubarraySum {
    public static List<List<Integer>> subarraySum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        int start = 0, end = 0, current_sum = 0;
        
        while (end < nums.length) {
            current_sum += nums[end];
            
            if (current_sum == target) {
                List<Integer> subarray = new ArrayList<>();
                for (int i = start; i <= end; i++) {
                    subarray.add(nums[i]);
                }
                result.add(subarray);
            }
            
            while (start <= end && current_sum > target) {
                current_sum -= nums[start];
                start++;
            }
            
            end++;
        }
        
        return result;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.