Editor

Shortest Run Reaching a Target

#109 · Sliding window · Intermediate · 85 XP · about 15 min

nums is a list of positive whole numbers. Write shortest_reach(nums, target) that returns the length of the shortest run of numbers next to each other whose sum is at least target. If no run reaches target, return 0.

Examples

shortest_reach([3, 1, 4, 1, 5, 9, 2], 14)   # returns 2
shortest_reach([2, 8, 1, 6], 7)             # returns 1
shortest_reach([1, 1, 1, 1], 5)             # returns 0

In the first example, 5 + 9 = 14 is the only pair of neighbours that reaches 14, and no single number does. In the second, 8 on its own is enough.

Constraints

  • 0 <= len(nums) <= 100,000
  • 1 <= nums[i] <= 10,000
  • 1 <= target <= 10^9

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.