Bird
Raised Fist0
Interview Prepstacks-monotonic-stackhardAmazonGoogleMicrosoft

Sliding Window Maximum

Choose your preparation mode4 modes available
📋
Problem

Imagine monitoring the highest temperature in the last hour every minute to detect heat spikes instantly.

Given an integer array nums and an integer k, return an array of the maximum values of each sliding window of size k moving from left to right across nums.

1 ≤ nums.length ≤ 10^5-10^4 ≤ nums[i] ≤ 10^41 ≤ k ≤ nums.length
Edge cases: k = 1 → output is the original arrayAll elements are equal → output is array of that element repeatedk equals array length → output is single max of entire array
</>
IDE
def maxSlidingWindow(nums: list[int], k: int) -> list[int]:public int[] maxSlidingWindow(int[] nums, int k)vector<int> maxSlidingWindow(vector<int>& nums, int k)function maxSlidingWindow(nums, k)
def maxSlidingWindow(nums: list[int], k: int) -> list[int]:
    # Write your solution here
    pass
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        // Write your solution here
        return new int[0];
    }
}
#include <vector>
using namespace std;

vector<int> maxSlidingWindow(vector<int>& nums, int k) {
    // Write your solution here
    return {};
}
function maxSlidingWindow(nums, k) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Output missing max for some windows or incorrect max valuesNot removing indices from deque front when they fall out of the current window✅ Add condition to pop from front of deque if deque[0] < i - k + 1 inside the loop
Wrong: Output has repeated smaller values instead of maxNot maintaining deque in decreasing order, failing to pop smaller elements from back✅ While deque not empty and nums[i] >= nums[deque.back()], pop back before pushing i
Wrong: Output incorrect when k=1, not returning original arrayCode does not handle k=1 as a special case or general logic fails for window size 1✅ Return nums directly if k == 1 or ensure window logic works for k=1
Wrong: Code crashes or returns non-empty output on empty inputNo guard clause for empty input array✅ Add check at start: if not nums: return []
Wrong: Solution times out on large inputsUsing brute force O(n*k) or heap O(n log k) instead of O(n) monotonic deque✅ Implement monotonic deque approach with O(n) time complexity
✓
Test Cases
t1_01basic
Input{"nums":[1,3,-1,-3,5,3,6,7],"k":3}
Expected[3,3,5,5,6,7]

For each window of size 3, the maximums are: [1,3,-1] → 3, [3,-1,-3] → 3, [-1,-3,5] → 5, [-3,5,3] → 5, [5,3,6] → 6, [3,6,7] → 7

t1_02basic
Input{"nums":[9,11,8,5,7,10],"k":2}
Expected[11,11,8,7,10]

Windows: [9,11] → 11, [11,8] → 11, [8,5] → 8, [5,7] → 7, [7,10] → 10

t2_01edge
Input{"nums":[],"k":1}
Expected[]

Empty input array returns empty output.

t2_02edge
Input{"nums":[5],"k":1}
Expected[5]

Single element window returns the element itself.

t2_03edge
Input{"nums":[2,2,2,2],"k":2}
Expected[2,2,2]

All elements equal, max in each window is the same element.

t3_01corner
Input{"nums":[1,3,1,2,0,5],"k":3}
Expected[3,3,2,5]

Tests correct removal of elements outside window and maintaining max correctly.

t3_02corner
Input{"nums":[4,3,2,1,0],"k":2}
Expected[4,3,2,1]

Descending order input tests if code handles decreasing sequences correctly.

t3_03corner
Input{"nums":[1,3,1,3,1,3],"k":2}
Expected[3,3,3,3,3]

Alternating pattern tests if code handles repeated max values correctly.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

Input size n=100000 with k=50000 tests O(n) monotonic deque solution performance within 2 seconds.

Practice

(1/5)
1. Given the following Python code for asteroid collision, what is the output when the input is [8, -8, 5, -10]?
def asteroidCollision(asteroids):
    stack = []
    for a in asteroids:
        alive = True
        while alive and stack and stack[-1] > 0 and a < 0:
            if stack[-1] < -a:
                stack.pop()
            elif stack[-1] == -a:
                stack.pop()
                alive = False
            else:
                alive = False
        if alive:
            stack.append(a)
    return stack

print(asteroidCollision([8, -8, 5, -10]))
easy
A. [5, -10]
B. [-10]
C. [8, 5, -10]
D. []

Solution

  1. Step 1: Trace collision between 8 and -8

    8 and -8 are equal size but opposite direction, both explode -> stack empty.
  2. Step 2: Process 5 and then -10

    5 is pushed; -10 collides with 5, since 10 > 5, 5 pops, -10 remains and is pushed.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Final stack contains only [-10] after resolving collisions [OK]
Hint: Equal size opposite asteroids both explode [OK]
Common Mistakes:
  • Forgetting to pop both equal asteroids
  • Appending asteroid after it exploded
  • Not handling multiple collisions in while loop
2. You are given a list of tokens representing an arithmetic expression in postfix notation, where each token is either an integer or an operator (+, -, *, /). Which algorithmic approach guarantees an optimal and straightforward evaluation of this expression?
easy
A. Dynamic programming approach that stores intermediate results in a table indexed by token positions.
B. Greedy algorithm that evaluates tokens from left to right, applying operators as soon as possible without using extra data structures.
C. Stack-based iterative evaluation that pushes operands and applies operators by popping the last two operands from the stack.
D. Recursive backtracking that tries all possible ways to parenthesize the expression and selects the correct evaluation.

Solution

  1. Step 1: Understand the problem structure

    Postfix expressions require operands to be processed before operators, which naturally fits a stack structure.
  2. Step 2: Identify the correct approach

    Stack-based iterative evaluation pushes operands and pops two operands when an operator is encountered, applying the operator and pushing the result back.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Stack usage matches postfix evaluation logic [OK]
Hint: Postfix evaluation naturally uses a stack [OK]
Common Mistakes:
  • Thinking greedy evaluation without stack works
  • Confusing postfix with infix DP
  • Using recursion without clear base cases
3. Consider the following Python code implementing the optimized next greater element algorithm. What is the final output when calling nextGreaterElement([4,1,2], [1,3,4,2])?
easy
A. [-1, -1, 3]
B. [-1, 3, -1]
C. [3, -1, -1]
D. [3, 4, -1]

Solution

  1. Step 1: Trace stack and map updates for nums2

    Process nums2: push 1, then 3 > 1 so pop 1 -> map[1]=3; push 3; 4 > 3 pop 3 -> map[3]=4; push 4; 2 < 4 push 2. Stack ends with [4,2].
  2. Step 2: Assign -1 for remaining stack elements and build result

    Pop 2 -> map[2]=-1; pop 4 -> map[4]=-1. Result for nums1=[4,1,2] is [map[4], map[1], map[2]] = [-1,3,-1].
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Matches expected output from code comments and manual trace [OK]
Hint: Stack pops smaller elements when a bigger one arrives [OK]
Common Mistakes:
  • Confusing order of popping leading to wrong map values
  • Forgetting to assign -1 for elements with no next greater
  • Mixing up indices when building the final result
4. What is the time complexity of the optimized stack simulation algorithm for the asteroid collision problem, given n asteroids in the input list?
medium
A. O(n) because each asteroid is pushed and popped at most once
B. O(n log n) due to sorting implicit in stack operations
C. O(n^2) because each asteroid can cause multiple pops in the stack
D. O(n) for iteration plus O(n) for auxiliary space, total O(n)

Solution

  1. Step 1: Analyze iteration over asteroids

    The algorithm iterates over each asteroid once.
  2. Step 2: Analyze stack operations

    Each asteroid can be pushed once and popped once, so total stack operations are O(n).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Each asteroid processed at most twice (push/pop) [OK]
Hint: Each asteroid pushed and popped once max [OK]
Common Mistakes:
  • Assuming nested while loop causes O(n^2)
  • Confusing stack operations with sorting
  • Ignoring amortized analysis of stack pops
5. Identify the bug in the following circular queue implementation snippet:
medium
A. Line updating tail pointer should use modulo operation to wrap around.
B. Line checking if queue is full should compare head and tail pointers instead of size.
C. Line initializing queue should use an empty list instead of fixed-size array.
D. Line incrementing size should be before updating tail pointer.

Solution

  1. Step 1: Examine tail pointer update

    Tail pointer increments by 1 but lacks modulo operation, so it can exceed array bounds.
  2. Step 2: Understand consequences

    Without modulo, tail pointer goes out of range causing runtime errors or incorrect behavior.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Modulo operation is essential for circular wrap-around [OK]
Hint: Tail pointer must wrap modulo capacity [OK]
Common Mistakes:
  • Forgetting modulo wrap-around
  • Using size incorrectly to check full
  • Misordering size increment
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard