Skip to main content

4.3 Double-Ended Queues (Deques) & Two-Stack Queue Simulation

πŸ“šModule 04 β€’ Queues & BuffersTopic 4.3⏱️14 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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 O(1)\mathcal{O}(1) 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 (Θ(1)\Theta(1) amortized), linear stream architectures achieve total positional flexibility.


πŸ”„ General, Input-Restricted & Output-Restricted Deques​

When backing a Deque with a circular array of capacity NN, stepping backward leftward (insertFront or deleteRear) MUST add +N+N before modulo to avoid negative C/Java remainders:

prevIndex(i)=(iβˆ’1+N)β€Šmodβ€ŠN\text{prevIndex}(i) = (i - 1 + N) \bmod N

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

Input-Restricted Deque

πŸ“₯
Dominant Architecture / Domain1 Entry Door β€’ 2 Exit Doors
  • β€’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.
"Single intake belt feeding emergency exit hatches at both ends."
Output-Restricted

Output-Restricted Deque

πŸ“€
Dominant Architecture / Domain2 Entry Doors β€’ 1 Exit Door
  • β€’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.
"Dual-entry intake converging into a unified single exit channel."

πŸ” 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: LIFO(LIFO(S))=FIFO(S)\text{LIFO}(\text{LIFO}(S)) = \text{FIFO}(S). Dedicate S1S_1 (Inbound) to enqueue and S2S_2 (Outbound) to dequeue β€” pouring S1β†’S2S_1 \to S_2 lazily ONLY when S2S_2 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​

πŸ“Problem Statement: Two-Stack Trace & Input-Restricted Deque Permutationtheorem
  1. Trace S1 (Inbound) and S2 (Outbound) across enqueue(10), enqueue(20), enqueue(30), dequeue(), enqueue(40), dequeue(), dequeue() starting from empty stacks.
  2. On an Input-Restricted Deque (insertions only at REAR, deletions at both FRONT and REAR), prove whether [4, 1, 3, 2] can be generated from ascending input 1, 2, 3, 4.

Step-by-Step Solution:​

  1. Two-Stack Queue Trace (40 buffered separately from S2):

    • After enqueue(10, 20, 30): S1=[10,20,30], S2=[]
    • dequeue(): S2 empty β€…β€ŠβŸΉβ€…β€Š\implies pour S1 -> S2 (S2=[30,20,10]), pop 10 β€…β€ŠβŸΉβ€…β€Š\implies S1=[], S2=[30,20]
    • enqueue(40): push straight to S1 (S1=[40], S2=[30,20]) β€” S2 untouched!
    • dequeue(), dequeue(): pops 20, then 30 straight from S2 in O(1)\mathcal{O}(1)!
  2. Input-Restricted Deque Reachability [4, 1, 3, 2]:

    • Execute insertRear(1, 2, 3, 4) β€…β€ŠβŸΉβ€…β€Š[1,2,3,4]\implies [1, 2, 3, 4].
    • deleteRear() emits 4, leaving [1, 2, 3].
    • deleteFront() emits 1 (impossible in a single Stack!), leaving [2, 3].
    • deleteRear() emits 3, deleteFront() emits 2 β€…β€ŠβŸΉβ€…β€Š\implies [4, 1, 3, 2] IS REACHABLE!

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. Why must implementing a Queue use at least 2 Stacks, and implementing a Stack use 2 Queues?
    • A single container locks one access order (LIFO vs FIFO). Two stacks enjoy Θ(1)\Theta(1) amortized batch flips, whereas simulating a Stack with 2 Queues forces Θ(n)\Theta(n) element rotation per push or pop!
  2. What is the only difference between Input-Restricted and Output-Restricted Deques?
    • Input-Restricted locks writes (insert) to 1 end (2 read doors); Output-Restricted locks reads (delete) to 1 end (2 write doors).
  3. Why does Python's collections.deque use a doubly-linked list of fixed-size array blocks?
    • Combines O(1)\mathcal{O}(1) double-ended growth with tiny pointer ratio and great CPU cache locality!
Common Interview Traps: Architectural Trade-Offs
  • Pouring S2 Back Into S1 After Every dequeue(): Immediately moving remaining items from S2 back to S1 destroys O(1)\mathcal{O}(1) amortization, turning every dequeue() into Θ(n)\Theta(n)! Keep elements sitting in S2 until it empties!
  • Negative Remainder Bug in Circular insertFront: (front - 1) % N evaluates to -1 in C/C++/Java when front == 0. Always write (front - 1 + N) % N!
  • Equating Stack & Input-Restricted Deque Permutations: [4, 1, 3, 2] is invalid from 1 Stack (413 pattern blocked!) yet completely valid using deleteFront() 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.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.