Dynamic Programming21 sections · 916 units
Open in Course

Shortest Subarray - Implementation

The code

You'll use a deque to maintain candidate starting positions. The core idea: if prefix[j]prefix[i]prefix[j] \geq prefix[i] and j>ij > i, position ii is never useful.

For each position jj, you do two things. First, remove positions from the back of the deque whose prefix sum is prefix[j]\geq prefix[j]. They will never be optimal starting points because jj is closer and has a smaller or equal prefix sum. Second, check positions at the front of the deque: while prefix[j]prefix[front]kprefix[j] - prefix[front] \geq k, you have a valid subarray. Update your answer with jfrontj - front, then pop the front (no future jj will do better with that index).

Each position enters the deque once and leaves once. This gives O(n)O(n) total work across all iterations.

Time complexity: O(n)O(n).

Space complexity: O(n)O(n) for the prefix array and deque.