Whether you’re preparing for interviews or building real-world systems, mastering the deque
data structure and the sliding window technique will help you solve a class of problems quickly and efficiently.
This post will walk you through:
- ✅ What is a
deque
- ✅ How it differs from
list
- ✅ What is the sliding window technique
- ✅ Real-life analogies, visuals, and code
- ✅ The kinds of questions interviewers ask — and what answers they expect
🔷 What is deque
?
deque
stands for double-ended queue, and it lives in Python’s collections
module. It allows:
- Adding/removing elements from both ends
- Constant-time operations at either end
- A much better choice than
list
for queue-like or sliding window problems
✅ Import and usage:
from collections import deque
dq = deque()
dq.append(1) # [1]
dq.appendleft(0) # [0, 1]
dq.pop() # [0]
dq.popleft() # []
🧱 Visualizing a deque
Left End Right End
| |
⬅ appendleft(x) [A, B, C] append(x) ➡
➡ popleft() pop() ⬅
You can think of it like a tunnel or conveyor belt where things can move in and out from either direction.
📌 Real-Life Examples
Real Life | deque Analogy |
---|---|
Train with two doors | People board/exit from either side |
Call center ticket queue | Oldest ticket first (FIFO) |
Undo/Redo feature | Push/pop from opposite ends |
Temperature buffer | Remove oldest, add latest |
❌ Why list
Can Be a Problem
Operation | list | deque |
---|---|---|
append() | ✅ O(1) | ✅ O(1) |
pop() | ✅ O(1) | ✅ O(1) |
insert(0, x) | ❌ O(n) | ✅ O(1) (appendleft ) |
pop(0) | ❌ O(n) | ✅ O(1) (popleft ) |
So if you’re using list.pop(0)
or list.insert(0, x)
, you’re losing performance — deque
solves this.
✅ The Sliding Window Technique (With Visuals and Examples)
🔍 What Is It?
The sliding window technique is used when you want to examine a subarray or substring of size k
, and move that “window” across the full input without recomputing everything.
❓ Common Questions Interviewers Ask
- “How do you find the max sum of subarray of size k?”
- “How do you find the longest substring without repeating characters?”
- “How would you process a live stream of numbers for moving max/min?”
✅ They’re all sliding window problems.
⚠️ Brute-Force Solution (Slow)
nums = [1, 3, 5, 2, 8, 1]
k = 3
max_sum = 0
for i in range(len(nums) - k + 1):
max_sum = max(max_sum, sum(nums[i:i+k]))
- ❌ Time:
O(n * k)
- You’re recalculating the sum each time
✅ Efficient Sliding Window (O(n) time)
def max_sum_k(nums, k):
window_sum = sum(nums[:k])
max_sum = window_sum
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k]
max_sum = max(max_sum, window_sum)
return max_sum
💡 Here’s how it works:
- You maintain the sum of a moving window
- When the window slides forward:
- Subtract the value leaving
- Add the value entering
🧱 Visual Explanation
Example: nums = [1, 3, 5, 2, 8, 1], k = 3
Window 1: [1, 3, 5] → sum = 9
Window 2: [3, 5, 2] → sum = 10 (add 2, remove 1)
Window 3: [5, 2, 8] → sum = 15 (add 8, remove 3)
Window 4: [2, 8, 1] → sum = 11
You move forward one index at a time, reusing work.
🔥 Advanced Problem: Sliding Window Maximum
Problem:
Find the max in every window of size
k
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output:[3, 3, 5, 5, 6, 7]
✅ Interview-Ready Answer Using deque
from collections import deque
def max_sliding_window(nums, k):
dq = deque()
result = []
for i in range(len(nums)):
# Remove out-of-window indices
while dq and dq[0] <= i - k:
dq.popleft()
# Remove smaller elements from the end
while dq and nums[dq[-1]] < nums[i]:
dq.pop()
dq.append(i)
if i >= k - 1:
result.append(nums[dq[0]])
return result
🔍 Step-by-Step Visual Explanation
Let’s walk through the input nums = [1, 3, -1, -3, 5, 3, 6, 7]
with k = 3
.
🔹 Initial State:
i = 0
: nums[0] = 1deque
:[0]
→ stores index- No result yet (window not full)
🔹 i = 1 → nums[1] = 3
- Compare
nums[1] > nums[0] → 3 > 1
, so remove index0
(we remove smaller values from back) - Add index
1
deque
:[1]
🔹 i = 2 → nums[2] = -1
-1 < 3
, keep1
- Add index
2
deque
:[1, 2]
- Now
i >= k-1
, so result →nums[1] = 3
✅ First window [1, 3, -1] → max = 3
🔹 i = 3 → nums[3] = -3
- Index
1
is in range → keep it -3 < -1
, keep- Add index
3
deque
:[1, 2, 3]
- Result →
nums[1] = 3
✅ Window [3, -1, -3] → max = 3
🔹 i = 4 → nums[4] = 5
- Remove index
1
(out of window:1 <= 4-3
) - Remove index
3
(nums[3] = -3 < 5) - Remove index
2
(nums[2] = -1 < 5) deque
becomes empty- Add index
4
deque
:[4]
- Result →
nums[4] = 5
✅ Window [-1, -3, 5] → max = 5
🔹 i = 5 → nums[5] = 3
- Keep index
4
(5 > 3) - Add index
5
deque
:[4, 5]
- Result →
nums[4] = 5
✅ Window [-3, 5, 3] → max = 5
🔹 i = 6 → nums[6] = 6
- Remove index
4
and5
(both nums < 6) deque
: []- Add index
6
deque
:[6]
- Result →
nums[6] = 6
✅ Window [5, 3, 6] → max = 6
🔹 i = 7 → nums[7] = 7
- Remove index
6
(6 < 7) - Add index
7
deque
:[7]
- Result →
nums[7] = 7
✅ Window [3, 6, 7] → max = 7
✅ Final Result:
pythonCopyEdit[3, 3, 5, 5, 6, 7]
🤔 Why Use deque
?
- Tracks only relevant indices
- Removes outdated and smaller values
- Always gives max at the front
- ✅ Makes entire algorithm O(n) instead of O(nk)
✅ Summary Diagram (Text Form)
nums[i] deque (indices) Max Value
0 1 [0] -
1 3 [1] -
2 -1 [1, 2] 3
3 -3 [1, 2, 3] 3
4 5 [4] 5
5 3 [4, 5] 5
6 6 [6] 6
7 7 [7] 7
🔎 Explanation:
dq
stores indices, not values- The max value is always at dq[0]
- We remove:
- Outdated indices (outside the window)
- Smaller elements that don’t help
✅ Time: O(n)
✅ Space: O(k)
✅ Real-Life Analogy of Sliding Window
Imagine you’re looking out a moving bus window:
- You see 3 people walking down the sidewalk (your window size)
- Every second, 1 person leaves your view and 1 new person enters
- You only need to update what you already saw, not start over
That’s the sliding window.
📌 When to Use deque
for Sliding Windows
Scenario | Why deque Helps |
---|---|
Moving max/min in stream | O(1) head/tail updates |
Temperature readings over time | Drop old, add new |
Log monitoring | Real-time event window |
Competitive programming | Clean + optimal |
Interview problems | ✅ Best-practice technique |
✅ Summary
Feature | Benefit |
---|---|
deque | Fast O(1) pop/append both ends |
Sliding window | Efficient O(n) moving logic |
Ideal for | Queues, stacks, stream buffers |
Avoid list.pop(0) | Use deque.popleft() instead |
Interview essential | Shows algorithmic thinking |
🏁 Final Thoughts
✅ deque
is your best friend for:
- Real-time queues
- Palindromes
- Undo/redo systems
- And sliding window problems like max, min, and stream analysis
✅ The sliding window pattern helps you avoid brute force and write O(n)
solutions for otherwise slow problems.
Next time you’re tempted to use list.pop(0)
, remember: deque.popleft()
is the real hero.
Leave a Reply