Skills101
← All coding problems

Minimum Size Subarray Sum

mediumSliding Window+20 XPTime limit 2s

All numbers are positive. Find the length of the shortest contiguous subarray whose sum is at least target. Print 0 if no such subarray exists.

Input:

  • line 1: n target
  • line 2: n positive integers

Output: the minimal length, or 0.

Constraints: 1 ≤ n ≤ 10⁵, 1 ≤ a[i] ≤ 10⁴, 1 ≤ target ≤ 10⁹.

Think about it: because every number is positive, growing the window only increases the sum and shrinking only decreases it — perfect for a sliding window.

Sample input 1

6 7
2 3 1 2 4 3

Sample output 1

2

Sample input 2

3 4
1 4 4

Sample output 2

1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.