Skip to main content

DSAPath14 mincore

deque Patterns

deque patterns use collections.deque for BFS, queues, double-ended updates, bounded windows, and sliding-window state.

DifficultyCore
TierTier 2
ModulePython Practice
LanguagesPython

Why This Matters

collections.deque is the Python queue structure you actually want for BFS and many sliding window tasks. It gives O(1) appends and pops from both ends.

Core Idea

Use deque when both ends matter.

MethodRole
appendpush right
appendleftpush left
popremove right
popleftremove left
maxlenkeep a bounded recent history

Non-Example or Failure Mode

list.pop(0) removes the first item but shifts the whole list. In BFS, that can turn a clean O(V + E) traversal into much slower code.

Runnable Drill

deque BFS and sliding window drill

Output will appear here.

Common Mistakes

MistakeCorrection
Using list.pop(0) for BFS.Use deque.popleft.
Forgetting to mark BFS nodes before enqueue.Mark when appending so duplicates do not pile up.
Using maxlen when old values still need explicit cleanup logic.maxlen discards silently; use manual pops if you need to update sums/counts.
Treating deque like a random-access list.It is built for end operations, not indexed scans.

Diagnostic Questions

Question typeQuestionAnswer signal
DefinitionWhat does collections.deque optimize?Appending and popping at both ends.
Example / non-exampleIs deque the default BFS queue?Yes.
ComputationWhat method removes the oldest queue item?popleft.
TransferWhy can maxlen help sliding window review?It keeps only the most recent k items.

Exercises

Beginner:

  • Replace a list queue with deque.
  • Use appendleft and pop to model a double-ended buffer.
  • Track the last three values with maxlen=3.

Intermediate:

  • Implement level-order tree traversal with deque.
  • Build a sliding-window maximum using a monotonic deque.

Challenge:

  • Compare BFS runtime with list.pop(0) and deque.popleft on a large grid.

References