Professional Documents
Culture Documents
Interview Camp
Technique: Queue with Max
Level: Hard
Maximum of Sliding Window: Given an array A and an integer K, find the maximum element in
each sliding window of size K.
For example,
if A = [4,6,5,2,4,7] and K = 3, windows are as follows:
[4,6,5,2,4,7] : Max = 6
[4,6,5,2,4,7] : Max = 6
[4,6,5,2,4,7] : Max = 5
[4,6,5,2,4,7] : Max = 7
Output: 6,6,5,7
Hint: You can do this in O(n) time, by using the Queue with Max technique.
Questions to Clarify:
Q. How should we output the result?
A. Print the max of each sliding window.
Q. What if A is empty or null?
A. Print nothing.
Q. What if K is 0?
A. Print nothing.
Solution:
This is a straightforward application of a Queue with Max. Maintain a Queue with Max and simply
output the max after processing each element.
Pseudocode:
(Note: Never write pseudocode in an actual interview. Unless you're writing a few
lines quickly to plan out your solution. Your actual solution should be in a real
language and use good syntax.)
slidingWindowMax(int[] a, int k)
q = new queuewithMax
for: i = k to a.length - 1:
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
add a[i]
dequeue q
print out max element
Test Cases:
Edge Cases: empty array, null array, k=0
Base Cases: single element array, k=1
Regular Cases: multiple elements (k=2, k=3)
Space Complexity: O(k) - the queue with max will store up to K elements
public static void slidingWindowMax(int[] a, int windowSize) {
if (a == null || a.length == 0 || windowSize <= 0)
return;
try {
// add first k elements
for (int i = 0; i < windowSize; i++) {
q.enqueue(a[i]);
}
System.out.println(q.findMax());
} catch (QueueEmptyException e) {
// should not happen
e.printStackTrace();
}
}
public QueueWithMax() {
main = new LinkedList<>();
max = new LinkedList<>();
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
/*
* Helper code, ask the interviewer if they want you to implement.
*/
public static class QueueEmptyException extends Exception {
public QueueEmptyException() {
}
}
© 2017 Interview Camp (interviewcamp.io)