Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Sliding window

Shortest subarray with a sum at least the target

Medium · Target 15 minutes · Sliding window · Type asked atOptiverTwo SigmaAmazon

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.

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.