Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Shortest run with sum at least K, negatives allowed

Hard · Target 35 minutes · Sliding window· Type asked at

Given an integer array nums, which may contain negative numbers, and an integer K ≥ 1, return the length of the shortest non-empty contiguous subarray whose sum is at least K, or 0 if there is none.

Examples

InputOutputWhy
nums = [2,-1,2], K = 33Only the whole array reaches 3.
nums = [1,2], K = 40
nums = [84,-37,32,40,95], K = 167332 + 40 + 95.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −10⁵ ≤ nums[i] ≤ 10⁵
  • 1 ≤ K ≤ 10⁹

Hints

Hint 1

Why does the positive-number window fail? Find a small array where shrinking from the left makes the sum larger.

Hint 2

With prefix sums P, a subarray i..j−1 has sum P[j] − P[i]. You want j − i small with P[j] − P[i] ≥ K.

Hint 3

Keep candidate starts i in a deque with increasing P[i]. A later start with a smaller or equal prefix makes earlier ones useless; a start that has already succeeded can be retired.

Where people lose marks

  • Running the positive-number window on this input: [2, −1, 2] with K = 3 already breaks it.
  • Prefix sums in 32-bit integers: 10⁵ × 10⁵ overflows. Use 64 bits.
  • Popping the front only once per step instead of while the condition holds.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.