Data Structures19 sections · 729 units
Open in Course

Shortest Subarray - Algorithm

Two operations

Maintain a monotonic increasing deque of indices (by prefix sum value):

1.1. For each jj, pop from front while prefix[j]prefix[deque.front()]kprefix[j] - prefix[deque.front()] \geq k. Each such index gives a valid subarray. Record the shortest.

2.2. Pop from back while prefix[j]prefix[deque.back()]prefix[j] \leq prefix[deque.back()]. These indices are dominated and never useful.

3.3. Push jj to back. The front removal is different from sliding window max. Once an index gives a valid answer, it can't give a shorter answer for any later jj, so you remove it. Time: O(n)O(n). Space: O(n)O(n).