Video in progress
How do you find the maximum in every window of length k in O(n)? For example, [1,3,-1,-3,5,3,6,7] with k = 3.
A monotonic deque: I keep indexes in it with their values in decreasing order. When a new element arrives, I drop smaller ones from the back and drop an index that left the window from the front, so the maximum is always at the head of the deque. Each index goes in once and comes out once.
📖 Answer
For the example input the result is [3, 3, 5, 5, 6, 7]. Re-scanning every window is O(n·k), a TreeMap multiset gives O(n log k), and a deque gives O(n).
static int[] windowMax(int[] a, int k) { // we assume 1 <= k <= a.length
int[] res = new int[a.length - k + 1];
Deque<Integer> dq = new ArrayDeque<>(); // indexes, decreasing by a[]
for (int i = 0; i < a.length; i++) {
if (!dq.isEmpty() && dq.peekFirst() <= i - k) dq.pollFirst(); // left the window
while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) dq.pollLast(); // can never be the maximum now
dq.addLast(i);
if (i >= k - 1) res[i - k + 1] = a[dq.peekFirst()];
}
return res;
}
The idea is simple: if j < i and a[j] <= a[i], then j leaves the window before i does and isn't larger than it. So there is no point in keeping j.
Why indexes and not values? You need the position to know when an element leaves the window. If you store values, with duplicates you can't tell which copy to remove.
There is a while inside, but it's still O(n); say this amortization argument yourself in the interview.
In practice: "the biggest latency in the last 60 seconds", or a windowed maximum or minimum on stock prices. For the minimum, flip the comparison. This is a relative of the "next greater element" stack, the difference being that elements now leave from both ends.
Sign up to mark studied questions and save your progress.