712151. Binary subarray with sum

Medium

Binary Subarray with Sum

Summary

Given an array of binary integers, find all subarrays that sum up to a specific target value. The problem involves using a sliding window approach and iterating through the array to identify these subarrays.

Detailed Explanation

To solve this problem, we'll employ a two-pointer technique, also known as the sliding window method. We'll initialize two pointers, start and end, at the beginning of the array. Our goal is to find all subarrays that sum up to the target value.

Here's a step-by-step breakdown:

  1. Initialize variables:
    • start: 0 (index of the first element)
    • end: 0 (index of the last element)
    • current_sum: 0 (sum of elements in the current window)
    • target: target sum value
  2. Iterate through the array:
    • While end is less than the array length:
      • Add the element at index end to current_sum
      • If current_sum equals the target, add the subarray [start, end] to our result list
      • If current_sum exceeds the target, subtract the element at index start from current_sum and increment start
  3. Continue iterating until end reaches the array length

To illustrate this process, consider an example:

Array: [1, 0, 1, 0, 1, 1]
Target: 2
Result: [[1, 0], [1, 1]]

In this case, we start with start and end at index 0. We add the elements to current_sum, and when it equals the target (2), we add the subarray [1, 0] to our result list. As we move forward, current_sum exceeds the target; so, we subtract the element at index 0 from current_sum and increment start. The process continues until we reach the end of the array.

Optimized Solutions

Java

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

public class BinarySubarray {
    public static List<List<Integer>> binarySubarraysWithSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        int start = 0, end = 0, currentSum = 0;
        
        while (end < nums.length) {
            currentSum += nums[end];
            if (currentSum == target) {
                result.add(List.of(start, end));
                currentSum -= nums[start];
                start++;
            } else if (currentSum > target) {
                currentSum -= 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.