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.
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
A naive approach to solve this problem involves considering every window possible of size K and then finding the maximum element for each window.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to get the maximum sliding window
vector<int> maxSlidingWindow(vector<int> &arr, int k) {
int n = arr.size(); // Size of array
// To store the answer
vector<int> ans;
/* Traverse on the arrary
for valid window */
for(int i=0; i <= n-k; i++) {
// To store the maximum of the window
int maxi = arr[i];
// Traverse the window
for(int j=i; j < i+k; j++) {
// Update the maximum
maxi = max(maxi, arr[j]);
}
// Add the maximum to the result
ans.push_back(maxi);
}
// Return the stored result
return ans;
}
};
int main() {
vector<int> arr = {4, 0, -1, 3, 5, 3, 6, 8};
int k = 3;
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the
maximum sliding window */
vector<int> ans = sol.maxSlidingWindow(arr, k);
cout << "The maximum elements in the sliding window are: ";
for(int i=0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
return 0;
}
import java.util.*;
class Solution {
// Function to get the maximum sliding window
public List<Integer> maxSlidingWindow(int[] arr, int k) {
int n = arr.length; // Size of array
// To store the answer
List<Integer> ans = new ArrayList<>();
/* Traverse on the arrary
for valid window */
for(int i = 0; i <= n - k; i++) {
// To store the maximum of the window
int maxi = arr[i];
// Traverse the window
for(int j = i; j < i + k; j++) {
// Update the maximum
maxi = Math.max(maxi, arr[j]);
}
// Add the maximum to the result
ans.add(maxi);
}
// Return the stored result
return ans;
}
public static void main(String[] args) {
int[] arr = {4, 0, -1, 3, 5, 3, 6, 8};
int k = 3;
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the
maximum sliding window */
List<Integer> ans = sol.maxSlidingWindow(arr, k);
System.out.println("The maximum elements in the sliding window are: ");
for(int num : ans) {
System.out.print(num + " ");
}
}
}
class Solution:
# Function to get the maximum sliding window
def maxSlidingWindow(self, arr, k):
n = len(arr) # Size of array
# To store the answer
ans = []
# Traverse on the array for valid window
for i in range(n - k + 1):
# To store the maximum of the window
maxi = arr[i]
# Traverse the window
for j in range(i, i + k):
# Update the maximum
maxi = max(maxi, arr[j])
# Add the maximum to the result
ans.append(maxi)
# Return the stored result
return ans
# Creating an instance of Solution class
sol = Solution()
arr = [4, 0, -1, 3, 5, 3, 6, 8]
k = 3
# Function call to get the maximum sliding window
ans = sol.maxSlidingWindow(arr, k)
print("The maximum elements in the sliding window are: ")
for num in ans:
print(num, end=" ")
class Solution {
// Function to get the maximum sliding window
maxSlidingWindow(arr, k) {
let n = arr.length; // Size of array
// To store the answer
let ans = [];
/* Traverse on the arrary
for valid window */
for(let i = 0; i <= n - k; i++) {
// To store the maximum of the window
let maxi = arr[i];
// Traverse the window
for(let j = i; j < i + k; j++) {
// Update the maximum
maxi = Math.max(maxi, arr[j]);
}
// Add the maximum to the result
ans.push(maxi);
}
// Return the stored result
return ans;
}
}
let arr = [4, 0, -1, 3, 5, 3, 6, 8];
let k = 3;
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to get the
maximum sliding window */
let ans = sol.maxSlidingWindow(arr, k);
console.log("The maximum elements in the sliding window are: ");
for(let num of ans) {
console.log(num + " ");
}
Time Complexity: O((N-K)*K) (where N is the size of given array)
Using two nested loops.
Space Complexity: O(N-K)
Due to the size taken to return the answer.
In the earlier approach, scanning every element of the window repeatedly was resulting in increased time complexity. Instead, if there can be a way where the maximum element for a window can be found in constant time, the overall time complexity will improve significantly.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to get the maximum sliding window
vector<int> maxSlidingWindow(vector<int> &arr, int k) {
int n = arr.size(); // Size of array
// To store the answer
vector<int> ans;
// Deque data structure
deque <int> dq;
// Traverse the
for(int i=0; i < n; i++) {
// Update deque to maintain current window
if (!dq.empty() && dq.front() <= (i-k)) {
dq.pop_front();
}
/* Maintain the monotonic (decreasing)
order of elements in deque */
while (!dq.empty() && arr[dq.back()] <= arr[i]) {
dq.pop_back();
}
// Add current elements index to the deque
dq.push_back(i);
/* Store the maximum element from
the first window possible */
if (i >= (k-1)) {
ans.push_back(arr[dq.front()]);
}
}
// Return the stored result
return ans;
}
};
int main() {
vector<int> arr = {4, 0, -1, 3, 5, 3, 6, 8};
int k = 3;
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the
maximum sliding window */
vector<int> ans = sol.maxSlidingWindow(arr, k);
cout << "The maximum elements in the sliding window are: ";
for(int i=0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
return 0;
}
import java.util.*;
class Solution {
// Function to get the maximum sliding window
public int[] maxSlidingWindow(int[] arr, int k) {
int n = arr.length; // Size of array
// To store the answer
int[] ans = new int[n - k + 1];
int ansIndex = 0;
// Deque data structure
Deque<Integer> dq = new LinkedList<>();
// Traverse the array
for (int i = 0; i < n; i++) {
// Update deque to maintain current window
if (!dq.isEmpty() && dq.peekFirst() <= (i - k)) {
dq.pollFirst();
}
/* Maintain the monotonic (decreasing)
order of elements in deque */
while (!dq.isEmpty() && arr[dq.peekLast()] <= arr[i]) {
dq.pollLast();
}
// Add current element's index to the deque
dq.offerLast(i);
/* Store the maximum element from
the first window possible */
if (i >= (k - 1)) {
ans[ansIndex++] = arr[dq.peekFirst()];
}
}
// Return the stored result
return ans;
}
public static void main(String[] args) {
int[] arr = {4, 0, -1, 3, 5, 3, 6, 8};
int k = 3;
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the
maximum sliding window */
int[] ans = sol.maxSlidingWindow(arr, k);
System.out.print("The maximum elements in the sliding window are: ");
for (int i = 0; i < ans.length; i++) {
System.out.print(ans[i] + " ");
}
}
}
from collections import deque
class Solution:
# Function to get the maximum sliding window
def maxSlidingWindow(self, arr, k):
n = len(arr) # Size of array
# To store the answer
ans = []
# Deque data structure
dq = deque()
# Traverse the array
for i in range(n):
# Update deque to maintain current window
if dq and dq[0] <= (i - k):
dq.popleft()
# Maintain the monotonic (decreasing)
# order of elements in deque
while dq and arr[dq[-1]] <= arr[i]:
dq.pop()
# Add current element's index to the deque
dq.append(i)
# Store the maximum element from
# the first window possible
if i >= (k - 1):
ans.append(arr[dq[0]])
# Return the stored result
return ans
# Creating an instance of Solution class
sol = Solution()
# Array and window size
arr = [4, 0, -1, 3, 5, 3, 6, 8]
k = 3
# Function call to get the maximum sliding window
ans = sol.maxSlidingWindow(arr, k)
print("The maximum elements in the sliding window are:", ans)
class Solution {
// Function to get the maximum sliding window
maxSlidingWindow(arr, k) {
const n = arr.length; // Size of array
// To store the answer
const ans = [];
// Deque data structure
const dq = [];
// Traverse the array
for (let i = 0; i < n; i++) {
// Update deque to maintain current window
if (dq.length && dq[0] <= (i - k)) {
dq.shift();
}
/* Maintain the monotonic (decreasing)
order of elements in deque */
while (dq.length && arr[dq[dq.length - 1]] <= arr[i]) {
dq.pop();
}
// Add current element's index to the deque
dq.push(i);
/* Store the maximum element from
the first window possible */
if (i >= (k - 1)) {
ans.push(arr[dq[0]]);
}
}
// Return the stored result
return ans;
}
}
// Array and window size
const arr = [4, 0, -1, 3, 5, 3, 6, 8];
const k = 3;
/* Creating an instance of
Solution class */
const sol = new Solution();
/* Function call to get the
maximum sliding window */
const ans = sol.maxSlidingWindow(arr, k);
console.log("The maximum elements in the sliding window are:", ans);
Time Complexity: O(N) (where N is the size of given array)
Space Complexity: O(N-K) + O(K)
Q: Why does the deque approach work in O(n) time?
A: The deque is monotonic decreasing, ensuring that each element is pushed only once and popped at most once, leading to an amortized O(n) complexity. Unlike brute force, we don’t repeatedly scan the window.
Q: Why do we store indices instead of values in the deque?
A: Indices help track validity of elements. Since the window moves right, older indices outside the window must be removed, which is easier with indices.
Q: How would you modify the solution to find the minimum sliding window instead of the maximum?
A: Instead of maintaining a monotonic decreasing deque, maintain a monotonic increasing deque, ensuring the front always holds the minimum.
Q: What if the sliding window moves by more than one step instead of 1?
A: If the step size is m, process only every mth element, ensuring validity of deque indices while skipping unnecessary updates.