Python coding

Shortest run of positives reaching a total

Given a list nums of positive integers and a positive integer target, return the length of the shortest contiguous subarray whose sum is at least target. If no subarray reaches target (for example, when nums is empty), return 0.

Aim for O(n) time and O(1) extra space.

Besides the tests, one large input (6,000 values) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • shortest_run([3,1,4,1,5,9,2], 12) → 2
  • shortest_run([1,1,1,1], 5) → 0
  • shortest_run([2,4,1,3,2,5], 10) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Variable-size window: every value is positive, so widening the window raises its sum and shrinking it lowers the sum.

Hint 2

Add nums[right]; then, while the sum is at least target, record the length and drop nums[left]. Use while, not if.

Solution and why it works
pythonO(n) · O(1)
def shortest_run(nums: list[int], target: int) -> int:
    left = total = 0
    best = len(nums) + 1                 # longer than any real window
    for right, x in enumerate(nums):
        total += x
        while total >= target:           # shortest: record, then try a tighter window
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return best if best <= len(nums) else 0

With positive values, a window that reaches target stays valid when widened, so for each right edge you shrink from the left while the sum still reaches target, recording the length before each step. Both edges only move forward: O(n) instead of O(n²) start-end pairs. Shrink with while: one large value can make several elements on the left unnecessary at once. Negative values break this; use prefix sums then.

Related lab: Sliding window, step by step