By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
"This pattern appears in 1 out of every 3 onsite interviews—master it, and you’ll solve sliding window problems in linear time while others struggle with brute force. It’s the difference between ‘We’ll get back to you’ and ‘When can you start?’"
Before diving into Sliding Window with Deque (Monotonic Queue), ensure you understand: 1. Sliding Window Technique – Maintaining a window of elements that satisfies a condition (e.g., max/min in a subarray). 2. Deque (Double-Ended Queue) – A data structure that allows O(1) insertion/deletion at both ends. 3. Monotonic Queue – A deque where elements are kept in sorted order (increasing or decreasing) to efficiently track min/max.
[3, 1, 4, 2]
[1, 2]
[4, 2]
k
nums = [1,3,-1,-3,5,3,6,7]
k=3
[3,3,5,5,6,7]
Follow these 6 steps for every sliding window + deque problem:
nums[i]
k = 1
O(n)
O(k)
Problem: Given an array nums and an integer k, return the maximum in every sliding window of size k.
nums
Solution (Step-by-Step): 1. Window Type: Fixed-size (k). 2. Deque Type: Monotonic decreasing (to track max). 3. Initialize: Empty deque. 4. Iterate: - Remove indices outside the current window (i - k). - Remove elements from the back that are ≤ nums[i] (they can’t be max). - Add i to the deque. - If i ≥ k-1, record nums[deque[0]] (front is the max). 5. Edge Cases: - k = 1 → Return nums as-is. - nums = [] → Return []. 6. Time: O(n), Space: O(k).
i - k
i
i ≥ k-1
nums[deque[0]]
nums = []
[]
Python Code:
from collections import deque def maxSlidingWindow(nums, k): dq = deque() res = [] for i, num in enumerate(nums): # Remove indices outside the window while dq and dq[0] <= i - k: dq.popleft() # Remove elements smaller than current from the back while dq and nums[dq[-1]] < num: dq.pop() dq.append(i) # Record max once window is valid if i >= k - 1: res.append(nums[dq[0]]) return res
Why This Works: - The deque always maintains the largest element at the front for the current window. - By removing smaller elements from the back, we ensure O(1) max access at any time.
Problem: Given an array nums and an integer k, find the length of the longest subarray where all elements are ≤ k.
Solution (Step-by-Step): 1. Window Type: Dynamic (expands/shrinks). 2. Deque Type: Monotonic increasing (to track min). 3. Initialize: Empty deque, left = 0, max_len = 0. 4. Iterate: - While nums[i] > k, move left forward (shrink window). - Remove elements from the back that are ≥ nums[i] (they can’t be min). - Add i to the deque. - Update max_len = max(max_len, i - left + 1). 5. Edge Cases: - All elements ≤ k → Return len(nums). - nums = [] → Return 0. 6. Time: O(n), Space: O(n) (worst case).
left = 0
max_len = 0
nums[i] > k
left
max_len = max(max_len, i - left + 1)
len(nums)
0
from collections import deque def longestSubarray(nums, k): dq = deque() left = 0 max_len = 0 for i, num in enumerate(nums): # Remove elements > k from the left while num > k: left += 1 if dq and dq[0] < left: dq.popleft() num = nums[i] # Re-check after moving left # Maintain monotonic increasing deque while dq and nums[dq[-1]] >= num: dq.pop() dq.append(i) max_len = max(max_len, i - left + 1) return max_len
Why This Works: - The deque tracks the smallest element in the current window, ensuring we can shrink the window efficiently when nums[i] > k.
Problem: Given an array nums and an integer k, find the number of subarrays where the sum equals k.
Solution (Step-by-Step): 1. Window Type: Dynamic (prefix sums). 2. Deque Type: Monotonic increasing (to track prefix sums). 3. Initialize: prefix = {0: 1}, sum = 0, count = 0. 4. Iterate: - sum += nums[i]. - If sum - k exists in prefix, add prefix[sum - k] to count. - Maintain a monotonic deque of prefix sums to optimize lookups (optional for follow-up). - Update prefix[sum]. 5. Edge Cases: - nums = [] → Return 0. - All elements 0 → Return n(n+1)/2. 6. Time: O(n), Space: O(n).
prefix = {0: 1}
sum = 0
count = 0
sum += nums[i]
sum - k
prefix
prefix[sum - k]
count
prefix[sum]
n(n+1)/2
from collections import defaultdict def subarraySum(nums, k): prefix = defaultdict(int) prefix[0] = 1 sum_ = 0 count = 0 for num in nums: sum_ += num if sum_ - k in prefix: count += prefix[sum_ - k] prefix[sum_] += 1 return count
Follow-up (Using Deque for Optimization): If the problem requires subarrays of length ≤ m, use a deque to track valid prefix sums in a sliding window.
m
Why This Works: - The prefix sum technique allows O(1) lookups for sum - k. - The deque optimizes the window when constraints are added (e.g., max subarray length).
dq[0] <= i - k
O(1)
collections.deque
k = len(nums)
n
k > n
"Alright, let’s lock this in. Sliding window with deque is all about tracking min/max in linear time. Here’s the playbook:
k=1
This pattern shows up in LeetCode 239, 862, 1425—and it’s a FAANG favorite. If you see ‘sliding window’ or ‘subarray min/max’, reach for the deque. Now go crush that interview!
Now go solve it like a pro! ?
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.