Neural Mastery
← Practice
Sliding Window Maximumhard

Sliding Window Maximum

hard Coding Interview Patterns 20–25 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Maintain a monotonic decreasing deque of indices to achieve O(1) amortized maximum lookup for every position of a sliding window.

Related Skills

Task

Implement max_sliding_window(nums, k): return a list of the maximum elements for each sliding window of size k moving from left to right across nums.

Function Signature

max_sliding_window(nums: list[int], k: int) -> list[int]

Examples

Example 1: Eight Element Window 3
Input: nums = [1, 3, -1, -3, 5, 3, 6, 7] k = 3
Output: [3, 3, 5, 5, 6, 7]
Example 2: Single Element k=1
Input: nums = [1] k = 1
Output: [1]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • 1 <= len(nums) <= 10^5, 1 <= k <= len(nums).
  • Must achieve O(n) total time complexity.
Python3Saved ✓
def max_sliding_window(nums: list[int], k: int) -> list[int]:
"""nums: an array of integers.
k: the sliding window size.
Return the max sliding window array containing the maximum value in each
window of size k moving from left to right."""
# Your implementation here
pass

Case 1: Eight Element Window 3
Input: nums = [1, 3, -1, -3, 5, 3, 6, 7] k = 3
Expected: [3, 3, 5, 5, 6, 7]
Case 2: Single Element k=1
Input: nums = [1] k = 1
Expected: [1]