We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard monotonic stack problem, graded against 6 test cases (3 of them hidden).
A stack kept sorted, for next-greater and largest-rectangle style questions.
Reach for it when you see: "Next greater/smaller element", or a maximum rectangle/area over a histogram.
More Monotonic Stackproblems →Maintain a deque of *indices* such that the values `nums[deque]` are strictly decreasing from front to back. The front is the index of the current window's maximum.
For each new index `i`:
1. While the deque's front index `< i - k + 1`, pop front (it has slid out of the window).
2. While the value at the deque's back is `<= nums[i]`, pop back (those values are now dominated and can never be max again).
3. Push `i` to the back.
4. Once `i >= k - 1`, record `nums[deque.front]` as this window's max.
Each index is pushed and popped at most once across the whole run.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.