← Questions
Sliding window maximum over an array and a stream
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Two forms of the same problem: the maximum of every window of k consecutive numbers in an array, and a stream structure that reports the maximum of the last k numbers inserted. Expect to start simple and improve.
Part 1: array version
max_sliding_window(nums: list[int], k: int) -> list[int]
max_sliding_window([2, 7, 3, 1, 5, 4], 3) -> [7, 7, 5, 5]
Part 2: stream version
Unless you agree on a different interface with the interviewer, assume:
-
SlidingWindow(k),put(number: int) -> None,get_max() -> int— the largest of the lastknumbers put, or of all of them while fewer thankhave been put.
w = SlidingWindow(2)
put(5); get_max() -> 5
put(1); get_max() -> 5
put(3); get_max() -> 3 # window is now 1, 3
put(8); get_max() -> 8
Then improve it in steps: a basic version with its complexity; space reduced to O(k); a comparison of arrays, hash maps, linked lists and heaps for this job; finally the monotonic deque.
Constraints
- Up to
10^5numbers; values may be negative or repeat;kis fixed.
Clarifying questions
- What does
get_maxreturn beforeknumbers have been put, and when nothing has been put? - Can numbers repeat or be negative?
- How often is
get_maxcalled compared withput?
What a strong answer covers
- The baseline: store everything and scan the last
k,O(k)perget_max; then a circular buffer of sizekforO(k)space. - What each structure costs to add the newest number, drop the oldest and find the largest, and why few do all three well (a heap needs lazy deletion of expired items).
- The monotonic deque: keep indices of decreasing values; pop smaller values from the back on insert, pop expired indices from the front; the front is the maximum.
- Amortized
O(1)per operation,O(k)space, and why each element is pushed and popped at most once. - Correct handling of duplicates (pop only strictly smaller values, or track indices).
Follow-ups
- Also support
get_min()inO(1). - The window is time-based: the maximum of the last 60 seconds.
- Many threads call
putandget_max. How do you keep it correct? - Return the median of the window instead.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
