Sliding Window Maximum

Stack / Queues FAQs Hard
  • A real-world application of this programming problem can be found in financial sectors and data analytics
  • The concept of a "sliding window" is equivalent to moving averages or other rolling statistics used in stock market, commodity, and economic analysis, where the most recent 'k' data points are used to make forecasts
  • For instance, a 50-day or 200-day moving average (which are very common in stock market analysis) would be a "sliding window" of 50 or 200 data points, hence the maximum (highest) value within that window can be beneficial in predicting or setting stock sales thresholds

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