Sliding Window Maximum
LeetCode 239 · কঠিন · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Monotonic decreasing deque; front = window max.
আমি Sliding Window Maximum (LeetCode 239) এভাবে সমাধান করেছি — Monotonic Queue প্যাটার্নের একটি কঠিন প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Keep a deque of indices whose values are decreasing from front to back. The front is always the maximum of the current window. A new value evicts smaller values from the back (they can never be a max again), and indices that slid out of the window leave from the front.
Approach
- 1
Pop expired indices from the front.
- 2
Pop indices with smaller or equal values from the back.
- 3
Append the current index.
- 4
Once the first window is full, record nums[dq[0]].
আমি কীভাবে সমাধান করেছি
Monotonic dequePythonO(n) time · O(k) space
class Solution:
def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
#monotonic deque
"""
nums = [1,3,-1,-3,5,3,6,7], k = 3
monotonically decreasing deque
front back
a) Remove indices from front if these are expired or outside the current window
b) Remove indices from back if their corresponding values are smaller or eqaul to the current element
c) front = always contains the candidate maximum
d) back = candidate may be removed because a larger element arrivec
"""
result=[]
dq = deque([])
n = len(nums)
for i in range(n):
#expired/out of window items remove from front
while dq and dq[0]<=i-k:
dq.popleft()
#Remove indices from back if their corresponding values are smaller or eqaul to the current element
while dq and nums[dq[-1]]<=nums[i]:
dq.pop()
dq.append(i)
#window is complete
if i>=k-1:
#keep the candidate maximum
result.append(nums[dq[0]])
return resultSliding Window Maximum — সাধারণ প্রশ্ন
Sliding Window Maximum-এর পেছনে intuition কী?
Keep a deque of indices whose values are decreasing from front to back. The front is always the maximum of the current window. A new value evicts smaller values from the back (they can never be a max again), and indices that slid out of the window leave from the front.
Sliding Window Maximum (LeetCode 239) কীভাবে সমাধান করবেন?
1. Pop expired indices from the front. 2. Pop indices with smaller or equal values from the back. 3. Append the current index. 4. Once the first window is full, record nums[dq[0]].
Sliding Window Maximum-এর time আর space complexity কত?
Time: O(n)। Space: O(k)। (Accepted approach: Monotonic deque।)
Sliding Window Maximum-এ সাধারণ ভুলগুলো কী?
Store indices, not values — you need them to expire elements.