Tutorialspoint
Problem
Solution
Submissions

Sliding Window Maximum

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to solve the Sliding Window Maximum problem. You are given an array of integers `nums` and an integer `k`, 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 maximum element in the sliding window.

Example 1
  • Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
  • Output: [3, 3, 5, 5, 6, 7]
  • Explanation:
    • Step 1: Create a data structure to track the maximum element in the current window.
    • Step 2: Slide the window through the array, one position at a time.
    • Step 3: For each window position, record the maximum element: [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
    • Step 4: Return the array of maximum values [3, 3, 5, 5, 6, 7].
Example 2
  • Input: nums = [1], k = 1
  • Output: [1]
  • Explanation:
    • Step 1: Create a data structure to track the maximum element in the current window.
    • Step 2: There is only one element and one window of size 1.
    • Step 3: The maximum in this window is 1.
    • Step 4: Return the array with the single maximum value [1].
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • 1 ≤ k ≤ nums.length
  • Time Complexity: O(n) where n is the length of the array
  • Space Complexity: O(k) where k is the window size
DequeIBMGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider using a deque (double-ended queue) to track potential maximum values
  • Maintain elements in the deque in decreasing order
  • Remove elements that are outside the current window
  • Remove smaller elements that won't be maximum in current or future windows
  • The front of the deque will always contain the current window's maximum

Steps to solve by this approach:

 Step 1: Create a deque to store indices of elements in the current window.
 Step 2: For each element in the array, remove indices that are outside the current window.
 Step 3: Remove indices of all elements smaller than the current element from the back of the deque.
 Step 4: Add the current element's index to the deque.
 Step 5: Once we've processed k elements, add the maximum (front of deque) to the result.
 Step 6: Continue this process for each element, sliding the window to the right.
 Step 7: Return the result array containing maximum values for each window position.

Submitted Code :