DSA interview question
A network monitor reports, every second, the peak latency over the last k seconds. For a stream of n measurements, that's the maximum of every window of size k. Rescanning each window costs O(n · k). A monotonic deque of indices does it in O(n). The deque holds indices whose values are decreasing from front to back. A new value evicts every smaller-or-equal value from the back, since those can never be a window's maximum again. The front drops out when it leaves the window. The front is always the current maximum.
Example: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3 → [3, 3, 5, 5, 6, 7].
vector<int> maxSlidingWindow(const vector<int>& nums, int k); // 1 <= k <= n
Input (nums, k) | Output | Explanation |
|---|---|---|
([1, 3, -1, -3, 5, 3, 6, 7], 3) | [3, 3, 5, 5, 6, 7] | |
([1], 1) | [1] | |
([9, 8, 7, 6], 2) | [9, 8, 7] | Decreasing: the maximum expires each step |
([1, 2, 3, 4], 4) | [4] | One window |
([4, 4, 4], 2) | [4, 4] |
(Confirm: windows are contiguous, of size exactly k; there are n − k + 1 outputs.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in