Sliding Window Maximum

Stack / Queues FAQs Hard

Given an array of integers arr, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Examples:

Input: arr = [4, 0, -1, 3, 5, 3, 6, 8], k = 3

Output: [4, 3, 5, 5, 6, 8]

Explanation: 


Window position          Max

------------------------     -----

[4 0 -1] 3 5 3 6 8      4

 4 [0 -1 3] 5 3 6 8      3

 4 0 [-1 3 5] 3 6 8      5

 4 0 -1 [3 5 3] 6 8      5

 4 0 -1 3 [5 3 6] 8      6

 4 0 -1 3 5 [3 6 8]     8


For each window of size k=3, we find the maximum element in the window and add it to our output array.

Input: arr = [20, 25], k = 2

Output: [25]

Explanation: There’s just one window of size 2 that is possible and the maximum of the two elements is our answer.

Input: arr = [1, 3, -1, -3, 5, 3, 6, 7], k = 3

Constraints

  • 1 <= arr.length <= 105
  • -104 <= arr[i] <= 104
  • 1 <= k <= arr.length

Hints

  • Deque-based solution is Maintain a monotonic decreasing deque (stores indices). The front of the deque always holds the max. Remove elements not within the current window. Remove smaller elements before inserting a new element.
  • Max Heap-based solution Maintain a Max Heap (priority queue) of size k. Extract max at each step, ensuring only valid elements remain.

Company Tags

Cerner Qualcomm Activision Blizzard Ubisoft Bain & Company Twilio Reddit ARM Epic Systems Freshworks NVIDIA Docker Cloudflare McKinsey & Company Wayfair Optum Salesforce Visa Unity Technologies Philips Healthcare Instacart Intel Teladoc Health American Express Swiggy Google Microsoft Amazon Meta Apple Netflix Adobe