4.3 Double-Ended Queues (Deques) & Two-Stack Queue Simulation
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy:β
Think of a two-door subway car. Passengers can board or exit through either the front door or the back door β letting urgent commuters skip ahead or letting drivers evacuate either end. Meanwhile, if you only own two one-way dead-end tunnels (two LIFO stacks), routing people into Tunnel 1 and reversing them into Tunnel 2 once turns dead-ends into a smooth FIFO through-station!
π» Bridging to Computer Science:β
A Double-Ended Queue (Deque) permits insertions and deletions at both FRONT and REAR (and subsumes both Stacks and FIFO Queues by simply ignoring two primitives). Paired with Two-Stack Amortized Reversal ( amortized), linear stream architectures achieve total positional flexibility.
πTable of Contents
π General, Input-Restricted & Output-Restricted Dequesβ
When backing a Deque with a circular array of capacity , stepping backward leftward (insertFront or deleteRear) MUST add before modulo to avoid negative C/Java remainders:
Two restricted specializations restrict either entry or exit to 1 end while freeing both operations at the opposite door:
Input-Restricted Deque vs. Output-Restricted Deque
Two classical restricted Double-Ended Queue specializations
Input-Restricted Deque
- β’Insertion allowed ONLY at ONE END (typically REAR via insertRear).
- β’Deletion allowed at BOTH ENDS (deleteFront AND deleteRear).
- β’Generates strictly more permutations than a single Stack or Queue.
Output-Restricted Deque
- β’Deletion allowed ONLY at ONE END (typically FRONT via deleteFront).
- β’Insertion allowed at BOTH ENDS (insertFront AND insertRear).
- β’Enables express urgent bypass straight onto FRONT of line.
π Two-Stack FIFO Queue Simulation (Amortized Constant Time)β
Implementing a FIFO Queue requires a minimum of 2 Stacks, because reversing an inverted stream restores identity: . Dedicate (Inbound) to enqueue and (Outbound) to dequeue β pouring lazily ONLY when becomes empty:
π Real-World Production Context: Work-Stealing & Sliding Windowsβ
Deque Engines in Schedulers & Streaming
Two-ended access unlocks work-stealing thread pools and linear-time sliding windows
Chase-Lev Work-Stealing Pools
Go / Tokio / Java ForkJoin- Worker thread pushes and pops fine-grained subtasks LIFO from its own FRONT for L1 cache heat.
- Idle neighbor cores steal older parent chunks FIFO from REAR to reduce contention.
Monotonic Sliding Window Extrema
Stream Analytics / Trading- Drops expired timestamps from FRONT and dominated smaller values from REAR in O(n) total.
- Answers rolling k-window max/min without O(n log k) tree overhead.
0-1 BFS Shortest Paths
Graph Routing (0 / 1 Weights)- Pushes zero-weight transitions onto FRONT and unit-weight transitions onto REAR.
- Solves {0, 1}-weighted graphs in pure O(V + E), bypassing Dijkstra heaps!
Undo/Redo Ring Buffers
Desktop Editors / CAD- Bounded fixed-capacity Deque drops oldest history from FRONT while appending latest edits onto REAR.
- Caps memory cleanly during marathon sessions.
π Numerical Applications & Worked Examplesβ
- Trace
S1(Inbound) andS2(Outbound) acrossenqueue(10), enqueue(20), enqueue(30), dequeue(), enqueue(40), dequeue(), dequeue()starting from empty stacks. - On an Input-Restricted Deque (insertions only at
REAR, deletions at bothFRONTandREAR), prove whether[4, 1, 3, 2]can be generated from ascending input1, 2, 3, 4.
Step-by-Step Solution:β
-
Two-Stack Queue Trace (
40buffered separately fromS2):- After
enqueue(10, 20, 30):S1=[10,20,30], S2=[] dequeue():S2empty pourS1 -> S2(S2=[30,20,10]), pop10S1=[], S2=[30,20]enqueue(40): push straight toS1(S1=[40], S2=[30,20]) βS2untouched!dequeue(), dequeue(): pops20, then30straight fromS2in !
- After
-
Input-Restricted Deque Reachability
[4, 1, 3, 2]:- Execute
insertRear(1, 2, 3, 4). deleteRear()emits4, leaving[1, 2, 3].deleteFront()emits1(impossible in a single Stack!), leaving[2, 3].deleteRear()emits3,deleteFront()emits2[4, 1, 3, 2]IS REACHABLE!
- Execute
π― Exam & Interview Pitfall Checkβ
- Why must implementing a Queue use at least 2 Stacks, and implementing a Stack use 2 Queues?
- A single container locks one access order (
LIFOvsFIFO). Two stacks enjoy amortized batch flips, whereas simulating a Stack with 2 Queues forces element rotation perpushorpop!
- A single container locks one access order (
- What is the only difference between Input-Restricted and Output-Restricted Deques?
- Input-Restricted locks writes (
insert) to 1 end (2read doors); Output-Restricted locks reads (delete) to 1 end (2write doors).
- Input-Restricted locks writes (
- Why does Python's
collections.dequeuse a doubly-linked list of fixed-size array blocks?- Combines double-ended growth with tiny pointer ratio and great CPU cache locality!
- Pouring
S2Back IntoS1After Everydequeue(): Immediately moving remaining items fromS2back toS1destroys amortization, turning everydequeue()into ! Keep elements sitting inS2until it empties! - Negative Remainder Bug in Circular
insertFront:(front - 1) % Nevaluates to-1in C/C++/Java whenfront == 0. Always write(front - 1 + N) % N! - Equating Stack & Input-Restricted Deque Permutations:
[4, 1, 3, 2]is invalid from 1 Stack (413pattern blocked!) yet completely valid usingdeleteFront()on an Input-Restricted Deque!
π Navigation & Next Stepsβ
Next, we complete Module 04 by discarding pure positional indices in favor of rank-ordered queues: Topic 4.4 β Priority Queue ADT, FIFO Tie-Breaking & Container Duality.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.