Backend Engineer
Senior
programming
Find the length of the shortest subarray with a sum at least K. You may assume that the array has at least one element. You must solve this in O(n) time complexity.
Constraints:
- 1 <= arr.length <= 10^5
- 1 <= arr[i] <= 10^4
- 1 <= K <= 10^9
Examples:
1. Input: arr = [2, -1, 2, 3, 4], K = 3
Output: 2
Explanation: The subarray [2, 3] has the minimum length of 2.
2. Input: arr = [1, 2, 3, 4, 5], K = 11
Output: 3
Explanation: The subarray [3, 4, 5] has the minimum length of 3.
```
def shortest_subarray(arr, K):
from collections import deque
n = len(arr)
prefix_sum = [0] * (n + 1)
for i in range(n):
prefix_sum[i + 1] = prefix_sum[i] + arr[i]
min_length = float('inf')
q = deque()
for i in range(n + 1):
while q and prefix_sum[i] - prefix_sum[q[0]] >= K:
min_length = min(min_length, i - q.popleft())
while q and prefix_sum[i] <= prefix_sum[q[-1]]:
q.pop()
q.append(i)
return min_length if min_length != float('inf') else 0
```
Trusted by 100+ professionals preparing for interviews
Trusted by 100+ professionals
50+ Company Question Banks
5+ Supported Languages
Practice More Questions Like This
Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.
Get Started Free