Linked Lists, Stacks, and Queues Questions
Pointer-based linear structures and the classic problems built on them: singly, doubly and circular linked lists (reversal whole, partial and in groups of k, cycle detection and cycle start with fast/slow pointers, intersection, middle and nth-from-end, merging two or k sorted lists, sorting a list, reordering, palindrome check, rotation, partitioning, duplicate removal, deep copy with random pointers, flattening child lists, sentinel nodes), implementing lists in C, C++ and Rust with attention to pointer handling, ownership and cleanup, array versus linked-list trade-offs including cache locality, stacks, queues and deques (array, linked and circular-buffer implementations, ring-buffer full versus empty, queue from two stacks, min stack, round-robin scheduling), monotonic stacks and queues (next greater element, largest rectangle in a histogram, sliding-window maximum), stack-based expression and bracket evaluation (balanced brackets, Reverse Polish Notation, infix to postfix, calculators), and structure-level builds such as an LRU cache from a hash map plus doubly linked list, undo/redo history, and variants like persistent or unrolled lists. Foundational for coding interviews and for understanding how higher-level structures are built. Concurrent and lock-free queues, memory allocators, general graph traversal, heaps and cache-eviction system design are covered elsewhere.
Determine whether a singly linked list is a palindrome in O(n) time and O(1) extra space. If you modify the list, restore it before returning.
Sample Answer
Direct answer
Find the end of the first half with slow and fast pointers, reverse the second half in place, walk the first half and the reversed second half together comparing values, then reverse the second half again to restore the list before returning. O(n) time, O(1) extra space.
The idea in plain words
A palindrome reads the same forwards and backwards, so the first value must equal the last, the second must equal the second-to-last, and so on. In an array that is two indices moving toward each other. A singly linked list only links forwards, so the "from the back" half is unreachable. The fix is to turn the second half around: after reversing it, both halves start at their own ends of the original list and can be read forward at the same time.
Example: 1 -> 2 -> 3 -> 2 -> 1 has middle 3. The second half 2 -> 1 becomes 1 -> 2. Comparing 1 -> 2 (first half) against 1 -> 2 (reversed second half) says palindrome; the middle node 3 needs no partner.
The brute force and why this is better
Copying the values to a Python list and comparing it with its reverse (vals == vals[::-1]) is O(n) time but O(n) extra space, which the question rules out. Recursing to compare front and back on the way out is also O(n) space (the call stack is the memory where each active function call keeps its variables), and hits Python's recursion limit (the cap of about 1000 nested calls that makes Python raise RecursionError instead of crashing) near 1000 nodes. Reversing half the list uses O(1) space; the cost is that you must undo your change.
Code
class ListNode:
__slots__ = ("val", "next")
def __init__(self, val=0, next=None):
self.val, self.next = val, next
def build(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def show(head):
return " -> ".join([str(v) for v in to_list(head)] + ["None"])
def reverse(head):
prev = None
while head:
head.next, prev, head = prev, head, head.next # see "Reading reverse and the restore"
return prev
def is_palindrome(head, trace=False):
if head is None or head.next is None:
return True
slow, fast = head, head
while fast.next and fast.next.next: # slow stops at the end of the first half
slow, fast = slow.next, fast.next.next
second_head = reverse(slow.next) # reverse the second half in place
slow.next = second_head # reconnect, so the list is one whole chain while it is compared
if trace:
print(f" second half reversed, list now: {show(head)}")
left, right = head, second_head
result = True
while right: # the second half is never longer than the first
if trace:
print(f" compare {left.val} with {right.val}")
if left.val != right.val:
result = False
break
left, right = left.next, right.next
slow.next = reverse(second_head) # undo the reversal, whatever the result
return result
for vals in ([1, 2, 3, 2, 1], [1, 2, 2, 1], [1, 2, 3, 4], [1, 2]):
head = build(vals)
print(f"{show(head)}")
print(" palindrome:", is_palindrome(head, trace=True), "| list after:", show(head))
print("empty:", is_palindrome(None), "| one node:", is_palindrome(build([5])))
import random
random.seed(3)
for _ in range(500):
size = random.randint(0, 9)
vals = [random.randint(0, 2) for _ in range(size)] # tiny alphabet so palindromes are common
head = build(vals)
before = []
node = head
while node:
before.append(node)
node = node.next
assert is_palindrome(head) == (vals == vals[::-1])
after = []
node = head
while node:
after.append(node)
node = node.next
assert before == after # same node objects in the same order
print("500 random cases correct and list restored: ok")
Run in a python:3.12 container (CPython 3.12.15), it prints:
1 -> 2 -> 3 -> 2 -> 1 -> None
second half reversed, list now: 1 -> 2 -> 3 -> 1 -> 2 -> None
compare 1 with 1
compare 2 with 2
palindrome: True | list after: 1 -> 2 -> 3 -> 2 -> 1 -> None
1 -> 2 -> 2 -> 1 -> None
second half reversed, list now: 1 -> 2 -> 1 -> 2 -> None
compare 1 with 1
compare 2 with 2
palindrome: True | list after: 1 -> 2 -> 2 -> 1 -> None
1 -> 2 -> 3 -> 4 -> None
second half reversed, list now: 1 -> 2 -> 4 -> 3 -> None
compare 1 with 4
palindrome: False | list after: 1 -> 2 -> 3 -> 4 -> None
1 -> 2 -> None
second half reversed, list now: 1 -> 2 -> None
compare 1 with 2
palindrome: False | list after: 1 -> 2 -> None
empty: True | one node: True
500 random cases correct and list restored: ok
Reading the trace
For 1 -> 2 -> 3 -> 2 -> 1, slow stops at the middle node 3, so the second half is 2 -> 1 and reverses to 1 -> 2, giving the printed 1 -> 2 -> 3 -> 1 -> 2. The comparisons are 1 with 1 and 2 with 2, and the middle node is skipped. For the even list 1 -> 2 -> 2 -> 1, slow stops at the first 2, the halves have two nodes each, and again both comparisons match. For 1 -> 2 -> 3 -> 4 the very first comparison (1 with 4) fails and the loop stops early, yet "list after" still prints the original list, because the restore line runs regardless of the result. The final line is an assert check on 500 seeded random lists over the values 0 to 2 (so palindromes are common): the answer matches vals == vals[::-1] and the same node objects are in the same order afterwards.
Reading reverse and the restore
The line head.next, prev, head = prev, head, head.next is a simultaneous assignment. Python first evaluates the right side into three values (the old prev, the old head, and the old head.next), then assigns them to head.next, prev and head. Because the right side is already evaluated, the old head.next survives even though head.next is overwritten. Written as separate statements it is following = head.next, head.next = prev, prev = head, head = following.
The program below runs those statements on 7 -> 8 -> 9, then replays the middle of the palindrome check on 1 -> 2 -> 2b -> 1b (the b only tells the two equal values apart), then prints where slow stops for lengths 2 to 7. Pointers are written node->next:
class ListNode:
def __init__(self, val):
self.val, self.next = val, None
def chain(values):
nodes = [ListNode(v) for v in values]
for a, b in zip(nodes, nodes[1:]):
a.next = b
return nodes
def arrows(nodes):
return " ".join(f"{n.val}->{n.next.val if n.next else 'None'}" for n in nodes)
# reverse() on the three nodes 7 -> 8 -> 9, one statement at a time
nodes = chain([7, 8, 9])
print("start ", arrows(nodes))
prev, head = None, nodes[0]
while head:
following = head.next # the old head.next, saved first
head.next = prev
prev = head
head = following
print(f"head.next flipped {arrows(nodes)} prev={prev.val} head={head.val if head else 'None'}")
# the palindrome 1 -> 2 -> 2 -> 1: split, reverse, reattach, compare, restore
nodes = chain(["1", "2", "2b", "1b"]) # b marks the second copy of a value
print("\nlist ", arrows(nodes))
slow = nodes[1] # the end of the first half
second_head = None
prev, cur = None, slow.next
while cur:
following = cur.next
cur.next = prev
prev, cur = cur, following
second_head = prev
print("reversed second half", arrows(nodes), " (slow.next still points at the old start)")
slow.next = second_head
print("slow.next = reversed", arrows(nodes))
prev, cur = None, second_head
while cur:
following = cur.next
cur.next = prev
prev, cur = cur, following
slow.next = prev
print("restored ", arrows(nodes))
# where does slow stop?
print("\nlength slow stops at position first half second half")
for length in range(2, 8):
ns = chain(list(range(1, length + 1)))
slow = fast = ns[0]
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
print(f"{length:>6} {slow.val:>22} {slow.val:>10} {length - slow.val:>11}")
Run with Python 3.12.15, it prints:
start 7->8 8->9 9->None
head.next flipped 7->None 8->9 9->None prev=7 head=8
head.next flipped 7->None 8->7 9->None prev=8 head=9
head.next flipped 7->None 8->7 9->8 prev=9 head=None
list 1->2 2->2b 2b->1b 1b->None
reversed second half 1->2 2->2b 2b->None 1b->2b (slow.next still points at the old start)
slow.next = reversed 1->2 2->1b 2b->None 1b->2b
restored 1->2 2->2b 2b->1b 1b->None
length slow stops at position first half second half
2 1 1 1
3 2 2 1
4 2 2 2
5 3 3 2
6 3 3 3
7 4 4 3
In the reverse of 7 8 9, each row flips one arrow and moves prev and head one node along, so the reversed part grows from the left. In the palindrome replay, after the second half 2b -> 1b is reversed, 2b->None and 1b->2b, while 2->2b still points at the old start. The statement slow.next = second_head makes 2->1b, so the list now reads 1 -> 2 -> 1b -> 2b (the same shape as the trace lines above), and the comparison reads 1 against 1b and 2 against 2b. The restore reverses the second half again and points slow.next back at its new start, and the restored row equals the list row. The length table shows the claim in the edge cases: slow stops on the last node of the first half for every length, and the second half is never longer than the first.
The same method in C and C++
Compiled with gcc (C11) in a python:3.12 container, the C version prints:
#include <stdio.h>
#include <stdlib.h>
struct node { int val; struct node *next; };
static struct node *build(const int *v, int n) {
struct node *head = NULL;
for (int i = n - 1; i >= 0; i--) {
struct node *x = malloc(sizeof *x);
x->val = v[i];
x->next = head;
head = x;
}
return head;
}
static struct node *reverse(struct node *head) {
struct node *prev = NULL;
while (head) {
struct node *following = head->next;
head->next = prev;
prev = head;
head = following;
}
return prev;
}
static int is_palindrome(struct node *head) {
if (!head || !head->next) return 1;
struct node *slow = head, *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
struct node *second = reverse(slow->next);
slow->next = second; /* reconnect, so the list is one whole chain while it is compared */
int result = 1;
for (struct node *l = head, *r = second; r; l = l->next, r = r->next)
if (l->val != r->val) { result = 0; break; }
slow->next = reverse(second); /* restore on every path */
return result;
}
static void print_list(struct node *h) {
for (; h; h = h->next) printf("%d -> ", h->val);
printf("NULL\n");
}
int main(void) {
int a[] = {1, 2, 3, 2, 1}, b[] = {1, 2, 3, 4};
struct node *p = build(a, 5), *q = build(b, 4);
printf("palindrome: %d\n", is_palindrome(p));
print_list(p);
printf("palindrome: %d\n", is_palindrome(q));
print_list(q);
return 0;
}
palindrome: 1
1 -> 2 -> 3 -> 2 -> 1 -> NULL
palindrome: 0
1 -> 2 -> 3 -> 4 -> NULL
Compiled with g++ (C++17) in the same container, the C++ version prints:
#include <iostream>
#include <vector>
#include <memory>
struct Node {
int val;
Node *next;
Node(int v, Node *n = nullptr) : val(v), next(n) {}
};
Node *build(const std::vector<int> &v) {
Node *head = nullptr;
for (auto it = v.rbegin(); it != v.rend(); ++it) head = new Node(*it, head);
return head;
}
Node *reverse(Node *head) {
Node *prev = nullptr;
while (head) {
Node *following = head->next;
head->next = prev;
prev = head;
head = following;
}
return prev;
}
bool isPalindrome(Node *head) {
if (!head || !head->next) return true;
Node *slow = head, *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
Node *second = reverse(slow->next);
slow->next = second;
bool result = true;
for (Node *l = head, *r = second; r; l = l->next, r = r->next)
if (l->val != r->val) { result = false; break; } // break, not return: the restore below must run
slow->next = reverse(second);
return result;
}
void print(Node *h) {
for (; h; h = h->next) std::cout << h->val << " -> ";
std::cout << "null\n";
}
int main() {
Node *p = build({1, 2, 3, 2, 1}), *q = build({1, 2, 3, 4});
std::cout << std::boolalpha << isPalindrome(p) << "\n";
print(p);
std::cout << isPalindrome(q) << "\n";
print(q);
}
true
1 -> 2 -> 3 -> 2 -> 1 -> null
false
1 -> 2 -> 3 -> 4 -> null
Both use break, not an early return, so the restore line always runs. The demo does not free its nodes because it exits right after printing; production code would.
Complexity
- Time: O(n). Finding the middle is n/2 steps, reversing is n/2, comparing at most n/2, restoring n/2.
- Space: O(1): pointers only, no recursion and no copy of the values.
Edge cases and common mistakes
- Empty list and single node are palindromes (the early return).
- Odd versus even length: stopping the first loop when
fast.nextandfast.next.nextexist leavesslowon the last node of the first half in both cases, soslow.nextis always the start of the second half, and the middle node of an odd list stays in the first half unmatched. - Returning early on a mismatch without restoring the list: the caller is left with a list whose second half is backwards. The code uses
breakinstead of an earlyreturn False, so the restore line after the loop always runs. - Cutting the list in two (
slow.next = None) and forgetting to rejoin it at the end. This code reconnects the reversed second half toslowstraight after reversing it, so the list stays one whole chain during the comparison; restoring is then reversing the second half again and pointingslow.nextat the result. The reconnect line is not what makes the restore possible (the savedsecond_headis enough); the restore line is. - Comparing nodes instead of
.val. - Loop condition
while left and rightis also correct; the second half is never longer than the first, sowhile rightis enough.
Running the code
Save as palindrome_list.py and run python palindrome_list.py with Python 3.12 (standard library only).
When would you build a stack or a queue on an array (or dynamic array) versus a linked list? Compare memory locality, resizing, worst-case versus amortized operation cost, and in Python the practical choice between a list and collections.deque.
Sample Answer
Direct answer
Default to an array for both. A stack on a dynamic array (a growable array such as a Python list) and a queue on a circular buffer (a fixed array used as a ring: indices that run off the end wrap back to slot 0) or collections.deque have O(1) amortized operations and keep data compact, so they are fast in practice. Choose a linked list only when you need a hard O(1) worst case on every single call, or when you hold node pointers and splice in the middle. In Python, use list for a stack and collections.deque for a queue; list.pop(0) is the classic mistake.
The terms
- Amortized O(1): the average cost per operation over a long run is constant, even though one operation occasionally costs more.
- Worst-case O(1): every single call is constant, with no occasional expensive call.
- Locality: the processor loads memory in small blocks called cache lines (commonly 64 bytes), so reading neighbouring addresses is cheap and chasing scattered addresses is slow.
- Resizing: when a fixed-size array is full, allocate a bigger one and copy every element across.
- Latency spike: one operation that is occasionally far slower than the typical one, which a caller sees as a stall.
- Allocator overhead: the bookkeeping memory the allocator (
mallocin C, the object allocator in Python) keeps for each separate allocation, so a small node costs more than its own fields. - Typed array: an array whose slots hold raw values of one fixed type (such as 4-byte ints), instead of pointers to separate objects.
Comparison
| Array / dynamic array | Linked list | |
|---|---|---|
| Push or enqueue | O(1) amortized, one call occasionally copies everything | O(1) worst case, one node allocation |
| Pop or dequeue | O(1) for the stack end; the front of a plain array is O(n) unless you use a circular buffer | O(1) at the head (with a tail pointer for enqueue) |
| Memory per element | One slot (a pointer, or the raw value in a typed array) | A node: value plus a next pointer, plus allocator overhead |
| Locality | Slots are contiguous, so scans and bursts of pushes hit the cache | Nodes are scattered, each step is a possible cache miss |
| Resizing | Needed, with a latency spike on the unlucky call | None |
Why doubling makes resizing cheap on average
If the array doubles when full, a push that triggers a resize copies size elements, but the next size pushes copy nothing. Spread over all pushes the copying is a constant per push. The program below counts it, implements the linked queue, and measures memory per element in Python 3.12:
import sys
from array import array
from collections import deque
class DynArrayStack:
"""Stack on a fixed-capacity array that doubles when full. Counts element copies."""
def __init__(self):
self.cap = 1
self.slots = [None] * self.cap
self.size = 0
self.copies = 0 # total elements copied by all resizes
self.worst_push = 0 # most copies done by any single push
def push(self, x):
copied = 0
if self.size == self.cap:
bigger = [None] * (2 * self.cap)
for i in range(self.size):
bigger[i] = self.slots[i]
copied += 1
self.slots, self.cap = bigger, 2 * self.cap
self.slots[self.size] = x
self.size += 1
self.copies += copied
self.worst_push = max(self.worst_push, copied)
def pop(self):
self.size -= 1
x, self.slots[self.size] = self.slots[self.size], None
return x
class Node:
__slots__ = ("val", "next")
def __init__(self, val, next=None):
self.val, self.next = val, next
class LinkedQueue:
"""Queue on a singly linked list with head and tail pointers."""
def __init__(self):
self.head = self.tail = None
def enqueue(self, x):
node = Node(x)
if self.tail is None:
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeue(self):
node = self.head
self.head = node.next
if self.head is None:
self.tail = None
return node.val
n = 1000
s = DynArrayStack()
for i in range(n):
s.push(i)
print(f"array stack, {n} pushes: capacity {s.cap}, total copies {s.copies}, "
f"worst single push copied {s.worst_push}, copies per push {s.copies / n:.2f}")
q = LinkedQueue()
for i in range(5):
q.enqueue(i)
print("linked queue dequeues:", [q.dequeue() for _ in range(5)], "empty:", q.head is None and q.tail is None)
print("python", sys.version.split()[0], "bytes per element, 1000 ints already created:")
lst = list(range(n))
dq = deque(lst)
print(" list pointer array :", sys.getsizeof(lst) / n)
print(" deque :", sys.getsizeof(dq) / n)
print(" one linked Node :", sys.getsizeof(Node(0)))
work = deque([1, 2, 3])
work.append(4)
typed = array("i", range(n))
print(" array('i') item size:", typed.itemsize, "bytes, no per-int object needed")
print("deque as queue:", work.popleft(), "then as stack:", work.pop(), "left:", list(work))
Run in a python:3.12 container (CPython 3.12.15), it prints:
array stack, 1000 pushes: capacity 1024, total copies 1023, worst single push copied 512, copies per push 1.02
linked queue dequeues: [0, 1, 2, 3, 4] empty: True
python 3.12.15 bytes per element, 1000 ints already created:
list pointer array : 8.056
deque : 8.68
one linked Node : 48
array('i') item size: 4 bytes, no per-int object needed
deque as queue: 1 then as stack: 4 left: [2, 3]
The 1000 pushes copied 1023 elements in total, about one copy per push, yet the single worst push copied 512. That is the difference between amortized and worst case: the average is constant, but a latency-sensitive caller can still see one slow call. A linked queue never has such a call, but pays one allocation per element and 48 bytes per node here (not counting the stored value), against about 8 bytes per slot for the list. The array's contiguous slots are also why a loop over them is friendly to the cache: the last line printed by the next program shows that 1000 contiguous 8-byte slots span about 125 cache lines, while 1000 scattered nodes can touch up to 1000.
How the wrap-around works
A circular buffer keeps a head index (the oldest element) and a size. The next free slot is (head + size) % capacity, and removing moves head forward by one, also with % capacity. Nothing is ever shifted. This program uses 4 slots and prints the array and head after each step, with None marking an empty slot:
class RingQueue:
"""Queue in a fixed array of 4 slots; head and tail indices wrap with %."""
def __init__(self, capacity=4):
self.slots = [None] * capacity
self.head = 0 # index of the oldest element
self.size = 0
def enqueue(self, x):
tail = (self.head + self.size) % len(self.slots) # first free slot, wrapping
self.slots[tail] = x
self.size += 1
def dequeue(self):
x = self.slots[self.head]
self.slots[self.head] = None
self.head = (self.head + 1) % len(self.slots) # head moves forward, wrapping
self.size -= 1
return x
def show(self, label):
print(f"{label:<14} slots={self.slots} head={self.head} size={self.size}")
q = RingQueue()
for ch in "abc":
q.enqueue(ch)
q.show("enqueue a b c")
q.dequeue(); q.dequeue()
q.show("dequeue twice")
q.enqueue("d"); q.enqueue("e")
q.show("enqueue d e") # e lands in slot 0: the tail wrapped around
class BlockDeque:
"""Toy model of a deque: a chain of blocks of 4 slots (CPython uses 64)."""
def __init__(self):
self.blocks = [[]]
self.left = 0 # how many slots at the front of the first block are already removed
def append(self, x):
if len(self.blocks[-1]) == 4:
self.blocks.append([]) # last block full: link a new block
self.blocks[-1].append(x)
def popleft(self):
x = self.blocks[0][self.left]
self.left += 1
if self.left == len(self.blocks[0]) == 4:
self.blocks.pop(0) # first block fully consumed: drop it, no copying
if not self.blocks:
self.blocks.append([]) # it was the only block: keep one empty block for the next append
self.left = 0
return x
def show(self, label):
print(f"{label:<12} blocks={self.blocks} left={self.left}")
d = BlockDeque()
for i in range(6):
d.append(i)
d.show("append 0..5")
for _ in range(4):
d.popleft()
d.show("popleft x4")
d.popleft()
d.show("popleft x1")
n = 1000
print(f"1000 pointer slots of 8 bytes span about {n * 8 // 64} cache lines of 64 bytes when contiguous; "
f"1000 scattered nodes can touch up to {n} lines")
Run with Python 3.12.15, it prints:
enqueue a b c slots=['a', 'b', 'c', None] head=0 size=3
dequeue twice slots=[None, None, 'c', None] head=2 size=1
enqueue d e slots=['e', None, 'c', 'd'] head=2 size=3
append 0..5 blocks=[[0, 1, 2, 3], [4, 5]] left=0
popleft x4 blocks=[[4, 5]] left=0
popleft x1 blocks=[[4, 5]] left=1
1000 pointer slots of 8 bytes span about 125 cache lines of 64 bytes when contiguous; 1000 scattered nodes can touch up to 1000 lines
After "dequeue twice" the two front slots are empty but the queue's oldest element is c in slot 2. Enqueueing d fills slot 3, and e goes to slot (2 + 2) % 4 = 0: the tail wrapped around to reuse the freed front. That reuse is what a plain array queue lacks, and why list.pop(0) (shift everything left) is the alternative that costs O(n).
The same listing includes a toy model of how deque finds the next element: a chain of blocks (4 slots here, 64 in CPython) and a left offset into the first block. popleft just moves left; when the first block is used up it is unlinked as a whole, with no copying. The 6 appended values 0..5 fill one block and start a second, four popleft calls drop the first block, and the fifth only moves left to 1.
Python: list versus collections.deque
| Task | Use | Why |
|---|---|---|
| Stack | list with append and pop | Both at the end, O(1) amortized |
| Queue (FIFO, first-in first-out) | collections.deque with append and popleft | O(1) at both ends |
Queue by list.pop(0) | avoid | The Python docs state that lists incur O(n) memory movement costs for pop(0) and insert(0, v), because every remaining element shifts left |
| Random access in the middle | list | The docs say deque indexing is O(1) at both ends but O(n) in the middle |
| Compact numeric data | array.array | Stores raw machine values (4 bytes each for type code 'i' in the run above) rather than pointers to int objects, but it has the same O(n) cost at the front as a list |
In the CPython 3.12 source a deque is a doubly linked list of fixed-size blocks (64 slots each), so it is a hybrid: you get the cheap ends of a linked list with block-sized locality and no per-element node.
Pitfalls
- Treating "amortized O(1)" as "O(1) every time" when a hard latency bound matters (a real-time loop, a request path with a strict deadline).
- Using
list.pop(0)in a breadth-first search loop: the loop turns from O(n) into O(n^2) as the queue grows. - Forgetting that a plain array queue needs wrap-around (a circular buffer: head and tail indices that wrap with modulo) or it wastes the front slots.
- Picking a linked list "because insertion is O(1)": that is only true when you already hold the node; finding it is O(n).
When the choice flips
Pick the linked list if worst-case latency per call must be bounded, or you keep references to nodes and remove them from the middle (an LRU cache does this with a doubly linked list plus a hash map). Pick the array otherwise.
Running the code
Save the listing as stack_queue_demo.py and run python stack_queue_demo.py with Python 3.12. It uses only the standard library. Byte counts from sys.getsizeof are specific to CPython on a 64-bit platform (this run: aarch64).
Implement a stack on top of a dynamic array with push, pop, peek, is_empty and size. Push and pop must be O(1) amortized, and pop on an empty stack must raise a clear error. Also show how you would support a fixed maximum capacity.
Sample Answer
Direct answer
A stack is last-in first-out (LIFO): the item you pushed most recently is the first one you pop. On an array, the top of the stack is the end of the occupied part, so push writes at index size and pop reads at size - 1, both O(1). When the array is full, allocate one twice as large, copy the items over, and carry on; that one slow push is paid for by all the cheap ones, which is why push is O(1) AMORTIZED (averaged over a long sequence of operations, even though a single call can do O(n) work). Pop on an empty stack raises a clear custom error. A fixed maximum capacity is a size check in push that raises a "full" error, and the array can be allocated once at that size.
The idea in plain words
An array gives instant access to any slot by index but has a fixed length. Keep a counter size for how many slots are in use; everything at index size and beyond is free. Push means "put it at size, add one"; pop means "subtract one, hand back what is there". Nothing is ever shifted, which is why both are constant time. The only hard part is what to do when push finds the array full.
Why doubling and not "add a few slots"
If you grew by a fixed number of slots each time, say 10, every 10th push would copy the whole array. The copies are 10, then 20, then 30, and so on up to about n, which add up to 10 x (1 + 2 + ... + n/10) = 10 x (n/10)(n/10 + 1)/2, about n^2 / 20 items: quadratic. The driver prints 49,500 copies for 1000 pushes (n^2 / 20 = 50,000) and 499,950,000 for 100,000 pushes. Doubling makes resizes rarer as the stack grows. With starting capacity 1 and doubling, the resizes happen at sizes 1, 2, 4, 8, ... and copy 1, 2, 4, 8, ... items. A geometric series (each term double the one before) like that sums to less than the next term: 1 + 2 + 4 + 8 = 15, which is less than 16, and in general 1 + 2 + ... + 2^k = 2^(k+1) - 1. So the copies add up to less than the final capacity, and for n >= 1 the final capacity is less than 2n (it is the smallest power of two that is at least n), so n pushes copy fewer than 2n items in total: under 2 extra copies per push on average, which is constant. The driver measures it: for 100,000 pushes the total copies are 131,071, below 2n = 200,000.
class EmptyStackError(IndexError):
pass
class StackFullError(OverflowError):
pass
class ArrayStack:
"""Stack on a dynamic array that doubles when full. Optional fixed maximum capacity."""
def __init__(self, max_size=None):
if max_size is not None and max_size < 1:
raise ValueError("max_size must be at least 1")
self._max_size = max_size
# With a maximum, allocate it once and never resize; otherwise start tiny and double.
self._slots = [None] * (max_size if max_size is not None else 1)
self._size = 0
self.copies = 0 # element copies made by resizing, to measure the cost
def push(self, item):
if self._max_size is not None and self._size == self._max_size:
raise StackFullError(f"stack is full (max_size={self._max_size})")
if self._size == len(self._slots):
self._grow()
self._slots[self._size] = item
self._size += 1
def pop(self):
if self._size == 0:
raise EmptyStackError("pop from empty stack")
self._size -= 1
item = self._slots[self._size]
self._slots[self._size] = None # drop the reference so the object can be freed
return item
def peek(self):
if self._size == 0:
raise EmptyStackError("peek at empty stack")
return self._slots[self._size - 1]
def is_empty(self):
return self._size == 0
def size(self):
return self._size
def capacity(self):
return len(self._slots)
def _grow(self):
bigger = [None] * (2 * len(self._slots))
for i in range(self._size): # copy every current element once
bigger[i] = self._slots[i]
self.copies += self._size
self._slots = bigger
# Trace: size, capacity and total resize copies after each push
s = ArrayStack()
print("push size capacity copies_so_far")
for value in range(1, 10):
s.push(value)
print(f"{value:>4} {s.size():>4} {s.capacity():>8} {s.copies:>13}")
# Amortized cost: total copies for n pushes stays below 2n
for n in (10, 1000, 100_000):
s = ArrayStack()
for i in range(n):
s.push(i)
print(f"n={n:>6}: capacity {s.capacity():>6}, total copies {s.copies:>6}, 2n = {2 * n}")
# The geometric series by hand, and the fixed-growth alternative
print("resize copies 1 + 2 + 4 + 8 =", 1 + 2 + 4 + 8, "which is below the next capacity, 16")
def copies_with_fixed_growth(n, step=10):
"""Element copies made by n pushes when a full array grows by only `step` slots."""
capacity, size, copies = step, 0, 0
for _ in range(n):
if size == capacity:
copies += size
capacity += step
size += 1
return copies
for n in (1000, 100_000):
print(f"n={n:>6}: growing by 10 copies {copies_with_fixed_growth(n):>9} items, n*n/20 = {n * n // 20}")
# One push that is expensive: the push that triggers a resize
s = ArrayStack()
for i in range(8):
s.push(i)
before = s.copies
s.push(8)
print("the 9th push copied", s.copies - before, "elements")
# Errors and LIFO order
s = ArrayStack()
for bad in (s.pop, s.peek):
try:
bad()
except EmptyStackError as err:
print(f"{bad.__name__} on empty: {type(err).__name__}: {err}")
for x in "abc":
s.push(x)
print("peek:", s.peek(), "| pops:", s.pop(), s.pop(), s.pop(), "| empty:", s.is_empty())
# Fixed maximum capacity
small = ArrayStack(max_size=3)
for x in (10, 20, 30):
small.push(x)
try:
small.push(40)
except StackFullError as err:
print(f"{type(err).__name__}: {err}")
print("after the failed push the stack is unchanged:", small.size(), small.peek(), "| capacity", small.capacity(), "| resize copies", small.copies)
# The constructor rejects a maximum below 1
try:
ArrayStack(max_size=0)
except ValueError as err:
print(f"ValueError: {err}")
# pop clears its slot, so a popped object is freed once the caller drops it
import weakref
class Box:
pass
s = ArrayStack()
box = Box()
watcher = weakref.ref(box)
s.push(box)
del box
s.pop()
print("object freed after pop:", watcher() is None)
# Shrinking: resizes caused by 100 pop/push pairs on the boundary
def boundary_resizes(shrink_divisor, rounds=100):
capacity, size, resizes = 8, 5, 0
for _ in range(rounds):
size -= 1 # pop
if size == capacity // shrink_divisor: # shrink rule: halve the array
capacity //= 2
resizes += 1
if size == capacity: # push finds the array full
capacity *= 2
resizes += 1
size += 1 # push
return resizes
print("shrink at half full:", boundary_resizes(2), "resizes | at a quarter full:", boundary_resizes(4), "resizes")
# Compare with a plain list as the reference
import random
rng = random.Random(4)
mine, ref = ArrayStack(), []
for _ in range(5000):
if ref and rng.random() < 0.45:
assert mine.pop() == ref.pop()
else:
v = rng.randint(0, 99)
mine.push(v)
ref.append(v)
assert mine.size() == len(ref)
assert mine.is_empty() == (not ref)
if ref:
assert mine.peek() == ref[-1]
print("5000 random push/pop steps match a Python list")
Output:
push size capacity copies_so_far
1 1 1 0
2 2 2 1
3 3 4 3
4 4 4 3
5 5 8 7
6 6 8 7
7 7 8 7
8 8 8 7
9 9 16 15
n= 10: capacity 16, total copies 15, 2n = 20
n= 1000: capacity 1024, total copies 1023, 2n = 2000
n=100000: capacity 131072, total copies 131071, 2n = 200000
resize copies 1 + 2 + 4 + 8 = 15 which is below the next capacity, 16
n= 1000: growing by 10 copies 49500 items, n*n/20 = 50000
n=100000: growing by 10 copies 499950000 items, n*n/20 = 500000000
the 9th push copied 8 elements
pop on empty: EmptyStackError: pop from empty stack
peek on empty: EmptyStackError: peek at empty stack
peek: c | pops: c b a | empty: True
StackFullError: stack is full (max_size=3)
after the failed push the stack is unchanged: 3 30 | capacity 3 | resize copies 0
ValueError: max_size must be at least 1
object freed after pop: True
shrink at half full: 200 resizes | at a quarter full: 0 resizes
5000 random push/pop steps match a Python list
Worked trace
The first table is printed by the code. Capacity starts at 1. Push 1 fits. Push 2 finds the array full (size 1, capacity 1), doubles to 2 and copies 1 item. Push 3 doubles to 4 and copies 2 more (total 3). Push 4 does not resize. Push 5 doubles to 8 (total 7), and pushes 6, 7 and 8 fit. Push 9 doubles to 16 and copies 8, taking the total to 15 (1 + 2 + 4 + 8), and the "9th push copied 8 elements" line confirms that single push was the expensive one, while a push that does not trigger a resize copies nothing. Popping returns items in reverse order: after pushing a, b, c, the pops return c, b, a.
Empty stack and fixed capacity
- Pop and peek on an empty stack raise
EmptyStackError, a subclass of Python'sIndexError, with a message saying what went wrong. The alternative of returningNoneis ambiguous whenNoneis a legal item, and it hides the bug at the call site. - Fixed maximum capacity: pass
max_size. The array is allocated once with that many slots,pushcheckssize == max_sizeBEFORE touching anything and raisesStackFullError, so a failed push leaves the stack unchanged (the driver prints size 3, top 30, no resize copies). An error is the right default for a bounded stack; the other policies are to block the producer, or to drop the oldest item, and the choice depends on the caller. The constructor rejects a maximum below 1, and the driver prints thatValueError. popclears the slot it read (None), so the stack does not keep a reference to an object that has left it. Garbage collection is the runtime freeing objects that nothing refers to any more; a stale reference left in the array would keep such an object alive. The driver pushes an object, drops its own name for it, pops, and printsTruebecause a weak reference to the object is now dead; without the clearing line the same run printsFalse.
Complexity
push: O(1) amortized, O(n) in the worst single call (the one that doubles the array). With a fixed maximum there is never a resize, so each push is O(1) worst case.pop,peek,is_empty,size: O(1), worst case.- Space: O(n), with unused capacity of at most the used size when doubling (capacity is less than 2n for n pushes).
- This version never shrinks. If you add shrinking, halve the array when it is a QUARTER full, not half full: at exactly half, a push-pop-push-pop sequence on the boundary would resize on every call. The driver counts 200 resizes for 100 pop and push pairs when the rule is "shrink at half full" and 0 when it is "shrink at a quarter full".
In everyday Python code you would use a list (append and pop), which is already a dynamic array; the class above makes the array and the resize visible, which is what the question asks for.
Edge cases
- Empty stack:
pop,peekraise;is_emptyis True;sizeis 0. - One item, then pop: size returns to 0.
max_sizebelow 1 is rejected at construction (ArrayStack(max_size=0)raisesValueError).- The random test runs 5000 push and pop steps against a plain Python list, checking pop values, size,
is_emptyand peek at every step.
Common mistakes
- Growing by a constant and claiming O(1) push.
- Saying "O(1)" without "amortized" for a resizing push.
- Incrementing
sizebefore checking capacity, so a failed push leaves the stack in a corrupt state. - Forgetting to clear the popped slot, a memory leak (memory that stays in use although the program no longer needs it) in languages with garbage collection.
- Using
list.pop(0)orinsert(0, x)to put the top at the front: each is O(n).
Running the code
python array_stack.py
Python 3.12, standard library only.
What are the differences between a stack and a queue? Give at least four realistic software uses of each and explain why that structure is the right fit.
Sample Answer
The difference in one sentence
A stack hands back the item added most recently (last in, first out, LIFO). A queue hands back the item added least recently (first in, first out, FIFO). Everything else follows from which end you remove from.
| Stack | Queue | |
|---|---|---|
| Order | LIFO: newest out first | FIFO: oldest out first |
| Add | push on the top | enqueue at the back |
| Remove | pop from the top | dequeue from the front |
| Ends used | One end only | Two ends: add at one, remove at the other |
| Question it answers | "What was I doing most recently?" | "Who has been waiting longest?" |
| Python | list.append and list.pop | collections.deque with append and popleft |
| Cost per operation | O(1) | O(1) with deque; O(n) with list.pop(0) |
On the last two rows: the Python documentation says a deque has "approximately the same O(1) performance in either direction" for appends and pops at both ends, while a list incurs "O(n) memory movement costs for pop(0) and insert(0, v)". That is why a queue in Python is a deque, never list.pop(0). A deque (double-ended queue, pronounced "deck") is a sequence that adds and removes at both ends in O(1); using only one end for adds and the other for removes makes it a queue.
A runnable comparison
from collections import deque
PAIRS = {")": "(", "]": "[", "}": "{"}
def balanced(text, trace=False):
"""Stack: the most recent opener must be the first one closed."""
stack = []
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in PAIRS:
if not stack or stack.pop() != PAIRS[ch]:
if trace:
print(f" {ch!r}: mismatch, stack after the pop = {stack}")
return False
else:
continue
if trace:
print(f" {ch!r}: stack = {stack}")
return not stack
def bfs_order(graph, start, trace=False):
"""Queue: nodes are visited in the order they were discovered (nearest first)."""
seen, queue, order = {start}, deque([start]), []
while queue:
node = queue.popleft() # dequeue from the front: O(1)
order.append(node)
for neighbour in graph[node]:
if neighbour not in seen:
seen.add(neighbour)
queue.append(neighbour) # enqueue at the back: O(1)
if trace:
print(f" visited {node}: queue = {list(queue)}")
return order
if __name__ == "__main__":
s, q = [], deque()
for x in (1, 2, 3):
s.append(x); q.append(x)
print("push/enqueue 1,2,3 -> stack pops:", [s.pop() for _ in range(3)],
"| queue dequeues:", [q.popleft() for _ in range(3)])
print("balanced('{[()]}'):")
print(" ", balanced("{[()]}", trace=True))
print("balanced('([)]'):")
print(" ", balanced("([)]", trace=True))
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": [], "E": []} # each key lists its neighbours
print("BFS from A:")
print(" ", bfs_order(graph, "A", trace=True))
Run, it prints:
push/enqueue 1,2,3 -> stack pops: [3, 2, 1] | queue dequeues: [1, 2, 3]
balanced('{[()]}'):
'{': stack = ['{']
'[': stack = ['{', '[']
'(': stack = ['{', '[', '(']
')': stack = ['{', '[']
']': stack = ['{']
'}': stack = []
True
balanced('([)]'):
'(': stack = ['(']
'[': stack = ['(', '[']
')': mismatch, stack after the pop = ['(']
False
BFS from A:
visited A: queue = ['B', 'C']
visited B: queue = ['C', 'D']
visited C: queue = ['D', 'E']
visited D: queue = ['E']
visited E: queue = []
['A', 'B', 'C', 'D', 'E']
The first line is the whole difference: the same three items 1, 2, 3 go in, and the stack returns them reversed while the queue returns them in order. The bracket trace shows the stack's job (the most recent opener must be closed first, so the top of the stack is always the one that matters), and the breadth-first search (BFS, which visits nodes nearest the start first) trace shows the queue's job (nodes are handled in the order they were discovered, so everything one step from A is processed before anything two steps away).
The graph in that program is a dictionary from each node to the list of nodes it points to:
A -> B, C
B -> D
C -> D, E
D, E have no outgoing edges
A is one step from B and C, and two steps from D and E, which is why breadth-first search visits B and C before D and E.
The uses below each come with a short run:
from collections import deque
def eval_postfix(text):
"""Postfix: operators come after their operands. A stack holds the values waiting for an operator."""
stack = []
for token in text.split():
if token in "+-*":
right = stack.pop() # the most recent value is the right operand
left = stack.pop()
stack.append({"+": left + right, "-": left - right, "*": left * right}[token])
else:
stack.append(int(token))
print(f" token {token!r}: stack = {stack}")
return stack.pop()
print("3 4 + 2 * =", eval_postfix("3 4 + 2 *"))
def dfs_order(graph, start):
"""Same loop as the BFS above, with a stack in place of the queue."""
seen, stack, order = {start}, [start], []
while stack:
node = stack.pop() # take the most recent, not the oldest
order.append(node)
for neighbour in graph[node]:
if neighbour not in seen:
seen.add(neighbour)
stack.append(neighbour)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": [], "E": []}
print("graph: A -> B, C | B -> D | C -> D, E")
print("stack in place of queue, order:", dfs_order(graph, "A"))
def allow(requests, limit=3, window=10):
"""Sliding window: keep the timestamps of accepted requests from the last `window` seconds."""
recent, results = deque(), []
for t in requests:
while recent and recent[0] <= t - window: # expired: remove from the front
recent.popleft()
if len(recent) < limit:
recent.append(t) # accepted: add at the back
results.append((t, "accepted", list(recent)))
else:
results.append((t, "rejected", list(recent)))
return results
print("limit 3 requests per 10 seconds:")
for t, verdict, window_now in allow([1, 2, 3, 4, 12, 13]):
print(f" t={t:>2} {verdict:<8} window = {window_now}")
buffer, log = deque(), []
for step in ["make a", "make b", "make c", "take", "make d", "take", "take", "take"]:
if step.startswith("make"):
buffer.append(step[-1])
else:
log.append(buffer.popleft())
print("producer-consumer: items taken in order", log)
Run with Python 3.12.15, it prints:
token '3': stack = [3]
token '4': stack = [3, 4]
token '+': stack = [7]
token '2': stack = [7, 2]
token '*': stack = [14]
3 4 + 2 * = 14
graph: A -> B, C | B -> D | C -> D, E
stack in place of queue, order: ['A', 'C', 'E', 'D', 'B']
limit 3 requests per 10 seconds:
t= 1 accepted window = [1]
t= 2 accepted window = [1, 2]
t= 3 accepted window = [1, 2, 3]
t= 4 rejected window = [1, 2, 3]
t=12 accepted window = [3, 12]
t=13 accepted window = [12, 13]
producer-consumer: items taken in order ['a', 'b', 'c', 'd']
Read in order: the postfix line shows how a stack evaluates 3 4 + 2 * (postfix means each operator comes after its operands). Numbers are pushed; an operator pops the two newest values, applies itself, and pushes the result, so + turns [3, 4] into [7] and * turns [7, 2] into [14]. The depth-first line replaces the queue with a stack and the visit order changes to A C E D B: the newest discovered node is taken first, so the search goes deep along C before coming back to B. This version marks a node as seen when it is pushed, which is what keeps the code the same size as the BFS loop. On some graphs that marking gives an order no recursive depth-first search could produce; marking a node when it is popped, and pushing each node's neighbours in reverse order, gives exactly the recursive order (A B D C E here). For this graph A C E D B is a valid depth-first order. The rate limiter keeps the timestamps of accepted requests; the 4th request at time 4 is rejected because three accepted requests are still inside the window, and at time 12 the entries 1 and 2 have expired from the front. The last line is a producer-consumer buffer: one side makes items, the other takes them, and the items come out in the order they were made.
Where stacks fit (and why)
- Function calls. Each call pushes a frame (the local variables and the place to return to) and each return pops it. The most recently called function must finish first, which is LIFO. This is why a recursion that never stops overflows the call stack (Python stops it with a
RecursionErrorat its recursion limit, 1000 frames by default, instead of crashing). - Undo. Each edit is pushed; undo pops the newest one. You must undo the last change before the one before it.
- Bracket and expression parsing. The innermost open bracket closes first, so a stack of open brackets validates nesting, as in the trace above. Evaluating
3 4 + 2 *uses the same idea with values (see the postfix run above). - Depth-first search and backtracking. Keep a stack of places to return to; the most recent branch point is revisited first.
- Browser back button. Each page visited is pushed; Back pops the most recent one.
Where queues fit (and why)
- Job or task queues. Work should start in arrival order so no request waits forever behind later ones.
- Breadth-first search. Discovery order is processing order, which is what makes each level finish before the next starts (shortest path by edge count in an unweighted graph).
- Message queues and producer-consumer buffers. A message queue is a service that holds messages from senders until receivers are ready for them. One part of a system produces work faster than another consumes it; the queue absorbs the gap and keeps order.
- Print spooler or request buffer. Jobs print in the order submitted.
- Rate limiting with a sliding window. Timestamps of recent requests are appended at the back and expired ones are removed from the front.
Common mistakes
- Using
list.pop(0)as the dequeue. It is correct but O(n) per call, so a queue of n items costs O(n squared) to drain. - Reading an empty structure without a check:
popon an empty list orpoplefton an empty deque raisesIndexError. - Mixing up which structure BFS and DFS use. Swapping the queue for a stack changes the traversal from nearest-first to deepest-first, which does not give shortest paths.
- Describing a stack as "an array". It is a rule about access (only the top), and can sit on an array or a linked list.
Running the code
python stack_queue_demo.py # the first program
python stack_uses_demo.py # the second program, saved as its own file
Python 3.12, standard library only.
Implement a stack using a singly linked list with push, pop, peek, is_empty and size, all O(1). Compare the memory use and speed against an array-backed stack.
Sample Answer
The idea in plain words
A stack is last in, first out: the most recently pushed item is the first one popped. With a singly linked list, make the head the top of the stack. Pushing adds a new node in front of the head, and popping removes the head. Both touch only the front, so no walking is needed and each is O(1) in the worst case.
Keeping a size counter that you update on every push and pop makes size() O(1) as well. Without it you would have to walk the list to count.
Approach, step by step
- State:
_top(the head node, orNonewhen empty) and_size. push(v): createNode(v, next=old_top), make it the new_top, add 1 to_size.pop(): if empty, raiseIndexError. Otherwise remember the top node, move_topto itsnext, subtract 1, return the remembered value.peek(): return the top's value without changing anything; same empty check.is_empty():_top is None.size(): return_size.
The code
class Node:
__slots__ = ("value", "next")
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedStack:
def __init__(self):
self._top = None # the head of the list is the top of the stack
self._size = 0
def push(self, value):
self._top = Node(value, self._top)
self._size += 1
def pop(self):
if self._top is None:
raise IndexError("pop from empty stack")
node = self._top
self._top = node.next
self._size -= 1
return node.value
def peek(self):
if self._top is None:
raise IndexError("peek at empty stack")
return self._top.value
def is_empty(self):
return self._top is None
def size(self):
return self._size
def __str__(self):
out, cur = [], self._top
while cur:
out.append(str(cur.value))
cur = cur.next
return "top -> " + " -> ".join(out + ["None"])
s = LinkedStack()
for v in (10, 20, 30):
s.push(v)
print(f"push {v}: {s} size={s.size()}")
print("peek:", s.peek())
while not s.is_empty():
print(f"pop {s.pop()}: {s} size={s.size()}")
try:
s.pop()
except IndexError as e:
print("pop on empty raises IndexError:", e)
# Reference check against a Python list used as a stack
import random
random.seed(44)
ref, mine = [], LinkedStack()
for _ in range(2000):
if ref and random.random() < 0.45:
assert mine.pop() == ref.pop()
else:
x = random.randint(0, 99)
mine.push(x)
ref.append(x)
assert mine.size() == len(ref) and mine.is_empty() == (not ref)
if ref:
assert mine.peek() == ref[-1]
print("2000 random operations agree with a list used as a stack")
Worked trace
Each line shows the list from the top, with the pointer state implied by the chain. The program printed:
push 10: top -> 10 -> None size=1
push 20: top -> 20 -> 10 -> None size=2
push 30: top -> 30 -> 20 -> 10 -> None size=3
peek: 30
pop 30: top -> 20 -> 10 -> None size=2
pop 20: top -> 10 -> None size=1
pop 10: top -> None size=0
pop on empty raises IndexError: pop from empty stack
2000 random operations agree with a list used as a stack
Reading it: push 20 creates a node whose next is the node holding 10, and _top now points at 20, so the chain reads 20 -> 10 -> None. Each pop moves _top one node along; the popped node is no longer reachable and Python reclaims it. After the third pop _top is None and size is 0, and a further pop raises IndexError. The last line records a check against a Python list used as a stack on 2000 random operations.
Complexity
push, pop, peek, is_empty and size are all O(1) in the worst case: a fixed number of pointer updates, no loops. Space is O(n) for n stored items, one node each. Nothing here is recursive.
Linked stack versus array-backed stack
An array-backed stack (a Python list with append and pop) stores element references in one contiguous block. Its append is amortized O(1) (cheap on average over many calls): usually constant, but an occasional call has to allocate a larger block and may have to copy everything, so a single call can cost O(n). The linked stack never has that pause: every push does the same small amount of work, but it allocates one object per push.
Memory per stored element and the work done for 200,000 pushes of distinct integers that were created beforehand (the integers themselves are excluded from the memory figure) are counted below. sys.getsizeof reports the bytes CPython uses for one object. __slots__ tells Python the class has exactly the fields value and next and nothing else, so each object skips the per-object dictionary that would otherwise hold its fields and costs less memory. Counting object creations and block resizes replaces a stopwatch here: those counts are the same on every run, while elapsed time varies with the machine.
import platform
import sys
class Node:
__slots__ = ("value", "next") # fixed two fields, no per-object dict
def __init__(self, value, next=None):
self.value = value
self.next = next
N = 200_000
values = list(range(1000, 1000 + N)) # the int objects exist before measuring
# Memory: sys.getsizeof reports the bytes CPython uses for one object itself.
node_bytes = sys.getsizeof(Node(1))
arr = []
for v in values:
arr.append(v)
array_bytes = sys.getsizeof(arr) - sys.getsizeof([])
print(f"linked stack {node_bytes:5.1f} bytes per element (excluding the values)")
print(f"list-backed stack {array_bytes / N:5.1f} bytes per element (excluding the values)")
print(f"ratio {node_bytes / (array_bytes / N):.1f}")
# Work: count object creations for N pushes instead of timing them.
top = None
node_allocations = 0
for v in values:
top = Node(v, top)
node_allocations += 1
resizes, copied, capacity = 0, 0, 0
arr = []
for v in values:
arr.append(v)
new_capacity = (sys.getsizeof(arr) - sys.getsizeof([])) // 8
if new_capacity != capacity:
resizes += 1
copied += len(arr) - 1 # references a resize may have to move
capacity = new_capacity
print(f"linked stack {node_allocations} node objects created for {N} pushes")
print(f"list-backed stack {resizes} block resizes, {copied} references in the resized blocks in total ({copied / N:.2f} per push)")
print("Python", sys.version.split()[0], platform.machine())
Output:
linked stack 48.0 bytes per element (excluding the values)
list-backed stack 8.1 bytes per element (excluding the values)
ratio 5.9
linked stack 200000 node objects created for 200000 pushes
list-backed stack 72 block resizes, 1620992 references in the resized blocks in total (8.10 per push)
Python 3.12.15 aarch64
A node (an object with a value field and a next field, declared with __slots__) cost 48.0 bytes against about 8 bytes for a slot in the list's array, so the linked stack used roughly six times the memory per element (the ratio line) in CPython 3.12 on aarch64. The work counts show where the speed gap comes from: every linked push creates and initialises a Python object (200,000 of them), while the list creates none per push and only resizes its block 72 times. The block sizes at those resizes add up to about 8 references per push, which is an upper bound on the copying, because the memory allocator can often grow a block in place. That bounded, small per-push share is what amortized O(1) means: averaged over many pushes the cost per push is constant even though an individual push that triggers a resize costs more.
Recommendation: use the array-backed stack by default (smaller, faster, better cache locality: the processor loads memory in small chunks called cache lines, so reading one element of an array also pulls its neighbours into the fast cache, whereas linked nodes can sit anywhere in memory and each step may miss the cache). Choose the linked stack when you need a hard worst-case bound per operation with no occasional resize copy (for example latency-sensitive code), when you cannot know the maximum size and cannot afford a large copy, or when you want a persistent stack (one whose operations never change an existing version; push returns a new stack that shares the older nodes, so old versions stay valid). In C or C++ the same trade holds: a linked node adds a pointer and allocator overhead per element, and an array adds spare capacity and the cost of a resize copy.
Edge cases and common mistakes
- Popping or peeking when empty: raise a clear error (here
IndexError) instead of returningNone, which cannot be told apart from a storedNone. - Forgetting to update
_sizein one of the two methods, sosize()drifts. - Computing
size()by walking the list, which makes it O(n). - Pushing by attaching the new node at the tail. That makes push O(n) unless you keep a tail pointer, and pop O(n) regardless in a singly linked list.
- In
push, assigningself._top = nodebefore settingnode.next, which loses the old chain.
Follow-ups
Add min() in O(1): store with each node the smallest value at or below it. Make the stack thread-safe: a lock around each operation, or a compare-and-swap loop on _top in a lock-free design (compare-and-swap is one atomic hardware step that replaces _top with a new node only if _top still holds the value you read, and retries otherwise, so no thread ever waits holding a lock). Limit the stack to a maximum size and decide whether push beyond it raises or overwrites.
Running the code
# save the listings above as linked_stack.py and stack_memory.py (Python 3.12, standard library only)
python linked_stack.py
python stack_memory.py
Unlock Full Question Bank
Get access to all 26 Linked Lists, Stacks, and Queues interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.