Subarray Fuel Capacity Matches — Problem Statement & Solution Guide

ArraysMediumPattern recognition and subarray formation
TimeO(n+K)
|
SpaceO(n)

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Arrays and solve the Subarray Fuel Capacity Matches problem optimally.

TopicArrays
PatternPattern recognition and subarray formation
TimeO(n+K)
SpaceO(n)

Problem Description

Given an integer array intervals and an integer targetFuel, identify every contiguous segment (subarray) whose elements sum exactly to targetFuel. Return all such subarrays in the order of their first appearance: earlier start indices precede later ones, and for equal starts the shorter end index comes first. Subarrays may overlap and identical value sequences occurring at different positions are treated as distinct results.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Subarray Fuel Capacity Matches"

medium

WHY DOES IT MATTER?

Identifying subarrays with a given sum is a classic pattern that appears in financial transaction reconciliation, load‑balancing windows, and anomaly detection. Mastering the prefix‑sum + hashmap technique equips engineers to turn quadratic range‑sum problems into linear scans, a decisive advantage in performance‑critical code.

OPTIMIZATION CHALLENGE

The breakthrough is realizing that you don’t need to examine every possible start for each end; you only need the previously seen prefix that matches currentPrefix‑target. Storing all prior prefixes in a hash map collapses the inner loop into O(1) work, dropping the complexity from O(n²) to O(n).

REAL-WORLD CONNECTION

Think of a river flow gauge: the cumulative water volume at each checkpoint is the prefix sum. To find a segment where exactly X liters passed, you look for two checkpoints whose cumulative volumes differ by X. The hashmap acts like a quick lookup table of past checkpoint readings, enabling instant detection of the desired segment.

When coding, build the prefix sum on the fly (runningSum) and update the map before querying for the complement. This guarantees that subarrays starting at index 0 are also captured and preserves the required ordering without a separate sorting step.

COMPLEXITY AT A GLANCE

⏱ Time:O(n+K)
💾 Space:O(n)

Core Theory — Why This Approach?

The problem reduces to finding all pairs of indices (i,j) such that the sum of elements from i to j inclusive equals targetFuel. By introducing a prefix‑sum array P where P[t] is the sum of the first t elements, the subarray sum condition becomes P[j+1]-P[i]=targetFuel, i.e. P[i]=P[j+1]-targetFuel. A naïve double‑loop checks every (i,j) in O(n²) time, which quickly becomes infeasible for n up to 10⁵ or more. The optimal paradigm leverages a hash map that records every prefix sum value together with the list of positions where it occurs. As we sweep the array once, for each new prefix sum we query the map for (currentPrefix‑targetFuel) and instantly retrieve all valid start indices, preserving the required order because earlier indices were inserted earlier. This transforms the problem into a linear‑time lookup‑driven scan while still enumerating every qualifying subarray.

The key insight is that prefix sums turn a range‑sum query into a simple equality test, and a hash map provides O(1) average‑time access to all previous occurrences of a needed complement. By storing the indices in insertion order, we naturally satisfy the “earlier start first, then shorter end” ordering without extra sorting. The overall algorithm runs in O(n+K) time where K is the total number of matching subarrays, and uses O(n) auxiliary space for the map and prefix array.

Interview Questions on This Problem

Q1How would you modify the solution if the array contains only non‑negative numbers and you need to return the first subarray that meets the target?

Use a sliding‑window two‑pointer technique: expand the right pointer while the current sum is below target, shrink from the left when it exceeds, and stop as soon as the sum equals target. This runs in O(n) time with O(1) extra space.

Q2What changes are required to output the subarrays in descending order of length instead of the start‑index order?

Collect all matching (start,end) pairs during the linear scan, then sort the list by length descending (or by -(end‑start+1)). The initial O(n) discovery remains, and the extra O(K log K) sort satisfies the new ordering.

Q3In a distributed system where the array is sharded across machines, how can you compute the matching subarrays without moving the entire data to a single node?

Each shard computes its local prefix sums and a map of prefix→indices, then exchanges boundary prefix values with neighboring shards to adjust for cross‑shard subarrays. A second pass merges the local results using the shared prefix complement logic, achieving near‑linear work per shard and O(1) communication per boundary.

Examples

Example 1

Input

{"intervals":[2,4,1,3,2],"targetFuel":6}

Output

[[2,4],[1,3,2]]

Explanation: Starting at index 0, 2+4=6 so [2,4] is recorded. Continuing, the segment from index 2 to 4 (1+3+2) also equals 6, giving [1,3,2]. No other contiguous group sums to 6.

Example 2

Input

{"intervals":[5,-1,2,3,-2,4],"targetFuel":5}

Output

[[5],[2,3]]

Explanation: The element at index 0 alone is 5, producing [5]. Scanning further, the pair at indices 2‑3 (2+3) equals 5, yielding [2,3]. No additional contiguous segment reaches the target.

Example 3

Input

{"intervals":[1,1,1,1],"targetFuel":2}

Output

[[1,1],[1,1],[1,1]]

Explanation: Every adjacent pair of 1s sums to 2. The pairs start at indices 0‑1, 1‑2, and 2‑3, resulting in three identical subarrays [1,1] that are listed separately because their positions differ.

Constraints

  • 1 <= intervals.length <= 100000
  • -1000000000 <= intervals[i] <= 1000000000
  • -1000000000 <= targetFuel <= 1000000000
  • The total number of qualifying subarrays fits in 64‑bit signed integer

Optimal Approach & Strategy

Maintain a running prefix sum and a hash map from sum to list of indices; for each new prefix, retrieve all earlier indices where prefix‑target appears and emit those subarrays – O(n+K) time.

Brute Force Approach

Check every possible start index i and every end index j≥i, compute the sum of arr[i..j] and record the pair if it equals targetFuel – O(n²) time.

Code Solutions

JavaScript Solution
Time: O(n+K)
function subarrayFuelCapacityMatches(intervals, targetFuel) {
    const result = [];
    let left = 0;
    let currentSum = 0;

    for (let right = 0; right < intervals.length; ++right) {
        currentSum += intervals[right];

        while (currentSum > targetFuel) {
            currentSum -= intervals[left];
            left++;
        }

        if (currentSum === targetFuel) {
            result.push(intervals.slice(left, right + 1));
        }
    }

    return result;
}

const intervals = [2, 4, 1, 3, 2];
const targetFuel = 6;
const result = subarrayFuelCapacityMatches(intervals, targetFuel);

// Print the result
console.log(result);

Asked in Top Tech Interviews

Adobe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.