









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










The two data structures that quietly run your call stack, your browser's
back button, your OS scheduler, and half of your coding interview.
A complete, accuracy-checked reference — from first principles to interview-ready patterns.
DEEP RESEARCH NOTES Stack & Queue
Stack & Queue — Data Structures Deep Dive Page 1
Before We Begin — Why This Topic Deserves 15
Minutes of Your Time
n Did You Know? The “call stack” that every running program uses to keep track of function calls is a literal Stack data structure. When a program crashes with a StackOverflowError , it means the call stack (implemented using the exact LIFO principle you are about to learn) ran out of memory — usually because of infinite or excessive recursion.
Here is why interviewers and system designers keep coming back to these two structures:
F They are everywhere. Undo/redo in editors, browser history, recursion, expression evaluators, CPU task scheduling, printer queues, BFS traversal, and caching systems (like LRU cache) all rely directly on Stack or Queue behaviour. F They are interview staples. A huge share of “easy-to-medium” coding interview questions — Valid Parentheses, Next Greater Element, Sliding Window Maximum, Implement Queue using Stacks — are really just Stack/Queue pattern-recognition problems in disguise. F They build intuition for everything else. Trees are traversed using stacks (DFS) and queues (BFS). Graphs use both. Even dynamic programming and backtracking borrow the “push state, explore, pop state” mental model directly from stacks.
n The One-Line Mental Model Stack = a pile of plates — you can only add or remove from the top (Last In, First Out). Queue = a ticket line — people join at the back and are served from the front (First In, First Out). Every operation, use case, and interview question in this document is just a variation on these two pictures.
1.1 What Is an Abstract Data Type (ADT)?
An Abstract Data Type is a conceptual model that defines a set of data and the operations that can be performed on it, without specifying how those operations are implemented internally. An ADT describes what a structure does (its behaviour and rules), not how it does it (the code or memory layout). Stack and Queue are the two most fundamental linear ADTs after the plain list/array, because they restrict access to data in a very specific, rule-based way.
Formally, an ADT is specified by three things: the data it holds, the operations allowed on that data, and the constraints on how those operations may be used. For a Stack, the constraint is “only touch the top”. For a Queue, the constraint is “add at the back, remove from the front”.
1.2 Why Stack and Queue Matter in DSA
1.3 Real-World Analogies
n Stack — A Pile of Plates In a cafeteria, clean plates are stacked one on top of another. You always take the plate from the top , and new plates are always placed on top too. You cannot pull a plate out from the middle or bottom without disturbing the whole pile. This is exactly LIFO : Last In, First Out.
n Queue — A Ticket Counter Line At a ticket counter, the first person to join the line is the first person to be served, and every new person joins at the back of the line. Nobody can “cut” to the front or leave from the middle in a fair system. This is exactly FIFO : First In, First Out.
2.1 Definition and the LIFO Principle
A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle: the most recently added element is always the first one to be removed. All insertions and deletions happen from a single end, conventionally called the top of the stack.
2.2 Core Operations
Operation Description Time Complexity
push(x) Insert element x at the top of the stack. O(1)
pop() Remove and return the top element. O(1)
peek() / top() Return the top element without removing it. O(1)
isEmpty() Check whether the stack has zero elements. O(1)
isFull() (Array-based only) Check if capacity is reached. O(1)
size() Return the number of elements currently stored. O(1)
2.3 Implementations
A fixed or dynamically-resizing array is used, along with an integer index ( top ) that tracks the current top position. push() increments top and writes the new value; pop() reads the value at top and decrements it.
class ArrayStack: def init(self, capacity): self.data = [None] * capacity self.top = -
def push(self, x): self.top += 1 self.data[self.top] = x
def pop(self): val = self.data[self.top] self.top -= 1 return val
With a fixed-size array, push() fails once capacity is reached (stack overflow). With a dynamic array (like Python's list or Java's ArrayList), push() is O(1) amortised — occasional resizing costs O(n), but this cost is spread out over
Every time a function is called, the runtime pushes a new “stack frame” (containing local variables and the return address) onto the call stack. When the function returns, its frame is popped. Recursion works precisely because of this LIFO behaviour — the most recently called (innermost) function always finishes and returns first.
Stacks are used to convert infix expressions (e.g. a + b * c) to postfix or prefix form (the classic Shunting Yard algorithm uses an operator stack), and to evaluate postfix or prefix expressions directly by pushing operands and popping them when an operator is encountered.
To check whether brackets like ( ), { }, [ ] are correctly matched and nested, an opening bracket is pushed onto a stack; when a closing bracket appears, the stack's top is popped and checked for a match. If the stack is empty at a closing bracket, or non-empty at the end, the expression is invalid.
Text editors and design tools keep an “undo stack” of previous states or actions. Pressing Undo pops the most recent action and reverses it (often pushing it onto a parallel “redo stack”).
Problems like maze solving, N-Queens, and Depth-First Search (DFS) rely on a stack (explicit or via recursion) to remember earlier states so the algorithm can backtrack to them when a path leads to a dead end.
Many browsers model the “Back” functionality using a stack of visited pages: visiting a new page pushes it on top, and pressing Back pops the current page to reveal the previous one.
n Worked Example — Valid Parentheses Logic For the string {[()]}: push '{', push '[', push '(', see ')' → pop '(' 3 match, see ']' → pop '[' 3 match, see '}' → pop '{' 3 match. Stack is empty at the end → the string is valid.
4.1 Definition and the FIFO Principle
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle: the element that has been in the queue the longest is the first one removed. Insertions happen at the rear (back) and deletions happen at the front.
4.2 Core Operations
Operation Description Time Complexity
enqueue(x) Insert element x at the rear of the queue. O(1)
dequeue() Remove and return the element at the front. O(1)*
front() / peek() Return the front element without removing it. O(1)
rear() Return the last (most recently added) element. O(1)
isEmpty() Check whether the queue has zero elements. O(1)
* Only O(1) with a circular array or linked list. A naive (non-circular) array queue that shifts all remaining elements forward after every dequeue() costs O(n) per dequeue — this is why circular queues exist (see Section 5).
4.3 Implementations
A plain array queue has a problem: after several enqueue/dequeue cycles, the front index creeps forward and space at the beginning of the array goes to waste even though the array isn't logically full. The fix is a circular queue , where the front and rear indices wrap around to index 0 using the modulo operator once they reach the end of the array.
The basic FIFO queue described above — strict insertion at rear, removal at front.
An array-based queue where front and rear indices wrap around using modulo arithmetic, eliminating wasted space and giving true O(1) enqueue/dequeue.
Elements are served based on priority rather than arrival order — the element with the highest (or lowest) priority is dequeued first, regardless of insertion time. Typically implemented with a binary heap , giving O(log n) insert and O(log n) extract-highest-priority, with O(1) peek at the top priority element.
Insertion and deletion are allowed at both ends — front and rear. A deque can behave like a stack, a queue, or both at once. Two restricted variants exist: an input-restricted deque (insertion only at one end, deletion at both) and an output-restricted deque (deletion only at one end, insertion at both).
5.1 Queue Applications
Aspect Stack Queue
Order principle LIFO (Last In, First Out) FIFO (First In, First Out)
Insertion point Top only Rear only
Deletion point Top only Front only
Number of ends used One (top) Two (front & rear)
Core operations push, pop, peek enqueue, dequeue, front, rear
Typical time complexity O(1) for all core ops O(1) for all core ops (array must be circular)
Common uses Recursion, undo/redo, DFS, expression parsing
Scheduling, BFS, buffering, spooling
Real-world analogy Stack of plates Ticket counter line
n Choosing Between Them Ask: “Does the most recently added item need to be handled first (Stack), or does fairness / arrival order matter (Queue)?” If neither fits — for example, you need priority-based ordering — reach for a Priority Queue. If you need access from both ends, reach for a Deque.
n Pattern Recognition Tip
If a problem asks for “next greater/smaller element”, “span”, or “maximum/minimum in every sliding window” — it is almost always a monotonic stack or monotonic deque problem in disguise, solvable in O(n) instead of the naive O(n²).
Given a string of brackets, determine if it is valid (every opening bracket has a matching closing bracket in the correct order). Push opening brackets; on a closing bracket, pop and check it matches. Time: O(n), Space: O(n).
For every element in an array, find the first element to its right that is strictly greater. Traverse right to left (or left to right with a monotonic decreasing stack), pushing indices and popping whenever the current element is greater than the stack's top. Time: O(n), Space: O(n).
A very common warm-up question: implement push/pop/peek using only an array (handling resizing) or a singly linked list (handling head/tail pointers correctly), and implement enqueue/dequeue as a circular buffer or with two pointers on a linked list.
Design a cache with get(key) and put(key, value) that evicts the Least Recently Used item when it exceeds capacity, both in O(1). The standard solution combines a HashMap (for O(1) lookup) with a Doubly Linked List (to maintain usage order and remove/move nodes in O(1)) — the doubly linked list acts as a deque-like structure, where the most-recently-used item sits at one end and the least-recently-used sits at the other.
As explained in Section 7.5, maintain a monotonic decreasing deque of indices. Time: O(n), Space: O(k).
A set of petrol pumps are arranged in a circle, each with a given amount of fuel and a given fuel cost to reach the next pump. The task is to find a starting pump from which a truck can complete the entire circular tour without running out of fuel. A queue-based simulation models this directly: start from pump 0, enqueue it, and keep a running fuel balance while moving to the next pump; whenever the balance goes negative, dequeue (reject) the starting pump, move the start to the next pump, and reset the balance. If the total fuel available is at least the total cost across the whole circuit, exactly one valid starting point exists, and this single pass finds it in O(n) time.
n people stand in a circle; starting from person 1, every k-th person is eliminated until one remains. A circular queue simulates this directly: dequeue k–1 people and immediately re-enqueue them (they survive this round), then dequeue and discard the k-th person. Repeat until one person is left in the queue.
n Practice Strategy Don't just memorise these solutions. For every new problem, first ask: “Does the most recent item matter most (Stack), or does order of arrival matter most (Queue), or do I need both ends (Deque)?” Recognising the pattern is 80% of solving these problems quickly.