CodingNodes / Sliding Window / Minimum Size Subarray Sum System design Space play · ←→ step · R restart

Problem

You are given a positive integer target and an array nums of positive integers.

Find the length of the shortest contiguous run of nums whose sum is at least target. If no run is big enough, return 0.

Constraints

  • 1 ≤ target ≤ 10⁹
  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁴

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: right visits each index once, and left only moves forward, so each number is added once and removed at most once.

Space: Only a few integers are kept: left, right, the running total, and the best length.

Because every number is positive, adding on the right only raises the sum and removing on the left only lowers it. Grow the window with right. While the sum is at least target, record the length and shrink from left to look for something shorter.