Sliding Window Maximum

Algorithms
Hard
Google
58.1K views

Given an array `nums` and a sliding window size $k$, find the maximum number in each window. Use a Deque (Double-Ended Queue) for an $O(n)$ solution.

Why Interviewers Ask This

Google engineers ask this to evaluate your ability to optimize time complexity beyond naive solutions. They specifically test if you can leverage a Deque to maintain state efficiently, demonstrating mastery of data structures and sliding window patterns essential for high-throughput systems.

How to Answer This Question

1. Clarify constraints: Confirm input size and whether k is valid. 2. Propose the brute force O(n*k) solution first to establish a baseline, then immediately pivot to the optimal approach. 3. Explain the Deque strategy: Describe how indices are stored so the front always holds the maximum index, and elements smaller than the current number are removed from the back. 4. Walk through the logic: Detail how you slide the window, remove expired indices (those outside the current k range), and add the new element while maintaining order. 5. Analyze complexity: Explicitly state why each element is added and removed at most once, proving O(n) time and O(k) space. 6. Implement carefully: Write clean code handling edge cases like empty arrays or k=1.

Key Points to Cover

  • Demonstrating knowledge of the Deque data structure for monotonic queue optimization
  • Explaining the O(n) time complexity proof based on single-pass operations
  • Handling edge cases like invalid k values or empty input arrays gracefully
  • Clearly articulating the logic for removing expired indices from the front
  • Maintaining the descending order invariant within the Deque during iteration

Sample Answer

To solve the Sliding Window Maximum problem efficiently, I would start by acknowledging that a brute force approach checking every window takes O(n*k) time, which is inefficient for large datasets Google often handles. I…

Common Mistakes to Avoid

  • Using a priority queue which results in O(n log k) instead of the required O(n)
  • Forgetting to remove indices that have slid out of the window from the front
  • Storing actual values instead of indices, making it impossible to check window boundaries
  • Implementing the solution without explaining why the monotonic property holds

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 145 Google questions