You are given an array of integers nums and a sliding window of size k which moves from the leftmost position to the rightmost position. At each position, you can only see the k numbers in the window.

Each time the sliding window moves right by one position, find the maximum element in the current window.

Return an array containing the maximum value of each window position.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
💡 Note: Window [1,3,-1] → max=3, [3,-1,-3] → max=3, [-1,-3,5] → max=5, [-3,5,3] → max=5, [5,3,6] → max=6, [3,6,7] → max=7
Example 2 — Single Element Window
$ Input: nums = [1], k = 1
Output: [1]
💡 Note: Only one element, so maximum is itself
Example 3 — All Same Elements
$ Input: nums = [7,7,7,7], k = 2
Output: [7,7,7]
💡 Note: All elements are same, so every window has maximum 7

Constraints

  • 1 ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Sliding Window Maximum INPUT Array nums (k=3): 1 0 3 1 -1 2 -3 3 5 4 3 5 6 6 7 7 Window slides right: max=3 max=3 max=5 Input Values: nums = [1,3,-1,-3,5,3,6,7] k = 3 ALGORITHM STEPS 1 Use Deque (Monotonic) Store indices in decreasing order 2 Remove Out-of-Window Pop front if index out of range 3 Maintain Decreasing Order Pop smaller elements from back 4 Record Maximum Front of deque is max Deque State (indices): Front 1 2 Back Complexity: Time: O(n) Space: O(k) Each element pushed/popped once FINAL RESULT Window maximums: 3 [0-2] 3 [1-3] 5 [2-4] 5 [3-5] 6 [4-6] 7 [5-7] Output: [3, 3, 5, 5, 6, 7] OK 6 windows processed Trace Example: i=0: deque=[0], wait... i=1: deque=[1], wait... i=2: deque=[1,2], out=3 i=3: deque=[1,3], out=3 Key Insight: The monotonic deque maintains potential maximums in decreasing order. When a new element arrives, we remove all smaller elements from back (they can never be maximum). The front always holds the current window maximum. This achieves O(n) time as each element is pushed and popped at most once. TutorialsPoint - Sliding Window Maximum | Optimal Solution (Monotonic Deque)
Asked in
Amazon 50 Google 45 Microsoft 40 Facebook 35
850.0K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen