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

Coding · Sliding window

Shortest subarray with a sum at least the target

Medium · Target 15 minutes · Sliding window· Type asked at

Given an array nums of positive integers and an integer target, return the length of the shortest contiguous subarray whose sum is at least target. If no such subarray exists, return 0.

Examples

InputOutputWhy
nums = [2, 3, 1, 2, 4, 3], target = 72The subarray [4, 3] sums to 7 and nothing shorter reaches it.
nums = [1, 1, 1, 1, 1, 1, 1, 1], target = 110The whole array sums to 8.
nums = [1, 4, 4], target = 41A single element is enough.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁴
  • 1 ≤ target ≤ 10⁹
  • Every value is strictly positive

Hints

Hint 1

There are n(n+1)/2 subarrays. Enumerating them is O(n²) even with a running sum. What property of the input lets you skip most of them?

Hint 2

Every value is positive, so extending a window can only increase its sum and shrinking it can only decrease it. The sum is monotone in the window.

Hint 3

Grow the right end until the window qualifies. Then, before growing again, shrink from the left for as long as it still qualifies — each shrink gives a shorter candidate.

Where people lose marks

  • Returning the running best as 0 when nothing qualifies, but initialising best to 0 as well — then a real answer of, say, 3 never replaces it. Initialise to n + 1 or to infinity and convert at the end.
  • Shrinking with while (sum > target) rather than >=, which stops one step early and returns a length one too long.
  • Summing into a 32-bit integer. With n = 10⁵ and values up to 10⁴ the total reaches 10⁹, which is close enough to the limit to be worth a 64-bit accumulator.
  • Reaching for prefix sums and binary search, O(n log n). It is a correct answer to a question that has an O(n) one.
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.