Minimum Size Subarray Sum solution explained

To find the shortest contiguous run of positive numbers whose sum reaches a target, slide a window: extend the right end one value at a time, and while the window's sum is at least the target, record its length and drop values from the left. Each index enters and leaves once, so it runs in O(n) time and O(1) extra space. The common follow-up, an O(n log n) version, binary searches over prefix sums.

By Published 7 min read

The task, restated

You get a list of positive integers and a positive target. Find the smallest number of neighboring values whose total is the target or more. If even the whole list falls short, return 0. You return a length, not the run itself, though the same code can track where the best run starts.

Examples made up for this walkthrough
ValuesTargetAnswerWhy
[3, 1, 4, 1, 5, 9, 2]1425 + 9 is 14, and no single value reaches 14
[3, 1, 4, 1, 5, 9, 2]919 alone is enough
[3, 1, 4, 1, 5, 9, 2]257The whole list sums to exactly 25
[3, 1, 4, 1, 5, 9, 2]260Nothing reaches 26
[2, 2, 2, 2]53Two values give 4; three give 6
Examples made up for this walkthrough. Scroll sideways on a small screen.

Ask two things before you code. Are all values positive? The fast answer depends on it. And is the condition "at least" or "exactly"? A sum of exactly k is a different problem, solved with a hash map of prefix sums.

What the interviewer is checking

This is a standard test of the sliding window. Interviewers want to see that you can explain why the window may shrink safely, keep the loop bounds right, and handle the no-answer case. Strong candidates also say out loud why the method breaks with negative numbers, and offer the binary search version when asked for a second approach.

Brute force: every start, extend until big enough

Fix each start index, add values to the right until the running total reaches the target, and record that length. Stopping as soon as the target is reached is safe for a fixed start: any longer run from the same start is worse. That is O(n²) in the worst case and a good reference to test the faster versions against.

def shortest_run_brute(values, target):
    best = 0
    for start in range(len(values)):
        total = 0
        for end in range(start, len(values)):
            total += values[end]
            if total >= target:
                length = end - start + 1
                if best == 0 or length < best:
                    best = length
                break
    return best
Brute force, O(n²) time, O(1) extra space.

Optimal: a window that grows right and shrinks left

Keep two indexes, left and right, and the sum of the values between them. Move right forward one step at a time and add the new value. Whenever the sum reaches the target, the current window is a candidate, so record its length. Then remove the leftmost value and move left forward, and keep shrinking while the sum still reaches the target.

Why is shrinking safe? Once a window starting at left reaches the target, no window starting at left and ending further right can be shorter. So left has given its best answer and can be dropped for good. Because values are positive, removing one always lowers the sum and adding one always raises it, which is what makes the two indexes move in only one direction.

def shortest_run(values, target):
    best = 0
    left = 0
    window = 0
    for right, value in enumerate(values):
        window += value
        while window >= target:
            length = right - left + 1
            if best == 0 or length < best:
                best = length
            window -= values[left]
            left += 1
    return best
Python: sliding window, O(n) time, O(1) extra space.
function shortestRun(values, target) {
  let best = Infinity;
  let left = 0;
  let windowSum = 0;
  for (let right = 0; right < values.length; right++) {
    windowSum += values[right];
    while (windowSum >= target) {
      best = Math.min(best, right - left + 1);
      windowSum -= values[left];
      left++;
    }
  }
  return best === Infinity ? 0 : best;
}
JavaScript: the same window, using Infinity as the starting best.

A quick trace on [3, 1, 4, 1, 5, 9, 2] with target 14: the window grows to 3 1 4 1 5 (sum 14), records length 5, then sheds 3 (sum 11). Adding 9 gives 20; the loop records 5, 4, 3 as it drops 1, 4 and 1, and records 2 at 5 9 before dropping 5 leaves 9. Adding 2 makes 11, below the target, so the answer stays 2.

Build prefix, where prefix[i] is the sum of the first i values. Because values are positive, prefix is strictly increasing. For each end position j, you want the largest start i with prefix[j] - prefix[i] >= target, which is the same as the first index where prefix exceeds prefix[j] - target, minus one. Binary search finds it in O(log n), so the whole thing is O(n log n) with O(n) extra memory.

from bisect import bisect_right

def shortest_run_prefix(values, target):
    prefix = [0]
    for value in values:
        prefix.append(prefix[-1] + value)
    best = 0
    for j in range(1, len(prefix)):
        need = prefix[j] - target
        if need < 0:
            continue
        i = bisect_right(prefix, need) - 1
        length = j - i
        if best == 0 or length < best:
            best = length
    return best
Prefix sums plus bisect, O(n log n).

Interviewers ask for this version because it shows you understand why the window works: both rely on the prefix sums only ever going up. If values could be negative, neither applies directly. The usual fix there keeps a deque of prefix indexes in increasing order of value, which this page describes but does not code.

Cost of each approach

n is the number of values
ApproachTimeExtra spaceNeeds positive values?
Every start, extendO(n²)O(1)No, though the early stop relies on it
Sliding windowO(n)O(1)Yes
Prefix sums plus binary searchO(n log n)O(n)Yes, for the sorted prefix
Prefix sums plus monotonic dequeO(n)O(n)No (described, not coded here)
n is the number of values. Scroll sideways on a small screen.

Edge cases to test

  • An empty list: return 0.
  • A single value that already reaches the target: 1.
  • The whole list exactly equal to the target: its length.
  • The whole list short of the target: 0, not the list length and not infinity.
  • Equal values everywhere, where many windows tie.
  • A target of 1 with all values at least 1: the answer is 1.

Common mistakes

  • Using if instead of while for the shrink step, so the window only loses one value per step and misses shorter runs.
  • Recording the length after shrinking instead of before, which reports a window that no longer reaches the target.
  • Returning the infinity placeholder when nothing qualifies.
  • Applying the window to data with negative numbers, where removing a value can raise the sum.
  • Mixing up "at least" with "exactly", which needs a different method.

How to explain it out loud

Fictional example

A concise explanation in a phone screen
Candidate
Brute force would try every start and extend right, which is quadratic. Since all values are positive, a window works better.
Candidate
I grow the right edge and add each value. Whenever the sum reaches the target, I record the length and shrink from the left, because that start cannot do any better by going further right.
Candidate
Each index is added once and removed at most once, so it is linear time and constant space. If you want a second approach, prefix sums are increasing here, so I can binary search for each end in n log n.

The sliding window pattern guide covers this window shape and the cases where windows do not apply. Find Pivot Index uses running sums in a different way, comparing the total on each side of a position. Minimum Window Substring is the same grow-then-shrink idea with a character count instead of a sum, and Binary Search covers the boundary search the follow-up needs.

Practicing with Natively

This problem rewards saying the invariant before writing code. In a practice round, Natively can read the prompt from a screenshot on Mac or Windows and offer a code hint, which is most useful after you have tried the window yourself and want to compare. The transcript of your mock session shows whether you explained why shrinking is safe or skipped straight to typing. See AI help for coding interviews for what the coding features do.

Questions people ask

How do you solve Minimum Size Subarray Sum in O(n)?

Use a sliding window. Add values on the right, and while the window's sum is at least the target, record its length and remove values from the left. Each index enters and leaves once.

Why does the sliding window need positive numbers?

With only positive values, adding a value always raises the sum and removing one always lowers it. With negative values that breaks, so shrinking the window can skip the right answer.

What is the O(n log n) solution?

Build prefix sums, which only increase when values are positive, then for each end position binary search for the latest start whose prefix is small enough.

What should the function return when no run reaches the target?

Return 0. A common bug is returning the infinity placeholder used as the starting best length.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP