Python โ Sliding Window Maximum (Monotonic Queue Trick) ๐ #PythonDSA #SlidingWindow
About this lesson
๐ง Problem Given an array nums and a window size k, find the maximum element in every window of size k. Example: nums = [1,3,-1,-3,5,3,6,7] k = 3 Output: [3,3,5,5,6,7] โ Brute Force For every window: Take max of k elements Time complexity: O(n * k) โ Optimal Approach โ Monotonic Queue (Deque) Key idea: Maintain a deque in decreasing order So: Front always = maximum element Remove smaller elements from back ๐ง Why This Works Each element enters and leaves deque only once Ensures O(n) complexity ๐ฅ Core Logic Remove elements outside window Remove smaller elements (not useful) Add current element Front = maximum ๐งช Example Walkthrough nums = [1,3,-1,-3,5] k = 3 Window evolution: [1,3,-1] โ 3 [3,-1,-3] โ 3 [-1,-3,5] โ 5 โฑ๏ธ Complexity Approach Time Space Brute O(nk) O(1) Deque O(n) O(k) ๐ง Concepts Used โ Sliding Window โ Monotonic Queue โ Deque (Double-ended queue) โ Greedy optimization โ Two pointers ๐ฏ Interview Importance This pattern is used in: Sliding window problems Stock problems Range queries Real-time analytics Maximum/minimum tracking ๐ค Interview Questions & Answers Q1. Why use deque instead of heap? Deque gives O(n), heap gives O(n log k) Q2. Why remove smaller elements? They will never be maximum in future windows Q3. Why store indices instead of values? To track window boundaries Q4. What is monotonic queue? A queue that maintains sorted order (increasing/decreasing) Q5. Can we solve using heap? Yes, but slower and less optimal ๐งฐ Real-World Applications Real-time stock analysis Signal processing CPU load monitoring Streaming data systems Sliding analytics Codes: # ๐ Brute Force (O(n * k)) def max_sliding_window_naive(nums, k): result = [] for i in range(len(nums) - k + 1): result.append(max(nums[i:i+k])) return result # โก Optimal: Monotonic Deque (O(n)) from collections import deque def max_sliding_window(nums, k): deq = deque() # stores indices result = [] for i in r
DeepCamp AI