iq.lab
Python starts when a code cell comes near or you run one
mediumSliding window target 25 min

Shortest block that reaches a target

Every number in the list nums is a whole number of at least 1, and so is target. A subarray is a block of consecutive items, such as [4, 1] in [3, 4, 1], and it holds at least one item.

Find the shortest subarray whose items add up to target or more, and return its length. If even the whole list adds up to less than target, no subarray reaches it, so return 0.

Example 1
Inputnums = [3, 1, 4, 1, 5], target = 9Output3

4 + 1 + 5 = 10 reaches 9. No single item does, and no two neighbors do: the biggest pair is 1 + 5 = 6.

Example 2
Inputnums = [1, 8, 2], target = 8Output1

The single item 8 is already at least 8.

Example 3
Inputnums = [2, 2, 2], target = 7Output0

Even the whole list sums to 6, so no subarray reaches 7.

Constraints
  • 1 ≤ len(nums) ≤ 105

  • 1 ≤ nums[i] ≤ 104

  • 1 ≤ target ≤ 109

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.