Python coding

Shortest run reaching a total, with negatives

Given a non-empty list of integers nums, which may hold negatives, and a positive integer k, return the length of the shortest non-empty contiguous subarray whose sum is at least k. Return -1 if no subarray reaches k.

The negatives break the usual sliding window: dropping a value from the left can raise the sum. Aim for O(n).

Besides the tests, one large input (5,500 numbers) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • shortest_reaching([3,-2,4], 5) → 3
  • shortest_reaching([2,1,1], 5) → -1
  • shortest_reaching([3,-4,2,5], 7) → 2
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

With prefix sums, nums[i:j] reaches k when P[j] - P[i] >= k. For each end j, you want the latest start i whose P[i] is low enough.

Hint 2

Keep a deque of start indices with increasing prefix values. Before adding j, pop from the back every start with a prefix >= P[j]: j is later and no higher, so it always wins.

Hint 3

From the front, while P[j] - P[front] >= k, record j - front and pop it: a later end would only give that start a longer run.

Solution and why it works
pythonO(n) · O(n)
from collections import deque

def shortest_reaching(nums: list[int], k: int) -> int:
    prefix = [0]
    for x in nums:
        prefix.append(prefix[-1] + x)
    best = len(nums) + 1
    starts = deque()                     # start indices, prefix values increasing
    for j, p in enumerate(prefix):
        while starts and p - prefix[starts[0]] >= k:
            best = min(best, j - starts.popleft())   # no later end can beat this
        while starts and prefix[starts[-1]] >= p:
            starts.pop()                 # j starts later and no higher: better
        starts.append(j)
    return best if best <= len(nums) else -1

A run nums[i:j] reaches k when P[j] - P[i] >= k. The deque keeps starts whose prefixes increase: a start with a prefix at least as high as a later one can never win, so it leaves from the back. At the front, a start that already reaches k is recorded and dropped, since later ends only lengthen its run. Each index enters and leaves once: O(n). A sliding window fails here: with negatives, shrinking it can raise the sum.