🌟 Introduction

The sliding window maximum is a common problem in data structures and algorithms. It asks us to find the maximum value in every window of size k as we slide the window across an array. While the problem looks simple, solving it efficiently is very important in real-world applications like stock market analysis, signal processing, system monitoring, and competitive programming.

A naive solution takes O(n·k) time, which becomes very slow when the input size is large. But with the right approach, we can solve this in O(n) linear time.

📊 What is the Sliding Window Maximum Problem?

Imagine you have an array of numbers, and you place a window of size k on it. The window covers k consecutive elements. As you slide the window from left to right, you want to know the maximum element in each window.

Example

Array = [1, 3, -1, -3, 5, 3, 6, 7], window size = 3

Windows and their maximums:

Final Output = [3, 3, 5, 5, 6, 7]

⚡ Naive Approach (Inefficient)

🚀 Best Approach: Using Deque (Double-Ended Queue)

The deque-based solution is the best way to solve the sliding window maximum problem in O(n) linear time. A deque is a data structure that allows insertion and deletion from both ends efficiently.

💡 Key Idea

👉 This way, each element is added and removed at most once → Total O(n).

🖥️ Python Implementation

from collections import deque

def sliding_window_max(nums, k):
    dq = deque()
    result = []

    for i in range(len(nums)):
        # 1. Remove indices outside the current window
        while dq and dq[0] <= i - k:
            dq.popleft()

        # 2. Remove smaller elements from the back
        while dq and nums[dq[-1]] < nums[i]:
            dq.pop()

        # 3. Add current element's index
        dq.append(i)

        # 4. Record the maximum for windows of size k
        if i >= k - 1:
            result.append(nums[dq[0]])

    return result

# Example
nums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(sliding_window_max(nums, k))  # Output: [3, 3, 5, 5, 6, 7]

🔍 Why Deque Works Efficiently

  1. Each element is processed once → added and removed from deque only once.

  2. Deque always stores useful candidates → smaller elements that can’t be maximum are removed quickly.

  3. Maximum is always at the front → constant-time access for every window.

Thus, total time complexity = O(n).

🌍 Real-World Applications

✅ Summary

The best way to solve the sliding window maximum problem in linear time is by using a deque (double-ended queue). This method ensures:

This algorithm is widely used in stock market analysis, monitoring systems, gaming, and competitive programming. By mastering the deque-based approach, you can handle large datasets efficiently and build high-performance solutions.