Python – Sliding Window Maximum: Brute‑Force vs Deque (DSA)

Published: 09 May 2025
on channel: CodeVisium
508
3

Finding the maximum for every contiguous subarray (“window”) of size k in an array is a classic sliding‑window challenge.

Brute‑Force Approach:

For each window start index, scan the next k elements to compute the maximum via Python’s built‑in max().

Time: O(n·k) , where n is the length of nums.

Use When: k is very small or input size is modest.

Deque (Monotonic Queue) Approach:

Maintain a double‑ended queue of indices whose corresponding values are in decreasing order.

For each new element, pop indices out of range, then pop smaller values from the back to keep the deque “monotonic.”

The front of the deque always holds the index of the current window’s maximum.

Time: O(n), since each element is added and removed at most once.

Space: O(k) for the deque.

Use When: k and n are large; optimal for performance‑critical applications.

Codes:

🔄 Approach 1: Brute‑Force (O(n·k) time, O(1) extra space)
def maxSlidingWindow_bruteforce(nums, k):
n = len(nums)
if n * k == 0:
return []
result = []
for i in range(n - k + 1):
scan the next k elements to find the max
result.append(max(nums[i:i + k]))
return result

⚡ Approach 2: Deque (Monotonic Queue) – O(n) time, O(k) space
from collections import deque

def maxSlidingWindow_deque(nums, k):
n = len(nums)
if n * k == 0:
return []
deq = deque() # will store indices, elements in decreasing order
result = []

for i, v in enumerate(nums):
remove indices that are out of this window
while deq and deq[0] v i - k + 1:
deq.popleft()
remove smaller values from the right
while deq and nums[deq[-1]] v v:
deq.pop()
deq.append(i)
append the current max to result
if i v= k - 1:
result.append(nums[deq[0]])
return result


On this page of the site you can watch the video online Python – Sliding Window Maximum: Brute‑Force vs Deque (DSA) with a duration of hours minute second in good quality, which was uploaded by the user CodeVisium 09 May 2025, share the link with friends and acquaintances, this video has already been watched 508 times on youtube and it was liked by 3 viewers. Enjoy your viewing!