Stack and Queue Simulator
Visualize LIFO stack and FIFO queue operations with step-by-step animations. Push and pop items onto the stack, enqueue and dequeue items from the queue — colour-coded highlights show additions and removals. No signup, runs entirely in your browser.
Stack and Queue Use Cases
Call stack
Every function call pushes a frame onto the call stack. When a function returns, its frame is popped. Recursive functions fill the stack one frame per recursive call — deep recursion causes a stack overflow.
Balanced parentheses
The classic stack problem: scan a string and push every opening bracket. When you hit a closing bracket, pop and check that it matches. If the stack is empty when you pop, or non-empty at end, the brackets are unbalanced.
BFS with a queue
Breadth-First Search uses a queue to process graph nodes level by level. Enqueue the start node, then repeatedly dequeue a node, process it, and enqueue its unvisited neighbours. This guarantees the shortest path in unweighted graphs.
Monotonic stack
A monotonic stack maintains elements in increasing or decreasing order. It solves problems like "next greater element" in O(n). Push elements; whenever the current element is greater than the top, pop and record the answer.
Frequently Asked Questions
What is a stack?
A stack is a Last In, First Out (LIFO) data structure. The most recently added element is the first one removed. Real-world analogies include a stack of plates or the browser back button. Operations: push (add to top), pop (remove from top), peek (see top without removing).
What is a queue?
A queue is a First In, First Out (FIFO) data structure. Elements are added at the rear and removed from the front — like a real queue or a print job queue. Operations: enqueue (add to rear), dequeue (remove from front), peek (see front).
When should I use a stack vs a queue?
Use a stack for problems that need reversal, backtracking, or nesting — function call stacks, undo history, expression evaluation, DFS traversal. Use a queue for problems that process items in arrival order — BFS traversal, task scheduling, producer-consumer patterns.
What is the time complexity of stack and queue operations?
Push, pop, enqueue, and dequeue are all O(1) when implemented correctly. Peek is also O(1). An array-based implementation is efficient but may require O(n) resizing occasionally.
What is a deque?
A deque (double-ended queue) supports insertion and deletion at both ends. It generalises both stack and queue behaviour. Python's collections.deque and Java's ArrayDeque implement this.
Is my data saved?
No. All data exists only in your browser session and is not sent to any server.