Tutorialspoint
Problem
Solution
Submissions

Sliding Window Maximum using Deque

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java program to find the maximum element in each sliding window of size k in an array. Given an array of integers nums and a window size k, return an array of maximum values for each window as it slides from left to right.

Example 1
  • Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
  • Output: [3, 3, 5, 5, 6, 7]
  • Explanation:
    Step 1: The sliding window has size k = 3
    Step 2: Window 1: [1, 3, -1] → max = 3
    Step 3: Window 2: [3, -1, -3] → max = 3
    Step 4: Window 3: [-1, -3, 5] → max = 5
    Step 5: Window 4: [-3, 5, 3] → max = 5
    Step 6: Window 5: [5, 3, 6] → max = 6
    Step 7: Window 6: [3, 6, 7] → max = 7
Example 2
  • Input: nums = [1, -1], k = 1
  • Output: [1, -1]
  • Explanation:
    Step 1: The sliding window has size k = 1
    Step 2: Window 1: [1] → max = 1
    Step 3: Window 2: [-1] → max = -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)
DequeTutorialspointDeloitte
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

  • Use a deque (double-ended queue) to maintain potential maximum elements.
  • Keep the deque in decreasing order of values.
  • The front of the deque will always contain the maximum element of the current window.
  • When sliding the window, remove elements from the front if they are outside the window.
  • Before adding a new element, remove elements from the back that are smaller than the new element.
  • This ensures that the deque is always in decreasing order and contains only elements from the current window.

Steps to solve by this approach:

 Step 1: Initialize a deque to store indices of array elements in decreasing order of their values.

 Step 2: Process the first k elements separately to initialize the deque.
 Step 3: For each element, remove all elements smaller than the current element from the back of the deque.
 Step 4: Add the current element's index to the back of the deque.
 Step 5: For each subsequent element, first remove elements from the front of the deque that are outside the current window.
 Step 6: Remove elements smaller than the current one from the back of the deque, then add the current element's index.
 Step 7: After processing each element, the front of the deque contains the index of the maximum element for the current window.

Submitted Code :