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.
Design a stack that supports push, pop, top and retrieving the minimum element, all in O(1) time. Show one approach with extra storage, then explain how to get the minimum with only O(1) extra space.
Sample Answer
Direct answer
Keep the minimum of "everything currently on the stack" alongside the stack itself, so that it always reflects what is left after pops.
- With extra storage: a second, helper (auxiliary) stack of the same size, called the min stack. After every push, put the current minimum on it; on pop, pop both.
get_minreads its top. Every operation is O(1), extra space O(n). - With O(1) extra space: one stack plus ONE variable
min. Push a valuexthat is at leastminas itself. Push a new minimumx(smaller thanmin) as the encoded value2*x - min(a number that stands for something else; it works as a marker saying "the item here was a new minimum"), then setmin = x. An encoded value is always smaller than the newmin, which is how pop recognises it, and2*min - storedrebuilds the previous minimum. Every operation is O(1).
The idea in plain words
The tricky part is not finding the minimum on push, it is remembering what the minimum WAS before a push, because pop has to restore it. A min-so-far has to survive a pop of the current minimum. There are two ways to remember the old minimum: store it explicitly next to each value (approach 1), or hide it inside the stored value itself (approach 2). The second works because a new minimum is exactly the case where a value is smaller than everything below, and we can fold the old minimum into the number we store.
Approach 1: auxiliary stack
Push x onto the item stack and min(x, current min) onto the min stack (the minimum of everything up to and including x). Pop from both. Because the two stacks always have the same length, get_min is just the top of the min stack. It uses 2n slots for n items, and uses extra memory even when the minimum never changes. A common refinement stores onto the min stack only when x <= current min and pops it only when the popped item equals its top; this keeps the same worst case (a strictly decreasing sequence still stores n entries: the program prints 100 entries after 100 such pushes) but saves space on typical input. For example, after pushing 5, 3, 7, 3, 1, 4 the full min stack is [5, 3, 3, 3, 1, 1] and the refined one is [5, 3, 3, 1], as the program prints: 7 and 4 never beat the minimum, so they leave no entry. The <= matters: with <, duplicates of the minimum lose track. After pushing 3 twice with <, the min stack holds only one 3, and popping one 3 empties it while a 3 is still stored; the program prints that failure.
Approach 2: O(1) extra space with encoding
The rules, with min the current minimum of the stack:
- push(x), stack empty: store
x, setmin = x. - push(x), x >= min: store
x. The minimum does not change. - push(x), x < min: store
2*x - min, then setmin = x. Becausex < min, the stored value2*x - minis less thanx, which is the newmin, so it is below the new minimum, a value no real item can have. - pop: read
stored. Ifstored >= min, it is an ordinary value: return it. Otherwise it is an encoded marker, so the item being popped is the currentmin(return it) and the previous minimum was2*min - stored, which becomes the newmin. - top: if the stored top is below
min, the real top ismin; otherwise it is the stored value.
Where the formula comes from. When x becomes the new minimum, pop will later need two things from the one number we store: a way to notice that this entry is special, and the old minimum. Let gap = old_min - x, which is positive because x is a new minimum. Store the number that sits gap BELOW x: x - gap = x - (old_min - x) = 2*x - old_min. Being below x is the marker, because no ordinary item can be below the current minimum. And the distance below x is the information: gap = x - stored, so old_min = x + gap = 2*x - stored. Any other number below x would flag the entry but would not let you rebuild old_min. The program prints the gap, the distance below, and the recovered minimum for 1 over 3: 2, 2 and 3.
Why the recovery works: if the marker is s = 2*x - old_min and min = x, then 2*min - s = 2x - (2x - old_min) = old_min. The algebra is exact, so there is no rounding to worry about with integers.
import random
class MinStackAux:
"""Approach 1: a second stack records the minimum after every push (O(n) extra)."""
def __init__(self):
self._items = []
self._mins = []
def push(self, x):
self._items.append(x)
self._mins.append(x if not self._mins else min(x, self._mins[-1]))
def pop(self):
self._mins.pop()
return self._items.pop()
def top(self):
return self._items[-1]
def get_min(self):
return self._mins[-1]
class MinStackEncoded:
"""Approach 2: one stack plus one variable. A new minimum is stored as 2*x - old_min."""
def __init__(self):
self._stack = []
self._min = None
def push(self, x):
if not self._stack:
self._stack.append(x)
self._min = x
elif x >= self._min:
self._stack.append(x)
else:
self._stack.append(2 * x - self._min) # always below x, so below the new min
self._min = x
def pop(self):
stored = self._stack.pop()
if stored >= self._min:
return stored # an ordinary value
value = self._min # stored was an encoded marker: the top was the min
self._min = 2 * self._min - stored # recover the previous minimum
return value
def top(self):
stored = self._stack[-1]
return self._min if stored < self._min else stored
def get_min(self):
return self._min
class MinStackRefined:
"""Approach 1 with the refinement: the min stack only records values that tie or beat the minimum."""
def __init__(self, strict=False):
self._items, self._mins, self._strict = [], [], strict
def push(self, x):
self._items.append(x)
if not self._mins or (x < self._mins[-1] if self._strict else x <= self._mins[-1]):
self._mins.append(x)
def pop(self):
x = self._items.pop()
if x == self._mins[-1]:
self._mins.pop()
return x
def get_min(self):
return self._mins[-1]
def trace(values):
s = MinStackEncoded()
print("op stored stack min top")
for v in values:
s.push(v)
print(f"push {v:>2} {str(s._stack):<20} {s.get_min():>4} {s.top():>4}")
while s._stack:
popped = s.pop()
mn = s.get_min() if s._stack else None
top = s.top() if s._stack else None
print(f"pop -> {popped:>2} {str(s._stack):<20} {str(mn):>4} {str(top):>4}")
trace([5, 3, 7, 3, 1])
# The refinement on 5, 3, 7, 3, 1, 4: what each version keeps on its min stack
full, refined = MinStackAux(), MinStackRefined()
for v in (5, 3, 7, 3, 1, 4):
full.push(v)
refined.push(v)
print("min stack after every push:", full._mins)
print("min stack with the refinement:", refined._mins)
# The refinement with < instead of <= loses a duplicate of the minimum
strict = MinStackRefined(strict=True)
strict.push(3)
strict.push(3)
strict.pop()
try:
print("strict version, min after popping one of two 3s:", strict.get_min())
except IndexError:
print("strict version, min after popping one of two 3s: IndexError (the min stack is empty, but a 3 is still stored)")
# Why the stored value is never mistaken for a real one
x, old_min = 1, 3
print("new min 1 over old min 3 is stored as", 2 * x - old_min, "(< 1, so < the new min)")
stored = 2 * x - old_min
print("gap the minimum dropped:", old_min - x, "| stored value sits that far below the new min:", x - stored, "| recovered old min:", 2 * x - stored)
# The refinement keeps n entries on a strictly decreasing sequence
worst = MinStackRefined()
for v in range(100, 0, -1):
worst.push(v)
print("refined min stack after 100 strictly decreasing pushes:", len(worst._mins), "entries")
# Random check of all three against brute force, with many duplicates and negatives
rng = random.Random(8)
for _ in range(400):
a, b, c, ref = MinStackAux(), MinStackEncoded(), MinStackRefined(), []
for _ in range(60):
if ref and rng.random() < 0.45:
expected = ref.pop()
assert a.pop() == expected
assert b.pop() == expected
assert c.pop() == expected
else:
v = rng.randint(-5, 5)
ref.append(v)
a.push(v)
b.push(v)
c.push(v)
if ref:
assert a.top() == b.top() == ref[-1]
assert a.get_min() == b.get_min() == c.get_min() == min(ref)
print("400 random runs: all three designs match top and min computed by brute force")
# Python ints do not overflow; in a 32-bit language 2*x - min can
INT_MAX, INT_MIN = 2**31 - 1, -(2**31)
print("2*x - min with x = -2**31 + 1 and min = 2**31 - 1:", 2 * (INT_MIN + 1) - INT_MAX,
"which is below the 32-bit minimum", INT_MIN)
Output:
op stored stack min top
push 5 [5] 5 5
push 3 [5, 1] 3 3
push 7 [5, 1, 7] 3 7
push 3 [5, 1, 7, 3] 3 3
push 1 [5, 1, 7, 3, -1] 1 1
pop -> 1 [5, 1, 7, 3] 3 3
pop -> 3 [5, 1, 7] 3 7
pop -> 7 [5, 1] 3 3
pop -> 3 [5] 5 5
pop -> 5 [] None None
min stack after every push: [5, 3, 3, 3, 1, 1]
min stack with the refinement: [5, 3, 3, 1]
strict version, min after popping one of two 3s: IndexError (the min stack is empty, but a 3 is still stored)
new min 1 over old min 3 is stored as -1 (< 1, so < the new min)
gap the minimum dropped: 2 | stored value sits that far below the new min: 2 | recovered old min: 3
refined min stack after 100 strictly decreasing pushes: 100 entries
400 random runs: all three designs match top and min computed by brute force
2*x - min with x = -2**31 + 1 and min = 2**31 - 1: -6442450941 which is below the 32-bit minimum -2147483648
Worked trace
The printed table pushes 5, 3, 7, 3, 1 into the encoded stack. After 5, the stack holds [5] with min 5. Pushing 3 is a new minimum: the stored value is 2*3 - 5 = 1 (below the new min 3), and min becomes 3. Pushing 7 and the second 3 store themselves (7 and 3 are at least the min 3, and equality stores the raw value). Pushing 1 is a new minimum: stored 2*1 - 3 = -1, min becomes 1. The top column shows the real value for each state (5, 3, 7, 3, 1), decoded from the stored stack.
Popping: the stored -1 is below min 1, so the popped item is 1 and the new min is 2*1 - (-1) = 3. The next pops return 3, 7, then the stored 1 is below min 3, so it is a marker: the popped item is 3 and the new min is 2*3 - 1 = 5. The last pop returns 5. The printed line new min 1 over old min 3 is stored as -1 and the line after it confirm that the marker -1 for pushing 1 over min 3 is below the new minimum, and that the gap of 2 gives back the old minimum 3.
Complexity
- Approach 1: all four operations O(1); extra space O(n).
- Approach 2: all four operations O(1); extra space O(1), meaning one variable beyond the stack's own n slots.
- All three designs (the two stacks, the encoded version and the refined min stack) are checked against a brute-force
min(list)on 400 random sequences of pushes and pops using values from -5 to 5 (many duplicates, and negatives).
Edge cases
- Duplicates of the minimum: the second
3is stored raw becausex >= minis true whenx == min, and popping it returns it without changing min. - Negative numbers and zero: the check compares to
min, not to zero, so the encoding is unaffected. The-1marker in the trace is an example. - Empty stack:
pop,topandget_minneed a guard (for example raise an error) in production code; the shipped classes assume a non-empty stack, as the usual problem statement does. - Fixed-width integers:
2*x - mincan overflow a 32-bit integer; the last line of the output shows2*x - minfor the extreme values reaching -6442450941, below the 32-bit minimum of -2147483648. Python integers do not overflow; in C, C++ or Java use a 64-bit type for the stored values.
Common mistakes
- Using only one variable
minwith no history: popping the minimum leaves you not knowing the next smallest. - Pushing to the min stack only when
x < min(strict), then losing a duplicate of the minimum when one copy is popped. - Reading the raw stored stack as real values, for example in a debugger or a
peek: marker entries are not real items. - Forgetting that the encoded form only applies to numbers (it needs subtraction and multiplication), so approach 2 does not generalise to strings or objects, where approach 1 does.
Running the code
python min_stack.py
Python 3.12, standard library only.
Implement a singly linked list from scratch with a Node class and operations to append, prepend, find a value and delete a value, plus a way to dump the contents for testing. Walk through how each operation behaves on an empty list, a single-node list and the tail, and state the cost of each.
Sample Answer
The idea in plain words
A singly linked list is a chain of small objects called nodes. Each node holds one value and one pointer (a reference) to the next node. The list object itself only remembers where the chain starts, the head. There is no index arithmetic: to reach the third value you must start at the head and follow next twice. The last node's next is None, and that None is how every loop knows when to stop.
The one extra field worth adding is a tail pointer to the last node. Without it, append has to walk the whole chain to find the end (O(n)). With it, append is a single pointer update (O(1)), provided every operation keeps tail correct. Most bugs in this question are bugs in keeping head and tail correct in the empty, one-node and last-node cases.
Picture the list before and after
append(3) on 0 -> 1 -> 2 -> None
step 1: make node 3 (its next is None)
step 2: tail.next = node 3 0 -> 1 -> 2 -> 3 -> None
step 3: tail = node 3 tail now points at 3
delete(2) on 0 -> 1 -> 2 -> 3 -> None
walk with two pointers: prev=1, cur=2
prev.next = cur.next 0 -> 1 -> 3 -> None (2 is skipped)
Approach, step by step
- append(value): make a node. If the list is empty, it becomes both
headandtail. Otherwise link it aftertail, then movetailto it. - prepend(value): make a node whose
nextis the old head and make it the head. If the list was empty, it is also the tail. - find(value): walk from
headuntil a node holds the value or the walk falls off the end. Return the node, orNone. - delete(value): walk with two pointers,
prev(the node behind) andcur. Whencurholds the value, linkprev.nexttocur.next, which skipscur. If there is noprev,curwas the head, soheadmoves instead. Ifcurwas thetail,tailmoves back toprev. - dump: walk once and join the values with
->, ending inNone, so a test can compare the whole list against an expected string. The list holding 0, 1, 2 dumps as0 -> 1 -> 2 -> None, and the empty list dumps asNone.
The code
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None # last node; makes append O(1)
def append(self, value):
node = Node(value)
if self.head is None: # empty list: new node is both ends
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def prepend(self, value):
self.head = Node(value, self.head)
if self.tail is None: # list was empty: new node is also the tail
self.tail = self.head
def find(self, value):
cur = self.head
while cur is not None and cur.value != value:
cur = cur.next
return cur # the node, or None
def delete(self, value):
"""Remove the first node holding value. Return True if one was removed."""
prev, cur = None, self.head
while cur is not None and cur.value != value:
prev, cur = cur, cur.next
if cur is None: # empty list or value absent
return False
if prev is None: # deleting the head
self.head = cur.next
else:
prev.next = cur.next
if cur is self.tail: # deleting the tail: tail steps back
self.tail = prev
return True
def dump(self):
parts, cur = [], self.head
while cur is not None:
parts.append(str(cur.value))
cur = cur.next
return " -> ".join(parts + ["None"])
def show(step, lst, result=None):
head = lst.head.value if lst.head else None
tail = lst.tail.value if lst.tail else None
extra = "" if result is None else f" returned {result}"
print(f"{step:<14} {lst.dump():<22} head={head} tail={tail}{extra}")
if __name__ == "__main__":
lst = SinglyLinkedList()
show("start", lst)
show("delete(5)", lst, lst.delete(5))
lst.append(1); show("append(1)", lst)
lst.append(2); show("append(2)", lst)
lst.prepend(0); show("prepend(0)", lst)
lst.append(3); show("append(3)", lst)
node = lst.find(2)
print(f"find(2) node holding {node.value}, next is {node.next.value}")
print(f"find(9) {lst.find(9)}")
show("delete(3) tail", lst, lst.delete(3))
show("delete(0) head", lst, lst.delete(0))
show("delete(9)", lst, lst.delete(9))
show("delete(1)", lst, lst.delete(1))
show("delete(2) last", lst, lst.delete(2))
lst.append(7); show("append(7)", lst)
Run, it prints:
start None head=None tail=None
delete(5) None head=None tail=None returned False
append(1) 1 -> None head=1 tail=1
append(2) 1 -> 2 -> None head=1 tail=2
prepend(0) 0 -> 1 -> 2 -> None head=0 tail=2
append(3) 0 -> 1 -> 2 -> 3 -> None head=0 tail=3
find(2) node holding 2, next is 3
find(9) None
delete(3) tail 0 -> 1 -> 2 -> None head=0 tail=2 returned True
delete(0) head 1 -> 2 -> None head=1 tail=2 returned True
delete(9) 1 -> 2 -> None head=1 tail=2 returned False
delete(1) 2 -> None head=2 tail=2 returned True
delete(2) last None head=None tail=None returned True
append(7) 7 -> None head=7 tail=7
A note on prev, cur = cur, cur.next in delete: Python evaluates the whole right-hand side first, producing the pair (the old cur, the old cur.next), and only then assigns the two names. So prev gets the node cur was standing on and cur gets its successor. As two separate statements the same step is prev = cur followed by cur = cur.next; in that order it works, and swapped it does not. The parameter named next in Node.__init__ only hides Python's built-in next() function inside that constructor, and self.next is a separate attribute, so nothing breaks.
To see the two pointers move, save the block below as delete_trace.py next to ll_basic.py (the first block above):
from ll_basic import SinglyLinkedList
def label(node):
return "None" if node is None else str(node.value)
lst = SinglyLinkedList()
for value in (0, 1, 2):
lst.append(value)
print("list before:", lst.dump())
print("walk for delete(2), as separate statements")
prev, cur = None, lst.head
print(f" start prev={label(prev)} cur={label(cur)}")
while cur is not None and cur.value != 2:
prev = cur # first: prev takes the node cur is standing on
cur = cur.next # then: cur moves on (cur itself was not changed by the line above)
print(f" after step prev={label(prev)} cur={label(cur)}")
prev.next = cur.next # unlink: node 1 now points past node 2
print(" after prev.next = cur.next:", lst.dump())
print("same walk with the two lines swapped (a bug)")
prev, cur = None, lst.head
cur = cur.next
prev = cur
print(f" after one step prev={label(prev)} cur={label(cur)} (prev is no longer behind cur)")
print("tuple form, evaluated right side first")
prev, cur = None, lst.head
prev, cur = cur, cur.next # right side is (old cur, old cur.next); then both names are assigned
print(f" prev={label(prev)} cur={label(cur)}")
fresh = SinglyLinkedList()
for value in (0, 1, 2):
fresh.append(value)
print("delete(2) on a fresh list returned", fresh.delete(2), "->", fresh.dump())
Run, it prints:
list before: 0 -> 1 -> 2 -> None
walk for delete(2), as separate statements
start prev=None cur=0
after step prev=0 cur=1
after step prev=1 cur=2
after prev.next = cur.next: 0 -> 1 -> None
same walk with the two lines swapped (a bug)
after one step prev=1 cur=1 (prev is no longer behind cur)
tuple form, evaluated right side first
prev=0 cur=1
delete(2) on a fresh list returned True -> 0 -> 1 -> None
Reading that: prev starts as None because nothing is behind the head. Each pass of the loop moves both pointers one node to the right, always keeping prev directly behind cur. When cur lands on the node holding 2, prev.next = cur.next makes node 1 point at what node 2 pointed at (None), so node 2 is skipped. The swapped version leaves prev and cur on the same node, which is why order matters. The full delete also moves tail back to prev, because node 2 was the tail.
Reading the output as the pointer state after each step: after prepend(0) the head is 0 and the tail is still 2; after delete(3) (the tail) the tail has stepped back to 2; after delete(1) the list is the single node 2 -> None and head and tail are the same node; after delete(2) both are None, exactly like the starting empty list, so the next append(7) works from the same code path as the very first append.
How each operation behaves in the three special cases
| Operation | Empty list | Single node (value 2) | Tail node |
|---|---|---|---|
| append | head and tail both become the new node | tail.next = new node, tail moves | same as a normal append |
| prepend | head and tail both become the new node | new node points at the old node; tail unchanged | tail unchanged |
| find | loop never runs, returns None | one comparison | walks the whole chain |
| delete | loop never runs, returns False; nothing is touched | head becomes None and tail becomes None | prev.next is already None after the unlink, and tail must move back to prev |
Cost of each operation
With n nodes, and the tail pointer shown above:
| Operation | Time | Why |
|---|---|---|
| append | O(1) | tail is known. With a head-only list it is O(n): walk to the end first |
| prepend | O(1) | only the head changes |
| find | O(n) | no index, so a linear scan; the worst case is a value that is absent |
| delete(value) | O(n) | scan to find the value; the unlink itself is O(1) |
| delete the tail | O(n) | even with a tail pointer, a singly linked node cannot reach its predecessor, so you walk to it |
| dump | O(n) | visits every node once |
Extra space is O(1) for every operation (a few local pointers); the list itself uses O(n) for its nodes.
Checking it against a reference
A compact randomized test runs 300 random sequences of append, prepend, find and delete, keeps a plain Python list alongside, and asserts after every operation that the dumped string, the tail value and the "tail.next is None" invariant (a property that must always hold) all match.
import random
from ll_basic import SinglyLinkedList
random.seed(1)
for trial in range(300):
lst, ref = SinglyLinkedList(), []
for _ in range(40):
op, v = random.choice("apfd"), random.randint(0, 5)
if op == "a":
lst.append(v); ref.append(v)
elif op == "p":
lst.prepend(v); ref.insert(0, v)
elif op == "f":
assert (lst.find(v) is not None) == (v in ref)
else:
removed = lst.delete(v)
assert removed == (v in ref)
if removed:
ref.remove(v)
expected = " -> ".join([str(x) for x in ref] + ["None"])
assert lst.dump() == expected
assert (lst.tail.value if lst.tail else None) == (ref[-1] if ref else None)
assert lst.tail is None or lst.tail.next is None
print("300 random runs agree with a Python list")
300 random runs agree with a Python list
Common mistakes
- Forgetting to update
tailwhen deleting the last node. The list still prints correctly, but the nextappendlinks onto a node that is no longer in the list and the new value silently vanishes. - Forgetting that
prependon an empty list must settailtoo. - Writing
while cur.nextinstead ofwhile cur, which crashes on an empty list or never inspects the last node. - Deleting by only changing
cur(for examplecur = cur.next), which changes a local variable and not the list. - Treating deletion of the head as the general case: there is no
prev, soheaditself must move.
Languages
The structure is identical in Java (class Node { int value; Node next; } with head and tail fields) and in C or C++ (a struct with a pointer; there you must also free or delete the removed node, which Python's garbage collector does for you).
Running the code
python ll_basic.py # the walkthrough
python delete_trace.py # needs ll_basic.py in the same folder
python ll_basic_check.py # needs ll_basic.py in the same folder
Python 3.12, standard library only.
Implement a queue using two stacks with amortized O(1) enqueue and dequeue. Explain what a worst-case single dequeue looks like and why the amortized cost is still constant.
Sample Answer
The idea in plain words
A stack gives last-in, first-out (LIFO) order: you push and pop at one end. A queue gives first-in, first-out (FIFO) order: items leave in the order they arrived. Pouring a stack into a second stack reverses it, and reversing a reversed order gives the original order back. So keep two stacks: an inbox that receives every new item, and an outbox that serves every removal. When the outbox is empty and someone dequeues, pour the whole inbox into the outbox. The oldest item, which was at the bottom of the inbox, lands on top of the outbox and comes out first.
Amortized O(1) means the cost averaged over a whole sequence of operations is constant, even though one single call can be expensive. The reason it holds here: an item is poured at most once in its life.
The brute force and why it is not enough
A simpler version moves everything into the outbox on every dequeue and moves it all back afterwards. Every dequeue then costs O(n). The fix is to leave the items in the outbox and only pour again when the outbox is empty.
Approach, step by step
enqueue(x): push onto the inbox. One step.dequeue(): if the outbox is empty, pop every item off the inbox and push it onto the outbox. Then pop the outbox and return it. If both stacks are empty, raise an error.peek(): the same refill step, then look at the top of the outbox without removing it.- The rule that keeps the order correct: only pour when the outbox is empty. Pouring while the outbox still holds items would put newer items underneath older ones and break FIFO.
The code
import random
from collections import deque
class QueueFromTwoStacks:
def __init__(self):
self.inbox = [] # new items are pushed here; newest on top
self.outbox = [] # items leave from here; oldest on top
self.moves = 0 # how many items have been moved inbox -> outbox
def enqueue(self, item):
self.inbox.append(item)
def _refill(self):
if not self.outbox: # only when outbox is empty
while self.inbox:
self.outbox.append(self.inbox.pop())
self.moves += 1
def dequeue(self):
self._refill()
if not self.outbox:
raise IndexError("dequeue from empty queue")
return self.outbox.pop()
def peek(self):
self._refill()
if not self.outbox:
raise IndexError("peek at empty queue")
return self.outbox[-1]
def __len__(self):
return len(self.inbox) + len(self.outbox)
def trace():
q = QueueFromTwoStacks()
print(f"{'operation':<12}{'inbox (top on right)':<22}{'outbox (top on right)':<23}{'returned':<9}moved")
steps = [("enqueue", 1), ("enqueue", 2), ("enqueue", 3), ("enqueue", 4),
("dequeue", None), ("enqueue", 5), ("dequeue", None),
("dequeue", None), ("dequeue", None), ("dequeue", None)]
for name, arg in steps:
before = q.moves
result = ""
if name == "enqueue":
q.enqueue(arg)
label = f"enqueue({arg})"
else:
result = q.dequeue()
label = "dequeue()"
print(f"{label:<12}{str(q.inbox):<22}{str(q.outbox):<23}{str(result):<9}{q.moves - before}")
enqueues = sum(1 for name, _ in steps if name == "enqueue")
print(f"{enqueues} enqueues, {q.moves} moves: stack operations = {enqueues} pushes + 2 x {q.moves} + {enqueues} pops "
f"= {total_stack_ops(enqueues, q.moves)}, and 4 x {enqueues} = {4 * enqueues}")
def worst_case(n):
q = QueueFromTwoStacks()
for i in range(n):
q.enqueue(i)
q.dequeue()
first = q.moves
for _ in range(n - 1):
q.dequeue()
print(f"n={n}: first dequeue moved {first} items; the other {n - 1} dequeues moved {q.moves - first} more")
print(f"total stack operations for {2 * n} queue operations: {total_stack_ops(n, q.moves)}")
def total_stack_ops(enqueues, moves):
# enqueue = 1 push; each move = 1 pop + 1 push; each dequeue = 1 pop (dequeues == enqueues here)
return enqueues + 2 * moves + enqueues
def random_check():
random.seed(7)
for _ in range(500):
q, ref = QueueFromTwoStacks(), deque()
enqueues = 0
for _ in range(60):
if ref and random.random() < 0.5:
assert q.peek() == ref[0]
assert q.dequeue() == ref.popleft()
else:
v = random.randint(0, 9)
q.enqueue(v); ref.append(v); enqueues += 1
assert len(q) == len(ref)
assert q.moves <= enqueues # each item is moved at most once
try:
QueueFromTwoStacks().dequeue()
except IndexError as e:
print("empty queue ->", e)
print("500 random runs match collections.deque; moves never exceeded enqueues")
if __name__ == "__main__":
trace()
worst_case(1000)
random_check()
Run, it prints:
operation inbox (top on right) outbox (top on right) returned moved
enqueue(1) [1] [] 0
enqueue(2) [1, 2] [] 0
enqueue(3) [1, 2, 3] [] 0
enqueue(4) [1, 2, 3, 4] [] 0
dequeue() [] [4, 3, 2] 1 4
enqueue(5) [5] [4, 3, 2] 0
dequeue() [5] [4, 3] 2 0
dequeue() [5] [4] 3 0
dequeue() [5] [] 4 0
dequeue() [] [] 5 1
5 enqueues, 5 moves: stack operations = 5 pushes + 2 x 5 + 5 pops = 20, and 4 x 5 = 20
n=1000: first dequeue moved 1000 items; the other 999 dequeues moved 0 more
total stack operations for 2000 queue operations: 4000
empty queue -> dequeue from empty queue
500 random runs match collections.deque; moves never exceeded enqueues
Worked trace
Reading the table above row by row:
- After four
enqueuecalls the inbox is[1, 2, 3, 4](4 on top) and the outbox is empty. - The first
dequeue()is the expensive call. It pops 4, 3, 2, 1 off the inbox and pushes them onto the outbox, so the outbox becomes[4, 3, 2, 1]with 1 on top. That is 4 moves. It then pops 1 and returns it, leaving[4, 3, 2]. enqueue(5)goes to the inbox, not the outbox. The outbox still holds the older items, which must leave first.- The next three
dequeue()calls return 2, 3, 4 with zero moves each, straight from the outbox. - The last
dequeue()finds the outbox empty, pours the single item 5 across (1 move) and returns it. - Counting the stack operations of this whole run, the last line of the table output does the arithmetic: 5 enqueues are 5 pushes onto the inbox, the 5 moves are 5 pops plus 5 pushes (2 x 5 = 10), and the 5 dequeues are 5 pops off the outbox, so 5 + 10 + 5 = 20, which is exactly 4 x 5, the 4-operations-per-item figure.
What the worst single dequeue looks like
Enqueue n items, then dequeue once. That one call moves all n items, so it costs Theta(n) (the cost grows in proportion to n: at least and at most a constant times n). The output shows n=1000: the first dequeue moved 1000 items. The next 999 dequeues moved 0 items, because the outbox already holds everything in the right order.
Why the amortized cost is still constant
Count the stack operations one item causes over its whole life: one push onto the inbox, one pop off the inbox, one push onto the outbox, one pop off the outbox. That is 4 operations per item, and an item is never poured twice, because once it is in the outbox it only ever leaves. So any sequence containing e enqueues costs at most 4e stack operations in total, which is at most 4 per enqueue, or O(1) per operation on average. In the n=1000 run the total is 4000 stack operations for 2000 queue operations, the 4e bound with e = 1000, computed as e + 2 x moves + dequeues.
An adversarial sequence (the worst ordering of operations someone could pick on purpose to make the structure slow) cannot defeat this. Alternating enqueue and dequeue never makes the outbox pour more than once per item. Each pour moves only what is currently in the inbox, and those items are then gone from the inbox for good. The random check in the program asserts the bound directly: the moves counter never exceeded the number of enqueues over 500 random runs, and every returned value matched collections.deque.
Python's list.append and list.pop() at the end are themselves amortized O(1) (the list occasionally grows its storage), so the whole structure is amortized O(1) per operation under that same reading.
Complexity
enqueue: O(1) amortized.dequeueandpeek: O(1) amortized, O(n) worst case for a single call that has to pour n items.- Space: O(n) for n stored items. No extra copies beyond the two stacks.
Edge cases and common mistakes
- Dequeue or peek on an empty queue: both stacks are empty, so the code raises
IndexError(the output shows the message). - One item: it goes inbox, outbox, out. Works with no special case.
- Pouring on every dequeue, or pouring while the outbox is non-empty. The first is O(n) per call, the second breaks FIFO order.
- Forgetting that
peekalso has to refill the outbox. Looking only atinbox[0]works sometimes but is wrong once the outbox holds items. - Counting
lenas only the outbox or only the inbox.
Running the code
python queue_two_stacks.py
Python 3.12, standard library only.
Detect whether a singly linked list contains a cycle using O(1) extra space. Explain why your method terminates and why it must find the cycle if one exists.
Sample Answer
The idea in plain words
A list has a cycle if following next forever never reaches None: some node's next points back to an earlier node. You cannot detect that by walking alone, because a walker in a cycle just goes round and round and looks the same as a very long list.
The O(1)-space trick is a race on a track with two runners starting together: slow takes one step per round, fast takes two. On a straight road with an end, fast simply arrives at the end first, which proves there is no cycle. On a circular track, fast laps slow and catches it from behind, and the moment both runners stand on the same node you have proved a cycle exists.
Brute force and why it is not enough
Walk the list and remember every node you have seen in a hash set; if you see one twice, there is a cycle. This is correct and O(n) time, but it uses O(n) extra space. The question asks for O(1), so the set version is the baseline to beat (it appears in the code as has_cycle_with_set, used only to check the answer).
The method
- Start
slowandfastat the head. - Repeat: move
slowone node andfasttwo nodes. Before movingfasttwo nodes, check bothfastandfast.nextare notNone, otherwise the second hop would crash. - If
fastorfast.nextisNone, the list has an end: return False. - If
slowandfastare the same node (compare identity withis, not value), return True.
The code
class Node:
def __init__(self, value):
self.value, self.next = value, None
def build(n, cycle_to=None):
"""Nodes 1..n in a row; the last node points back to node cycle_to (1-based), or None."""
nodes = [Node(i) for i in range(1, n + 1)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
if cycle_to is not None:
nodes[-1].next = nodes[cycle_to - 1]
return nodes[0] if nodes else None
def has_cycle(head, trace=False):
slow = fast = head
step = 0
while fast is not None and fast.next is not None: # fast reaching None means a real end
slow = slow.next # 1 step
fast = fast.next.next # 2 steps
step += 1
if trace:
print(f"step {step}: slow={slow.value} fast={fast.value if fast else None}")
if slow is fast:
return True
return False
def has_cycle_with_set(head):
seen = set() # O(n) space alternative
while head is not None:
if head in seen:
return True
seen.add(head)
head = head.next
return False
def cycle_length(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow, fast = slow.next, fast.next.next
if slow is fast:
length, node = 1, slow.next
while node is not slow: # walk once around the loop
node, length = node.next, length + 1
return length
return 0
def cycle_start(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow, fast = slow.next, fast.next.next
if slow is fast:
slow = head # restart one pointer at the head
while slow is not fast: # both now move 1 step at a time
slow, fast = slow.next, fast.next
return slow
return None
if __name__ == "__main__":
print("list 1..6, node 6 points back to node 3:")
head = build(6, cycle_to=3)
print(" has_cycle:", has_cycle(head, trace=True))
print(" cycle length:", cycle_length(head), "| cycle starts at node", cycle_start(head).value)
print("list 1..6, no cycle:")
print(" has_cycle:", has_cycle(build(6), trace=True))
print("empty:", has_cycle(None), "| one node, no cycle:", has_cycle(build(1)),
"| one node pointing at itself:", has_cycle(build(1, cycle_to=1)))
Run, it prints each round on a six-node list whose last node points back to node 3, then the same on a list with no cycle:
list 1..6, node 6 points back to node 3:
step 1: slow=2 fast=3
step 2: slow=3 fast=5
step 3: slow=4 fast=3
step 4: slow=5 fast=5
has_cycle: True
cycle length: 4 | cycle starts at node 3
list 1..6, no cycle:
step 1: slow=2 fast=3
step 2: slow=3 fast=5
step 3: slow=4 fast=None
has_cycle: False
empty: False | one node, no cycle: False | one node pointing at itself: True
On the cycle, fast enters the loop first, passes slow, and at step 4 both stand on node 5. Without a cycle, fast runs off the end at step 3 (fast=None) and the loop exits with False.
Why it terminates
- No cycle:
fastmoves two nodes per round along a list that ends, so it reachesNoneafter at most about n/2 rounds. The loop ends. - Cycle:
slowenters the loop aftermurounds, wheremuis the number of nodes before the loop (2 in the example, nodes 1 and 2). By thenfastis already inside the loop. The loop hasLnodes (4 in the example).
Why it must find a cycle if one exists
Once both pointers are inside the loop, let g be the number of steps fast still has to travel, going forward round the loop, to land on slow's node. g is between 0 and L - 1. In each round fast moves 2 nodes and slow moves 1 node, so fast gains exactly 2 - 1 = 1 node on slow and closes the gap by exactly 1: g drops to g - 1 (and wraps to L - 1 only if it was 0, which means they had already met). Because g decreases by exactly 1 and cannot jump over 0, it reaches 0 within L rounds after slow enters, so they meet after at most mu + L rounds in total. fast can never leap over slow because the gap shrinks one node at a time. In the example, g is 2 when slow reaches node 3, and the meeting is two rounds later.
Cycle length and where the cycle starts
The same race answers two follow-ups. The code shows both.
- Length: when they meet, keep one pointer there and walk it once around the loop, counting nodes until it returns to the meeting node. In the example that is 4.
- Start of the loop: after the meeting, move one pointer back to the head and advance both pointers one node at a time; the node where they meet is the first node of the loop. That is node 3 in the example. Why it works, with the numbers of the example (
mu= nodes before the loop = 2,L= nodes in the loop = 4):
- Let
tbe the number of rounds until they meet.slowhas takentsteps from the head andfasthas taken2t. In the examplet = 4. - Both stand on the same node, and
fasttooktmore steps thanslow. Those extra steps only went round the loop, sotis a whole number of laps:t = k * Lfor some whole numberk. Here4 = 1 * 4, sok = 1. - Look at
slow, which is at the meeting node aftert = k * Lsteps from the head. If it takesmumore steps it has gonek * L + musteps from the head, which ismusteps to enter the loop at its first node plusk * Lmore steps that are exactlyklaps and bring it back to that first node. Somusteps from the meeting node land on the loop start. Here the meeting node is 5, and two steps give 6 then 3, the loop start. - A second pointer restarted at the head also reaches the loop start after exactly
musteps (1, then 2, then 3 here). - Both pointers moving one step at a time therefore arrive at the loop start together after
musteps. Before that step they are not on the same node, because the one from the head is still on the straight part while the other is on the loop.
This program prints those numbers for the six-node example:
class Node:
def __init__(self, value):
self.value, self.next = value, None
def build(n, cycle_to=None):
nodes = [Node(i) for i in range(1, n + 1)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
if cycle_to is not None:
nodes[-1].next = nodes[cycle_to - 1]
return nodes[0]
head = build(6, cycle_to=3) # 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> back to 3
slow = fast = head
t = 0
while True:
slow, fast, t = slow.next, fast.next.next, t + 1
print(f"round {t}: slow={slow.value} fast={fast.value} fast has taken {2 * t} steps, slow {t}")
if slow is fast:
break
print(f"met at node {slow.value} after t = {t} rounds")
mu, L = 2, 4 # nodes before the loop, nodes in the loop
k = t // L
print(f"t = k * L -> {t} = {k} * {L} (the extra steps fast took are k whole laps)")
walker_a, walker_b = head, slow # one restarted at the head, one left at the meeting node
step = 0
print(f"start: from head = {walker_a.value}, from meeting node = {walker_b.value}")
while walker_a is not walker_b:
walker_a, walker_b, step = walker_a.next, walker_b.next, step + 1
print(f"after {step} step(s): from head = {walker_a.value}, from meeting node = {walker_b.value}")
print(f"they meet at node {walker_a.value} after mu = {mu} steps: the loop start")
Output:
round 1: slow=2 fast=3 fast has taken 2 steps, slow 1
round 2: slow=3 fast=5 fast has taken 4 steps, slow 2
round 3: slow=4 fast=3 fast has taken 6 steps, slow 3
round 4: slow=5 fast=5 fast has taken 8 steps, slow 4
met at node 5 after t = 4 rounds
t = k * L -> 4 = 1 * 4 (the extra steps fast took are k whole laps)
start: from head = 1, from meeting node = 5
after 1 step(s): from head = 2, from meeting node = 6
after 2 step(s): from head = 3, from meeting node = 3
they meet at node 3 after mu = 2 steps: the loop start
Complexity
- Time O(n): at most about
mu + Lrounds, andmu + Lis at most n. - Space O(1): two pointers. The set version is O(n) space.
Checking it
The test builds every list of length 0 to 12 with every possible cycle position (and no cycle), and compares the pointer version with the set version, the loop length n - cycle_to + 1, and the loop start:
from cycle_detect import build, has_cycle, has_cycle_with_set, cycle_length, cycle_start
checked = 0
for n in range(0, 13):
for cycle_to in [None] + list(range(1, n + 1)):
if n == 0 and cycle_to is not None:
continue
head = build(n, cycle_to)
expected = cycle_to is not None
assert has_cycle(head) == has_cycle_with_set(head) == expected
if expected:
assert cycle_length(head) == n - cycle_to + 1
assert cycle_start(head).value == cycle_to
else:
assert cycle_length(head) == 0 and cycle_start(head) is None
checked += 1
print(f"{checked} lists (every length 0 to 12, every cycle position): all answers correct")
91 lists (every length 0 to 12, every cycle position): all answers correct
Edge cases and common mistakes
- Empty list and one node without a cycle:
fastisNoneorfast.nextisNoneimmediately, so the answer is False. - One node pointing at itself:
Trueafter one round (slowandfastboth land on it). - Checking
fast.nextbeforefast:fast.nextonNoneraisesAttributeError. Testfastfirst, thenfast.next. - Comparing values instead of nodes: two different nodes can hold equal values;
slow is fastcompares identity. - Checking
slow is fastbefore the first move: both start at the head, so the check is true immediately and reports a cycle in every list. Compare only after moving. - Trying to mark visited nodes by editing them: works only if you may modify the list, and leaves it damaged.
Running the code
python cycle_detect.py
python cycle_detect_check.py # needs cycle_detect.py in the same folder
python cycle_start_trace.py
Python 3.12, standard library only.
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.
Unlock Full Question Bank
Get access to all 13 Linked Lists, Stacks, and Queues interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.