0
0
DSA Pythonprogramming~3 mins

Why Sliding Window Maximum Using Deque in DSA Python?

Choose your learning style9 modes available
The Big Idea

Discover how to find the highest number in every group without checking each group again and again!

The Scenario

Imagine you have a long list of daily temperatures, and you want to find the highest temperature for every 3-day period. Doing this by checking each 3-day group one by one feels like repeating the same work over and over.

The Problem

Manually checking each group means looking at many numbers again and again. This takes a lot of time and can easily cause mistakes, especially if the list is very long.

The Solution

Using a sliding window with a deque helps keep track of the highest numbers efficiently. It moves through the list just once, updating the highest value quickly without rechecking everything.

Before vs After
Before
for i in range(len(nums) - k + 1):
    print(max(nums[i:i+k]))
After
from collections import deque
window = deque()
for i in range(len(nums)):
    # update window and print max
What It Enables

This method lets you find maximum values in moving windows fast, even for huge lists, saving time and effort.

Real Life Example

Stock traders use this to find the highest stock price in the last few days quickly, helping them make smart decisions.

Key Takeaways

Manual checking repeats work and is slow.

Deque keeps track of max values efficiently.

Sliding window moves through data once, saving time.