CodexBloom - Programming Q&A Platform

Unexpected Results in Sliding Window Maximum Algorithm Using Deque in Python 3.10

👀 Views: 29 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
python algorithms deque Python

I've been banging my head against this for hours... I'm working on a personal project and I'm implementing the sliding window maximum algorithm using a deque in Python 3.10 but I'm getting unexpected results when testing with edge cases. Specifically, my implementation fails for negative numbers and a small window size. My current approach is as follows: ```python from collections import deque def max_sliding_window(nums, k): if not nums or k == 0: return [] result = [] dq = deque() # stores indices of useful elements for i in range(len(nums)): # Remove indices of elements not in the sliding window while dq and dq[0] < i - k + 1: dq.popleft() # Remove indices of all elements smaller than the current element while dq and nums[dq[-1]] < nums[i]: dq.pop() dq.append(i) # Start adding results after the first k elements if i >= k - 1: result.append(nums[dq[0]]) return result ``` When I run the following test case: ```python nums = [1, -1, 3, 5, 2, 8, 6] k = 3 print(max_sliding_window(nums, k)) # Expected: [3, 5, 8, 8] ``` The output I receive is `[1, 3, 5, 8]`, which is incorrect. I suspect that the scenario might be with how I'm managing the deque during the transitions between negative and positive numbers. I've tried printing the contents of the deque at various stages, and it seems like it's maintaining indices correctly, but the maximum is not updating as expected for the sliding window. Can anyone point out what might be going wrong in my implementation? I've also considered edge cases where `k` is larger than the list size, but that seems to work fine since I handle empty inputs initially. Any insights would be appreciated! Could this be a known issue? I'm working in a Windows 11 environment.