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.
Compare a contiguous array (or dynamic array) with a singly linked list for random access, insertion at the head, insertion at the tail, insertion in the middle given a pointer, and iteration. Give the cost of each and say which you would choose for a workload with frequent inserts and occasional reads.
Sample Answer
The idea in plain words
A dynamic array (Python list, C++ std::vector, Java ArrayList) keeps its elements side by side in one block of memory. That gives instant access by index (the address is start + index * element_size), but inserting near the front means shifting everything after it one slot to the right. A singly linked list scatters its elements in separate nodes, each pointing at the next. That gives instant insertion next to a node you already hold (change two pointers), but reaching the k-th element means following k pointers from the head.
The whole comparison follows from those two layouts: contiguous memory buys random access and cache-friendly scans, and linked nodes buy cheap local edits. "Cache-friendly" means this: the CPU keeps a small, very fast memory (the cache) and loads memory into it in blocks of about 64 bytes at a time, so when elements are neighbours, reading one has already loaded the next few. Nodes scattered across memory get no such help.
Cost table
| Operation | Dynamic array | Singly linked list |
|---|---|---|
| Random access by index | O(1) | O(n), follow k pointers |
| Insert at head | O(n), shift all elements | O(1) |
| Insert at tail | amortized O(1) | O(n) with only a head pointer; O(1) if a tail pointer is kept |
| Insert in the middle, given the position | O(n), shift the elements after it | O(1) given the node before it; finding that node is O(n) |
| Iterate over all elements | O(n), consecutive memory | O(n), one pointer follow per element |
Amortized O(1) means the cost averaged over a whole sequence of operations is constant, even though one call can be much more expensive. An append to a full array allocates a bigger block (typically double) and copies every element, which is O(n) for that one call. Doubling keeps the total small.
Measured with counted operations
The program counts element copies for the array and next-pointer follows for the list, so the numbers do not depend on machine speed. The helper measure(label, array_fn, list_fn) zeroes both counters, runs one operation on the array (the lambda is a one-line function that delays the call until measure is ready), runs the matching operation on the list, and records the two counters as one row of the table. So each printed row answers: how many element moves did the array need, and how many pointer hops did the list need, for this one operation on about 1000 elements.
import sys
class DynArray:
"""Growable array: doubles its capacity when full. `moves` counts element copies."""
def __init__(self):
self.cap, self.n, self.data, self.moves = 1, 0, [None], 0
def append(self, x):
if self.n == self.cap: # full: allocate double and copy everything
self.data = self.data + [None] * self.cap
self.moves += self.n
self.cap *= 2
self.data[self.n] = x
self.n += 1
def insert(self, i, x):
self.append(None) # make room (amortized O(1))
for j in range(self.n - 1, i, -1): # shift the tail one slot right
self.data[j] = self.data[j - 1]
self.moves += 1
self.data[i] = x
def get(self, i):
return self.data[i] # one step
class Node:
__slots__ = ("val", "next")
def __init__(self, val, next=None):
self.val, self.next = val, next
class LinkedList:
"""Singly linked list. `hops` counts next-pointer follows."""
def __init__(self):
self.head = None
self.hops = 0
def push_front(self, x):
self.head = Node(x, self.head)
def get(self, i):
node = self.head
for _ in range(i):
node = node.next
self.hops += 1
return node
def push_back(self, x): # no tail pointer: walk to the end
node = Node(x)
if not self.head:
self.head = node
return
cur = self.head
while cur.next:
cur = cur.next
self.hops += 1
cur.next = node
def insert_after(self, node, x): # given the node: no walk
node.next = Node(x, node.next)
N = 1000
arr, lst = DynArray(), LinkedList()
for i in range(N):
arr.append(i)
print(f"{N} appends to the doubling array copied {arr.moves} elements in total (capacity {arr.cap})")
for i in range(N - 1, -1, -1):
lst.push_front(i)
rows = []
def measure(label, array_fn, list_fn):
arr.moves, lst.hops = 0, 0
array_fn()
list_fn()
rows.append((label, arr.moves, lst.hops))
measure("random access, index 500", lambda: arr.get(500), lambda: lst.get(500))
measure("insert at head", lambda: arr.insert(0, -1), lambda: lst.push_front(-1))
mid = lst.get(500) # a pointer we already hold
measure("insert in middle, position 500", lambda: arr.insert(500, -2), lambda: lst.insert_after(mid, -2))
measure("insert at tail, no tail pointer", lambda: arr.append(-3), lambda: lst.push_back(-3))
print(f"{'operation (list of ~1000)':<34}{'array element moves':>20}{'list pointer hops':>19}")
for label, a, l in rows:
print(f"{label:<34}{a:>20}{l:>19}")
steps_array = sum(1 for _ in range(arr.n))
steps_list, node = 0, lst.head
while node:
steps_list += 1
node = node.next
print(f"iteration: the array loop takes {steps_array} steps and the list loop {steps_list} (one per element either way)")
n = 100_000
as_list = list(range(n))
appended = []
for v in range(n):
appended.append(v)
nodes = None
for v in reversed(range(n)):
nodes = Node(v, nodes)
node_bytes = sys.getsizeof(Node(0))
print(f"Python {sys.version.split()[0]}: list of {n} items: {sys.getsizeof(as_list)} bytes of references; "
f"{sys.getsizeof(appended)} bytes when grown by append; "
f"{n} linked nodes: {n * node_bytes} bytes ({node_bytes} per node)")
Run with Python 3.12.15, it prints:
1000 appends to the doubling array copied 1023 elements in total (capacity 1024)
operation (list of ~1000) array element moves list pointer hops
random access, index 500 0 500
insert at head 1000 0
insert in middle, position 500 501 0
insert at tail, no tail pointer 0 1001
iteration: the array loop takes 1003 steps and the list loop 1003 (one per element either way)
Python 3.12.15: list of 100000 items: 800056 bytes of references; 800984 bytes when grown by append; 100000 linked nodes: 4800000 bytes (48 per node)
How to read it:
- Resizing. 1000 appends to the doubling array copied 1023 elements in total (1 + 2 + 4 + ... + 512), about one copy per append. One single append can copy hundreds of elements, which is why the claim is amortized and not worst case. The cost that matters in latency-sensitive code is that spike: the append that triggers a resize is slow.
- Random access. The array needs one index calculation; the list followed 500 pointers to reach index 500.
- Insert at head. The array shifted 1000 elements; the list did no pointer follows at all.
- Insert in the middle. The array shifted 501 elements. The list inserted after a node the code already held (found by an earlier walk) with 0 hops. Without that held node, the list needs the walk first, and both structures are O(n).
- Insert at tail. With no tail pointer the list walked 1001 nodes; the array just appended.
- Iteration. Both loops take one step per element (1003 elements because three were inserted above). The difference in practice is hardware: the array's elements are neighbours in memory, so a scan is fast, while list nodes may be anywhere.
- Memory overhead per node. The list of 100000 references takes about 800 KB (8 bytes per slot, 800984 bytes when grown by append, which includes spare capacity). Linked nodes took 48 bytes each on this Python build, 4800000 bytes in total, six times more, because each node is an object with its own header plus a value reference and a next reference. In C on a 64-bit platform a node holding an
intis typically 16 bytes (4-byte value, padding, 8-byte pointer) against 4 bytes per array element, before the allocator's own per-allocation overhead. Padding means unused bytes the compiler inserts so the 8-byte pointer starts at an address divisible by 8. Allocator overhead means the bookkeeping the memory allocator (mallocin C) keeps for every separate allocation, so a node costs more than its own fields. The C program below prints both for a two-field node:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct node { int value; struct node *next; };
int main(void) {
struct node *a = malloc(sizeof *a);
struct node *b = malloc(sizeof *b);
printf("sizeof(struct node) = %zu (int 4 + padding 4 + pointer 8)\n", sizeof *a);
printf("usable bytes behind a 16-byte request (glibc): %zu\n", malloc_usable_size(a));
long gap = (char *)b - (char *)a;
printf("distance between two back-to-back nodes: %ld bytes\n", gap < 0 ? -gap : gap);
free(a);
free(b);
return 0;
}
Compiled with gcc in a python:3.12 (Debian, glibc) container, it prints:
sizeof(struct node) = 16 (int 4 + padding 4 + pointer 8)
usable bytes behind a 16-byte request (glibc): 24
distance between two back-to-back nodes: 32 bytes
The 16-byte node was placed 32 bytes after the previous one: in a long chain of such nodes each one uses 32 bytes, of which 4 hold the value and 8 hold the pointer; the other 20 are padding (4) and the allocator's header and rounding (16). This gap is specific to glibc; other allocators differ.
The choice for frequent inserts and occasional reads
Commit to the linked list when inserts happen at the head or next to nodes you already hold (an undo stack where each action is pushed on the front, a work queue where new jobs are added at the front, an LRU list (least recently used: the entries ordered by when they were last touched) where a touched entry is moved to the front, a text editor cursor), reads are rare, and the elements are large or must keep a stable address. Commit to the dynamic array when the inserts are appends, or inserts at an index you must search for first, because then the list's walk to the position costs O(n) anyway and the array's shift is a fast block move on contiguous memory. What would flip the decision: the reads become frequent, the data is small (list overhead dominates), or you need indexing.
If the inserts are at both ends, use a deque (a double-ended queue, usually built from a circular buffer or a list of fixed-size blocks) instead of either. A circular buffer is an array treated as a ring: a head index and a count, with indices wrapping around the end by using % capacity, so removing from the front just moves the head index forward and shifts nothing.
How one use case maps to the held-node case
A text editor shows it. The editor holds a reference to the node at the cursor. Typing a character is "insert after the node I already hold", which is the 0-hop row of the table. An array-backed text must shift everything after the cursor on every keystroke. The program types X then Y after abc in abcdef both ways:
hops = 0 # counts next-pointer follows made while searching from the head
class Node:
def __init__(self, ch, nxt=None):
self.ch, self.next = ch, nxt
def walk_to(head, k):
"""Return the k-th node by following next pointers from the head, counting each follow."""
global hops
node = head
for _ in range(k):
node = node.next
hops += 1
return node
def text_of(head):
out = []
while head:
out.append(head.ch)
head = head.next
return "".join(out)
# A text editor holding "abcdef" with the cursor after "c".
head = None
for ch in reversed("abcdef"):
head = Node(ch, head)
cursor = walk_to(head, 2) # node "c": found once by a walk, then kept
print(f"finding the cursor node from the head took {hops} pointer hops")
hops = 0
for typed in "XY": # each keystroke inserts right after the held node
cursor.next = Node(typed, cursor.next)
cursor = cursor.next # the cursor moves onto the new node
print(f"list after typing {typed!r}: {text_of(head)} (pointer hops: {hops})")
chars, moves = list("abcdef"), 0
pos = 3 # cursor position after "c"
for typed in "XY":
chars.append(None) # grow by one slot
for j in range(len(chars) - 1, pos, -1):
chars[j] = chars[j - 1] # shift the tail one slot right
moves += 1
chars[pos] = typed
pos += 1
print(f"array after typing {typed!r}: {''.join(chars)} (elements moved so far: {moves})")
# Chunked (unrolled) list: up to 4 elements per node.
CHUNK = 4
chunks = []
for v in range(10):
if not chunks or len(chunks[-1]) == CHUNK:
chunks.append([]) # a full chunk: start a new node
chunks[-1].append(v)
print("chunks:", chunks)
print(f"next pointers: {len(chunks)} for {sum(map(len, chunks))} elements, "
f"against {sum(map(len, chunks))} for a plain linked list")
print("with 64 elements per chunk, one 8-byte pointer is shared:", 8 / 64, "bytes per element")
Run with Python 3.12.15, it prints:
finding the cursor node from the head took 2 pointer hops
list after typing 'X': abcXdef (pointer hops: 0)
list after typing 'Y': abcXYdef (pointer hops: 0)
array after typing 'X': abcXdef (elements moved so far: 3)
array after typing 'Y': abcXYdef (elements moved so far: 6)
chunks: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
next pointers: 3 for 10 elements, against 10 for a plain linked list
with 64 elements per chunk, one 8-byte pointer is shared: 0.125 bytes per element
The only pointer hops were the 2 spent finding the cursor node the first time; each keystroke after that reported 0 because the cursor node was kept between keystrokes (a version that walked from the head again before each keystroke would report 2 and then 3 more hops). The array moved 3 elements for the first keystroke and 3 more for the second. That is the whole reason the "frequent inserts" workload leans toward a list when the inserts cluster around a held position, and leans away once every insert first has to search for its position.
Chunked structures and streaming ingestion
For data that arrives continuously and whose size is unknown, a plain array has to copy everything on each resize, with a latency spike (one operation that is occasionally far slower than the usual, which the user sees as a stutter), and it needs one contiguous block. A chunked (unrolled) list stores several elements per node, for example 64 in a small array per node. The printout above shows the shape with a chunk size of 4: ten elements sit in three nodes, [0 1 2 3] [4 5 6 7] [8 9], so there are 3 next pointers instead of 10, and one 8-byte pointer shared by 64 elements is 0.125 bytes per element. The chunk size is a trade: a bigger chunk spreads the pointer and allocation overhead over more elements and scans faster, but an insert in the middle must shift more elements inside one chunk. Sizes of a few cache lines (a cache line is the 64-byte block mentioned above) are a typical starting point. Appends fill the last chunk or allocate a new one, no existing data is ever copied, and the per-node overhead is shared by many elements. It keeps most of the array's scan speed too. Block-based deques use the same idea.
Converting between the two
Array to list: one pass, O(n) time, n node allocations. List to array: one pass with a known length, O(n) time and one allocation, or amortized appends if the length is unknown. Do it once when the workload changes phase (build with inserts, then freeze into an array for many reads), rather than repeatedly.
Common mistakes
- Saying a linked list insertion is O(1) without saying that the node must already be in hand.
- Saying array insertion at the end is O(1) without the word amortized.
- Ignoring the per-node memory and allocation cost, and treating Big-O as the whole story.
- Forgetting that a tail pointer fixes tail insertion on a list, but not tail deletion in a singly linked list (that needs the predecessor).
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python array_vs_list.py
Save the listing as array_vs_list.py. It uses only the standard library.
Given a singly linked list, detect whether it has a cycle and, if it does, return the length of the cycle. Explain the time and space cost.
Sample Answer
The idea
If a singly linked list has no cycle, following next eventually reaches None. If it has a cycle, you walk forever. The trick that detects this with no extra memory is Floyd's tortoise and hare: two pointers start at the head, the slow one (tortoise) moves one node per round and the fast one (hare) moves two. If the list ends, the hare falls off the end first. If there is a cycle, both end up circling it, and the hare closes the distance to the tortoise by exactly one node per round, so it cannot jump over the tortoise: they land on the same node. (Why one: each round the hare advances 2 nodes and the tortoise 1, so the hare gains 1. If the hare is 2 nodes behind the tortoise inside the loop, one round makes the gap 1 and the next makes it 0, a meeting. A gap can never go from 1 to -1, because it only ever shrinks by 1.)
Once they meet, that node is inside the cycle. Leave one pointer there and walk the other around the cycle until it returns to that node, counting the nodes. The count is the cycle length.
The brute force and why it is not enough
Keep a dictionary of every node you have visited and the position at which you first saw it. The first time you reach a node already in the dictionary, the cycle length is the current position minus the stored position. That is correct and also easy to explain, but it costs O(n) extra memory. Floyd gets the same answer with two pointers. (The program ships the dictionary version as the cross-check.)
Approach
- Set
slowandfastto the head. - Repeat while
fastandfast.nextexist: moveslowone node,fasttwo nodes. If they are the same node, a cycle exists. - If the loop ended because
fastorfast.nextisNone, there is no cycle: return 0. - Otherwise start a counter at 1, step a walker from
slow.nextuntil it is back atslow, adding 1 per step. Return the counter.
Code
The program prints the pointer positions round by round.
import random
class Node:
def __init__(self, val):
self.val, self.next = val, None
def build(n, cycle_to=None):
"""Nodes 1..n in a row; if cycle_to is given, the last node points back at node number cycle_to."""
nodes = [Node(i + 1) for i in range(n)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
if cycle_to is not None and n:
nodes[-1].next = nodes[cycle_to - 1]
return nodes
def cycle_length(head, trace=False):
"""Return 0 if the list ends, otherwise the number of nodes in the cycle."""
slow = fast = head
steps = 0
while fast and fast.next:
slow = slow.next # moves 1 node per round
fast = fast.next.next # moves 2 nodes per round
steps += 1
if trace:
print(f" round {steps}: slow at {slow.val}, fast at {fast.val if fast else None}")
if slow is fast: # they can only meet inside the cycle
length = 1
walker = slow.next
while walker is not slow: # lap the cycle once, counting nodes
walker = walker.next
length += 1
return length
return 0 # fast fell off the end: no cycle
def cycle_length_with_set(head):
seen = {} # node -> position at which it was first visited
position = 0
while head:
if head in seen:
return position - seen[head]
seen[head] = position
position += 1
head = head.next
return 0
def says_cycle_by_value(head):
"""Wrong on purpose: compares the values the pointers see instead of the nodes."""
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if fast is not None and slow.val == fast.val:
return True
return False
print("list 1 -> 2 -> 3 -> 4 -> 5 -> back to 3 (cycle of 3):")
nodes = build(5, cycle_to=3)
print("result:", cycle_length(nodes[0], trace=True))
print("list 1 -> 2 -> 3 -> 4 -> None:")
print("result:", cycle_length(build(4)[0], trace=True))
print("single node pointing at itself:", cycle_length(build(1, cycle_to=1)[0]))
print("empty list:", cycle_length(None))
same = build(3) # three separate nodes that all hold 7, no cycle
for node in same:
node.val = 7
print("three nodes all holding 7, no cycle: by node", cycle_length(same[0]), "| by value says cycle:", says_cycle_by_value(same[0]))
rng = random.Random(69)
for trial in range(3000):
n = rng.randint(1, 30)
start = rng.choice([None, rng.randint(1, n)])
nodes = build(n, start)
expected = 0 if start is None else n - start + 1
assert cycle_length(nodes[0]) == cycle_length_with_set(nodes[0]) == expected
if start is not None:
tail_len = start - 1 # nodes before the cycle
slow = fast = nodes[0]
rounds = 0
while True:
slow, fast, rounds = slow.next, fast.next.next, rounds + 1
if slow is fast:
break
assert rounds <= tail_len + expected # meets within tail + cycle rounds
print("3000 random lists agree with the set-based method; rounds to meet never exceeded tail + cycle length")
Output:
list 1 -> 2 -> 3 -> 4 -> 5 -> back to 3 (cycle of 3):
round 1: slow at 2, fast at 3
round 2: slow at 3, fast at 5
round 3: slow at 4, fast at 4
result: 3
list 1 -> 2 -> 3 -> 4 -> None:
round 1: slow at 2, fast at 3
round 2: slow at 3, fast at None
result: 0
single node pointing at itself: 1
empty list: 0
three nodes all holding 7, no cycle: by node 0 | by value says cycle: True
3000 random lists agree with the set-based method; rounds to meet never exceeded tail + cycle length
Worked trace
The list is 1 -> 2 -> 3 -> 4 -> 5 with node 5 pointing back at node 3:
1 -> 2 -> 3 -> 4 -> 5
^ |
+---------+ cycle = 3, 4, 5 (3 nodes)
Rounds from the output: round 1, slow at 2 and fast at 3; round 2, slow at 3 and fast at 5; round 3, slow at 4 and fast at 4, the same node, so a cycle exists. The counting loop starts the walker at slow.next (node 5), goes 5 to 3 to 4 and stops when it is back at 4, having counted 3 nodes. On the acyclic list 1 -> 2 -> 3 -> 4 -> None the hare reaches None in round 2 and the answer is 0.
Complexity
Let the list have a tail of t nodes before the cycle and a cycle of c nodes. The tortoise needs t rounds to reach the cycle, and then the hare is at most c - 1 nodes behind it, closing one node per round, so they meet within t + c rounds. The random test asserts that bound on 3000 lists. Counting adds c steps. Total O(t + c), which is O(n), and space O(1): two pointers and a counter. The dictionary version is O(n) time and O(n) space. Nothing recurses, so there is no stack-depth issue even on a million nodes.
Edge cases and common mistakes
- Empty list: the loop condition fails at once and the answer is 0.
- One node pointing at itself: slow and fast meet after one round; the counting loop returns 1.
- One node with
next = None: no cycle. - The loop condition. Test both
fastandfast.next. Each round readsfast.next.next, sofastmust be a node andfast.nextmust be a node (notNone) before the double step is taken. - Comparing values instead of nodes:
slow.val == fast.valis wrong when values repeat. In the program, the three separate nodes that all hold 7 and have no cycle are reported as a cycle bysays_cycle_by_valueand as 0 by the real function. Compare the node objects withis.
Follow-ups
To find the node where the cycle starts: after the meeting, reset one pointer to the head and move both one step at a time; they meet at the entry node. Brent's algorithm, described in the next section, finds the cycle length directly by letting the tortoise teleport to the hare's position each time the step count reaches a power of two.
Why the gap shrinks by exactly one, and Brent's variant
The program below measures, after each round, the forward distance from the tortoise to the hare (the number of next steps from slow to fast) on the list 1 -> 2 -> ... -> 7 -> back to 3, whose cycle holds 5 nodes. On this list the tail (2 nodes) is shorter than the cycle (5 nodes), so that distance grows by exactly 1 per round, because the hare gains one node per round, and the hare is on the tortoise's node when the distance reaches the cycle length, 5, which is the same node again: round 5 in the output. With a tail longer than the cycle the hare laps the loop before the tortoise enters it, so the printed distance wraps around and is not monotone; what stays true is the rule inside the loop, where the hare gains exactly one node per round.
Brent's algorithm needs only one pointer moving and finds the cycle length directly; it is the length-finding step, so it assumes the list is already known to contain a cycle (Floyd's detection loop above is what establishes that). A hare walks forward one node at a time. Whenever the number of hare steps since the last teleport equals the current window (1, 2, 4, 8, ...), the tortoise jumps to the hare's node and the window doubles. Once the window is at least as large as the cycle and the tortoise sits inside the cycle, the hare returns to the tortoise's node after exactly one lap, and the number of steps counted is the cycle length. In the trace the tortoise teleports to 2, 4 and then 3 (a node on the cycle), and with window 8 the hare comes back to node 3 after 5 steps, which is the cycle length. Interviews usually ask for Floyd; Brent is deeper material, worth knowing as the variant that does not move a second pointer at double speed.
import random
class Node:
def __init__(self, val):
self.val, self.next = val, None
def build(n, cycle_to=None):
nodes = [Node(i + 1) for i in range(n)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
if cycle_to is not None and n:
nodes[-1].next = nodes[cycle_to - 1]
return nodes
def forward_gap(slow, fast):
"""Nodes you step through going forward from slow until you reach fast."""
gap = 0
while slow is not fast:
slow = slow.next
gap += 1
return gap
def floyd_with_gap(head):
slow = fast = head
rounds = 0
while True:
slow, fast, rounds = slow.next, fast.next.next, rounds + 1
print(f" round {rounds}: slow at {slow.val}, fast at {fast.val}", end="")
if slow is fast:
print(", gap 0: they meet")
return
print(f", forward distance slow to fast = {forward_gap(slow, fast)}")
def brent_cycle_length(head, verbose=True):
"""Brent: the tortoise jumps to the hare's position whenever the number of steps taken reaches a power of two."""
power = length = 1
tortoise, hare = head, head.next
if verbose:
print(f" tortoise at {tortoise.val}, hare at {hare.val}, window {power}")
while tortoise is not hare:
if power == length: # window used up: teleport and double the window
tortoise, power, length = hare, power * 2, 0
if verbose:
print(f" teleport: tortoise jumps to {tortoise.val}, window now {power}")
hare = hare.next
length += 1
if verbose:
print(f" hare moves to {hare.val} (steps since teleport: {length})")
return length
print("cycle of 5 (nodes 3..7), fast starts at the head like slow does:")
nodes = build(7, cycle_to=3)
floyd_with_gap(nodes[0])
print("Brent on the same list:")
print("cycle length:", brent_cycle_length(nodes[0]))
import random
rng = random.Random(3)
for _ in range(2000):
n = rng.randint(2, 30)
start = rng.randint(1, n)
assert brent_cycle_length(build(n, start)[0], verbose=False) == n - start + 1
print("Brent matches the expected cycle length on 2000 random lists")
Output:
cycle of 5 (nodes 3..7), fast starts at the head like slow does:
round 1: slow at 2, fast at 3, forward distance slow to fast = 1
round 2: slow at 3, fast at 5, forward distance slow to fast = 2
round 3: slow at 4, fast at 7, forward distance slow to fast = 3
round 4: slow at 5, fast at 4, forward distance slow to fast = 4
round 5: slow at 6, fast at 6, gap 0: they meet
Brent on the same list:
tortoise at 1, hare at 2, window 1
teleport: tortoise jumps to 2, window now 2
hare moves to 3 (steps since teleport: 1)
hare moves to 4 (steps since teleport: 2)
teleport: tortoise jumps to 4, window now 4
hare moves to 5 (steps since teleport: 1)
hare moves to 6 (steps since teleport: 2)
hare moves to 7 (steps since teleport: 3)
hare moves to 3 (steps since teleport: 4)
teleport: tortoise jumps to 3, window now 8
hare moves to 4 (steps since teleport: 1)
hare moves to 5 (steps since teleport: 2)
hare moves to 6 (steps since teleport: 3)
hare moves to 7 (steps since teleport: 4)
hare moves to 3 (steps since teleport: 5)
cycle length: 5
Brent matches the expected cycle length on 2000 random lists
Running the code
Save as cycle_length.py, then run: python cycle_length.py
Needs Python 3.12 and the standard library only.
Given a singly linked list, rearrange it so that nodes at indices 0, k, 2k, ... come first, then indices 1, k+1, 2k+1, ... and so on, preserving relative order within each group, in place. For k = 2 this is the odd/even list problem.
Sample Answer
The idea
Number the nodes 0, 1, 2, ... from the head. The target order is "every node whose index leaves remainder 0 when divided by k, then remainder 1, and so on", keeping the original order inside each remainder. So the job is to deal the nodes into k separate sub-lists by index % k as you walk, then join the sub-lists end to end. "In place" means you relink the existing nodes (change their next pointers) rather than creating new nodes or copying values. For k = 2 this is the classic odd/even list: with 0-based indices, the even-index nodes first, then the odd-index nodes.
Two arrays of k pointers do the dealing: heads[r] is the first node of group r and tails[r] is the last node seen so far in group r. Appending a node to a group is tails[r].next = node, which is O(1).
The brute force and why it is not enough
Copy the values into an array, build values[0::k], values[1::k], ... and write them back (or build new nodes). That is O(n) extra space and does not move the nodes, which is what "in place" forbids. Relinking pointers needs only the 2k group pointers.
Approach
- Walk the list once with a counter
index. For each node computer = index % k. - If group r is empty, the node becomes
heads[r]; otherwise link it aftertails[r]. Either way it becomestails[r]. - After the walk, go through r = 0, 1, ..., k-1, skipping empty groups, and link each group's head after the previous group's tail.
- Cut the last tail: set the final group's last node's
nexttoNone. That node may still point at whatever followed it in the original list. It does exactly when it was not the original last node (for example, the last node of group 1 when k = 2 and the list is1..5), and then, without the cut, the result has a cycle.
Code
The program prints before and after for k = 2, a pointer-state trace for k = 3 on seven nodes, the failure when the cut in step 4 is forgotten, and a seeded check of 500 random lists against a slicing reference. The check also confirms the result uses the same node objects in the expected order, and 174 of the 500 cases have k at least as large as the list.
import random
class Node:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head, limit=50):
out = []
while head and len(out) < limit: # limit guards against an accidental cycle
out.append(head.val)
head = head.next
return out
def show(head, limit=12):
vals = to_list(head, limit)
tail = "None" if len(vals) < limit else "..."
return " -> ".join(map(str, vals + [tail]))
def group_by_index_mod_k(head, k, trace=False):
"""Reorder nodes so indices with remainder 0 come first, then remainder 1, ... (stable, in place)."""
if k < 1:
raise ValueError("k must be at least 1")
heads = [None] * k # first node seen for each remainder
tails = [None] * k # last node seen for each remainder
index = 0
node = head
while node:
r = index % k
if heads[r] is None:
heads[r] = node
else:
tails[r].next = node
tails[r] = node
if trace:
print(f"index {index} (value {node.val}) -> group {r}: "
+ " | ".join(f"g{g}: {show_group(heads[g], tails[g])}" for g in range(k)))
node = node.next
index += 1
new_head = None
last = None
for r in range(k): # stitch the non-empty groups in remainder order
if heads[r] is None:
continue
if last is None:
new_head = heads[r]
else:
last.next = heads[r]
last = tails[r]
if last:
last.next = None # the final node still points into an old position: cut it
return new_head
def show_group(first, last):
out = []
node = first
while node is not None:
out.append(str(node.val))
if node is last: # stop at the group's tail; its .next may still point into another group
break
node = node.next
return "[" + ",".join(out) + "]" if out else "[]"
def group_without_cutting(head, k):
"""Wrong on purpose: same as above but forgets to cut the final next pointer."""
heads, tails, i, node = [None] * k, [None] * k, 0, head
while node:
r = i % k
if heads[r] is None:
heads[r] = node
else:
tails[r].next = node
tails[r] = node
node, i = node.next, i + 1
new_head, last = None, None
for r in range(k):
if heads[r] is None:
continue
if last is None:
new_head = heads[r]
else:
last.next = heads[r]
last = tails[r]
return new_head
def reference(values, k):
return [v for r in range(k) for v in values[r::k]]
print("k=2 (odd/even list), 1..6")
h = build([1, 2, 3, 4, 5, 6])
print(" before:", show(h))
print(" after: ", show(group_by_index_mod_k(h, 2)))
print()
print("k=3 trace on 10..16 (seven nodes)")
h = build([10, 11, 12, 13, 14, 15, 16])
print(" before:", show(h))
h = group_by_index_mod_k(h, 3, trace=True)
print(" after: ", show(h))
print()
print("forgetting to cut the last pointer, k=2 on 1..5 (first 12 values shown):")
print(" ", show(group_without_cutting(build([1, 2, 3, 4, 5]), 2)))
rng = random.Random(41)
checked = big_k = 0
for trial in range(500):
n = rng.randint(0, 12)
k = rng.randint(1, 6)
values = [rng.randint(0, 3) for _ in range(n)] # repeated values: order is judged by position
head = build(values)
nodes = []
node = head
while node:
nodes.append(node)
node = node.next
new_head = group_by_index_mod_k(head, k)
result_nodes = []
node = new_head
while node and len(result_nodes) <= n:
result_nodes.append(node)
node = node.next
expected_idx = [i for r in range(k) for i in range(r, n, k)]
assert result_nodes == [nodes[i] for i in expected_idx] # same node objects, expected order
assert [x.val for x in result_nodes] == reference(values, k)
checked += 1
big_k += (k >= n)
print(f"{checked} random lists match the reference with the same node objects ({big_k} had k >= n)")
for bad in (0, -3):
try:
group_by_index_mod_k(build([1]), bad)
except ValueError as e:
print(f"k={bad}: ValueError: {e}")
Output:
k=2 (odd/even list), 1..6
before: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> None
after: 1 -> 3 -> 5 -> 2 -> 4 -> 6 -> None
k=3 trace on 10..16 (seven nodes)
before: 10 -> 11 -> 12 -> 13 -> 14 -> 15 -> 16 -> None
index 0 (value 10) -> group 0: g0: [10] | g1: [] | g2: []
index 1 (value 11) -> group 1: g0: [10] | g1: [11] | g2: []
index 2 (value 12) -> group 2: g0: [10] | g1: [11] | g2: [12]
index 3 (value 13) -> group 0: g0: [10,13] | g1: [11] | g2: [12]
index 4 (value 14) -> group 1: g0: [10,13] | g1: [11,14] | g2: [12]
index 5 (value 15) -> group 2: g0: [10,13] | g1: [11,14] | g2: [12,15]
index 6 (value 16) -> group 0: g0: [10,13,16] | g1: [11,14] | g2: [12,15]
after: 10 -> 13 -> 16 -> 11 -> 14 -> 12 -> 15 -> None
forgetting to cut the last pointer, k=2 on 1..5 (first 12 values shown):
1 -> 3 -> 5 -> 2 -> 4 -> 5 -> 2 -> 4 -> 5 -> 2 -> 4 -> 5 -> ...
500 random lists match the reference with the same node objects (174 had k >= n)
k=0: ValueError: k must be at least 1
k=-3: ValueError: k must be at least 1
Worked trace
The diagram for k = 3 on seven nodes (indices 0 to 6):
before: 10 -> 11 -> 12 -> 13 -> 14 -> 15 -> 16 -> None
group 0 (indices 0,3,6): 10, 13, 16
group 1 (indices 1,4): 11, 14
group 2 (indices 2,5): 12, 15
after: 10 -> 13 -> 16 -> 11 -> 14 -> 12 -> 15 -> None
The trace lines show each group growing as the walk advances: indices 0, 1, 2 start groups 0, 1, 2; index 3 (value 13) goes after 10 in group 0; and so on until index 6 (value 16) ends group 0 as [10,13,16]. Joining groups 0, 1, 2 gives the printed result. For k = 2 on 1..6 the groups are 1,3,5 and 2,4,6, which is the printed 1 -> 3 -> 5 -> 2 -> 4 -> 6 -> None.
Complexity
One pass over n nodes plus one pass over k groups: O(n + k) time. Extra space is the two arrays of k pointers, O(k). For a fixed k such as 2 that is a constant number of pointers, and no node is allocated or copied. There is no recursion, so Python's recursion limit does not matter, and the loop works on a list of any length.
Edge cases and common mistakes
- Not cutting the final tail. The run above shows the result for
1..5with k = 2:1 -> 3 -> 5 -> 2 -> 4 -> 5 -> 2 -> ..., a cycle, because node 4 still points at node 5. The cut matters whenever the final group's last node is not the original last node. For1..6with k = 2 the final group ends at node 6, which already points atNone, so forgetting the cut goes unnoticed there; keep the cut anyway, since it is unconditional and cheap. - k = 1 keeps the order (one group). k at least n also keeps the order (each node is its own group). Both are in the random check.
- Empty list returns
None. k below 1 raisesValueErrorhere, becauseindex % 0would fail and a negative k has no meaning. - Losing the rest of the list. Appending a node changes only the previous tail's
next, never the current node's ownnext, sonode = node.nextstill reaches the unvisited part. Do not reassignnode.nextbefore you have saved where the walk goes next. - Equal values. The check uses repeated values and compares node objects, so it cannot pass by accident when values repeat.
Follow-ups
To reach O(1) extra space for any k, make k passes, each unlinking one group and appending it to the result: time grows to O(nk). The detail that makes it work is the stride. After group 0 is pulled out, the remaining list holds groups 1 to k-1 interleaved, so group 1 now sits at positions 0, k-1, 2(k-1), ...; after group 1 is gone it is every (k-2)th node, and so on down to every 1st node. The program below prints the result and the remaining list after each pass for k = 3 on seven nodes.
import random
class Node:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def show(head):
out = []
while head:
out.append(str(head.val))
head = head.next
return " -> ".join(out + ["None"])
def group_k_passes(head, k, trace=False):
"""O(1) extra space: pass j pulls every (k-j)-th node out of what is left and appends it to the result."""
result_head = result_tail = None
rest = head
for j in range(k):
step = k - j # groups still interleaved in `rest`
prev = None # node before the current one in `rest`
node, pos = rest, 0
while node:
nxt = node.next
if pos % step == 0: # this node belongs to the group being extracted
if prev is None:
rest = nxt
else:
prev.next = nxt
node.next = None
if result_tail is None:
result_head = node
else:
result_tail.next = node
result_tail = node
else:
prev = node
node, pos = nxt, pos + 1
if trace:
print(f"after pass {j} (positions 0, {step}, {2 * step}, ... of rest): result = {show(result_head)} | rest = {show(rest)}")
return result_head
print("k=3 on 10..16, one pass per group")
print("start:", show(build([10, 11, 12, 13, 14, 15, 16])))
print("final:", show(group_k_passes(build([10, 11, 12, 13, 14, 15, 16]), 3, trace=True)))
rng = random.Random(8)
for _ in range(500):
n, k = rng.randint(0, 12), rng.randint(1, 6)
values = [rng.randint(0, 99) for _ in range(n)]
expected = [v for r in range(k) for v in values[r::k]]
out, node = [], group_k_passes(build(values), k)
while node:
out.append(node.val)
node = node.next
assert out == expected
print("500 random lists match the slicing reference")
Output:
k=3 on 10..16, one pass per group
start: 10 -> 11 -> 12 -> 13 -> 14 -> 15 -> 16 -> None
after pass 0 (positions 0, 3, 6, ... of rest): result = 10 -> 13 -> 16 -> None | rest = 11 -> 12 -> 14 -> 15 -> None
after pass 1 (positions 0, 2, 4, ... of rest): result = 10 -> 13 -> 16 -> 11 -> 14 -> None | rest = 12 -> 15 -> None
after pass 2 (positions 0, 1, 2, ... of rest): result = 10 -> 13 -> 16 -> 11 -> 14 -> 12 -> 15 -> None | rest = None
final: 10 -> 13 -> 16 -> 11 -> 14 -> 12 -> 15 -> None
500 random lists match the slicing reference
The last pass takes every node that is left. Only the fixed set of pointers rest, prev, node, nxt, result_head, result_tail and the counters pos and step are used, whatever k is; each pass walks what remains, so the total work is at most k walks of n nodes, O(nk). If the interviewer asks for stability within groups, this approach already gives it because nodes are appended in walk order.
Running the code
Save as group_by_index.py, then run: python group_by_index.py
Needs Python 3.12 and the standard library only.
Simulate a round-robin scheduler: given tasks as (id, duration) pairs and a time quantum q, return each task's finish time in completion order. Explain which structure you use for the ready queue.
Sample Answer
The idea
Round-robin scheduling gives every unfinished task the processor for at most one fixed slice (the time quantum, q), then sends it to the back of the line so the next task gets a turn. "Front of the line, back of the line" is exactly a queue: first in, first out (FIFO). The ready queue holds the tasks that still need time; each turn you take the front, run it for min(q, time_left), and either put it at the back (work remains) or record its finish time (done). The clock advances by the time actually run, so a task shorter than the quantum gives the processor back early.
Which structure for the ready queue
Use collections.deque (a double-ended queue). The notation O(1) means the number of steps does not grow with the number of items, O(n) means it grows in proportion to the n items, and amortized O(1) means constant when averaged over many calls even if an occasional call is slower. A deque is O(1) at both ends. Dequeuing from the front and enqueuing at the back are both O(1). A Python list works for the back (append is amortized O(1)) but list.pop(0) shifts every remaining element, so it is O(n) per turn. A linked list with head and tail pointers would give the same O(1) cost but needs a node allocation per turn.
Brute force is a for-loop over a list that keeps sweeping all tasks and skips finished ones. It gives the same answers but rescans finished tasks on every sweep and is hard to extend (a new arrival has no natural place). The sweep_all function in the listing is that version: on the example below it makes 12 task visits, 5 of them to tasks that had already finished, while the queue does only the 7 turns that actually happen.
Steps
- Put every
(task_id, duration)into the queue in input order. Rejectq <= 0(a zero quantum would loop forever). - While the queue is not empty: pop the front,
run = min(q, left), addrunto the clock, subtract it fromleft. - If
left > 0, append the task to the back. Otherwise append(task_id, clock)to the results.
Code
from collections import deque
import random
def round_robin(tasks, quantum, trace=False):
"""tasks: list of (task_id, duration), all ready at time 0.
Returns [(task_id, finish_time), ...] in completion order."""
if quantum <= 0:
raise ValueError("quantum must be positive")
ready = deque(tasks) # FIFO ready queue of (task_id, time_left)
clock = 0
finished = []
while ready:
task_id, left = ready.popleft()
run = min(quantum, left) # a task shorter than the quantum gives the CPU back early
clock += run
left -= run
if left > 0:
ready.append((task_id, left)) # back of the line
else:
finished.append((task_id, clock))
if trace:
print(f"t={clock:2d} ran {task_id} for {run} "
f"left={left} queue={list(ready)} done={finished}")
return finished
def reference(tasks, quantum):
"""Slow check: sweep the unfinished tasks in order, round after round."""
left = dict(tasks)
clock, out = 0, []
while left:
for task_id in [t for t, _ in tasks if t in left]:
run = min(quantum, left[task_id])
clock += run
left[task_id] -= run
if left[task_id] == 0:
out.append((task_id, clock))
del left[task_id]
return out
def sweep_all(tasks, quantum):
"""Brute force: every round visits every task, finished or not, and skips the finished ones."""
left = dict(tasks)
clock, out, visits, wasted = 0, [], 0, 0
while len(out) < len(tasks):
for task_id, _ in tasks:
visits += 1
if left[task_id] == 0 and any(t == task_id for t, _ in out):
wasted += 1 # a finished task looked at again
continue
run = min(quantum, left[task_id])
clock += run
left[task_id] -= run
if left[task_id] == 0:
out.append((task_id, clock))
return out, visits, wasted
if __name__ == "__main__":
tasks = [("A", 5), ("B", 3), ("C", 8), ("D", 2)]
print(round_robin(tasks, 3, trace=True))
turns = sum(max(1, -(-d // 3)) for _, d in tasks) # ceil(d / q), at least 1 turn per task
total = sum(d for _, d in tasks)
print(f"turns taken: {turns}; bound T/q + n = {total}/3 + {len(tasks)} = {total / 3 + len(tasks):.1f}")
order, visits, wasted = sweep_all(tasks, 3)
assert order == round_robin(tasks, 3)
print(f"sweep-everything version: {visits} task visits, {wasted} of them to already finished tasks")
rng = random.Random(1)
for _ in range(300):
n = rng.randint(1, 6)
case = [(f"T{i}", rng.randint(0, 9)) for i in range(n)]
q = rng.randint(1, 5)
assert round_robin(case, q) == reference(case, q), (case, q)
assert sweep_all(case, q)[0] == round_robin(case, q), (case, q)
print("300 random cases (durations 0 to 9) match the reference and the sweep-everything version")
print(round_robin([("Z", 0), ("Y", 4)], 3))
try:
round_robin(tasks, 0)
except ValueError as err:
print("ValueError:", err)
The reference function is a slower, simpler version used only for checking: it sweeps the unfinished tasks round after round. The assert loop compares it, and the sweep-everything version, with the queue version on 300 random task lists (durations 0 to 9) and stops with an error on the first disagreement.
Output
t= 3 ran A for 3 left=2 queue=[('B', 3), ('C', 8), ('D', 2), ('A', 2)] done=[]
t= 6 ran B for 3 left=0 queue=[('C', 8), ('D', 2), ('A', 2)] done=[('B', 6)]
t= 9 ran C for 3 left=5 queue=[('D', 2), ('A', 2), ('C', 5)] done=[('B', 6)]
t=11 ran D for 2 left=0 queue=[('A', 2), ('C', 5)] done=[('B', 6), ('D', 11)]
t=13 ran A for 2 left=0 queue=[('C', 5)] done=[('B', 6), ('D', 11), ('A', 13)]
t=16 ran C for 3 left=2 queue=[('C', 2)] done=[('B', 6), ('D', 11), ('A', 13)]
t=18 ran C for 2 left=0 queue=[] done=[('B', 6), ('D', 11), ('A', 13), ('C', 18)]
[('B', 6), ('D', 11), ('A', 13), ('C', 18)]
turns taken: 7; bound T/q + n = 18/3 + 4 = 10.0
sweep-everything version: 12 task visits, 5 of them to already finished tasks
300 random cases (durations 0 to 9) match the reference and the sweep-everything version
[('Z', 0), ('Y', 4)]
ValueError: quantum must be positive
Worked trace
Tasks A=5, B=3, C=8, D=2 with q=3. Each row above is one turn; t is the clock after the turn, and queue is the line after the task has been put back (or dropped). In words: A runs 3 and has 2 left, so it goes behind D. B needs exactly 3, so it finishes at 6. C runs 3 and has 5 left. D needs only 2, so the turn ends early at 11. A finishes at 13 (2 more units), and C gets the processor alone for two more turns (3 units, then 2) and finishes at 18. The total work is 5 + 3 + 8 + 2 = 18, and the last finish time is 18 because the processor never idled. The completion order is B, D, A, C, which differs from the input order: that is the point of round-robin, short jobs finish early.
Complexity
Each task needs ceil(duration / q) turns (ceil rounds up, and a zero-length task still takes one turn). Rounding up adds less than 1 to duration / q, and a zero-length task takes its one turn, so a task takes at most duration / q + 1 turns. Summing over the tasks, the number of turns is at most T / q + n, where T is the total duration (the sum of the duration / q parts) and n is the number of tasks (the sum of the + 1 parts). For the example the code prints 7 turns against a bound of 10.0. Every turn does O(1) deque work, so time is O(T / q + n) (for q = 1 that is O(T + n)). Space is O(n) for the queue and the result list.
Edge cases and common mistakes
- Duration shorter than the quantum: advance the clock by the real run time (
min(q, left)), not by q. Adding q is the commonest bug. It makes every finish time after the first short turn too late (on the example D would finish at 12 instead of 11, while B, which uses its full slice, stays at 6). - Duration exactly divisible by q (B above):
leftis 0 after the turn, so it must finish, not be requeued with 0 left. - Zero-length task: finishes immediately at the current clock without moving time (
Zin the last run). - One task: runs repeatedly alone; finish equals its duration.
- Quantum of 0 or less: reject it.
- Using
pop(0)on a list: correct output, but O(n) per turn. - Returning finish times in input order instead of completion order: the question asks for completion order.
Follow-ups
A task that is preempted (stopped by the scheduler before it has finished, so that another task can run) goes to the back of the line. Tasks arriving at different times need an arrival-sorted list and a check at each turn for tasks that arrived during the slice (they join the back, and commonly a just-preempted task goes behind arrivals that came in during its slice). Context-switch cost (the time the processor spends saving one task's state and loading the next one's) adds a fixed overhead to the clock per turn, which is why a tiny q hurts throughput (the number of tasks completed per unit of time). Turnaround time is a task's finish time minus its arrival time, and waiting time is the turnaround time minus the time the task actually ran; here every arrival is 0, so turnaround equals the finish time. Priorities replace the single queue with one queue per level or a heap.
Running the code
Save the code as round_robin.py.
Run: python round_robin.py (Python 3.12, standard library only)
Given an array, return for each element the first greater element to its right, or -1 if none exists. Aim for O(n) time and explain why the total work is linear.
Sample Answer
The idea in plain words
For each element you want the first value to its right that is strictly greater (not equal), or -1 if none exists. The key observation: scan left to right and keep the indices that are still waiting for a greater value. When a new value arrives, it is the answer for every waiting element that is smaller than it. Those are always the most recent waiting elements, so a stack (last-in, first-out: the newest entry is the first to come off) holds the waiting indices, and resolving them means popping from the top until the top is not smaller than the new value.
The stack has a property worth stating in words: reading from the bottom to the top, each waiting value is equal to or smaller than the one below it (this is what "non-increasing" means). The reason is a short argument. Suppose a waiting value sat directly above a smaller one. When the larger value arrived, the smaller one was already waiting and the larger one is greater than it, so the smaller one would have been resolved and popped at that moment. It cannot still be waiting. You can see the property in the trace below: at i=4 the waiting entries are (1, 7), (3, 5), (4, 4), whose values 7, 5, 4 only go down from bottom to top, and when 6 arrives at i=5 it pops 4 and then 5 from the top and stops at 7.
A stack that keeps its contents in sorted order by popping anything that would break the order is called a monotonic stack (monotonic means always moving in one direction, here never increasing).
The brute force and why it is not enough
For each element, scan right until a larger value appears. On a descending array like [5, 4, 3, 2, 1] no element finds a greater value, so every scan runs to the end and the total is O(n^2). The program keeps this version as the reference to test against.
Approach, step by step
result = [-1] * nand an empty stack of indices.- For each index
iwith valuev: while the stack is not empty and the value at the top index is smaller thanv, pop that indexjand setresult[j] = v. - Push
i. It now waits for something greater. - Indices still on the stack when the scan ends keep their -1.
Equal values do not resolve each other: the comparison is <, so for [4, 4, 4] nothing is popped and the answer is all -1.
The code
import random
def next_greater(nums, trace=False, stats=None):
result = [-1] * len(nums)
waiting = [] # indices still waiting for a greater value; their values never increase
for i, value in enumerate(nums):
while waiting:
if stats is not None:
stats["comparisons"] += 1
if nums[waiting[-1]] >= value:
break # the newest waiting value is not smaller, so nothing below it is either
j = waiting.pop()
result[j] = value
if stats is not None:
stats["pops"] += 1
if trace:
print(f" i={i} value={value}: resolves index {j} (value {nums[j]})")
waiting.append(i)
if trace:
print(f" i={i} value={value}: waiting={[(k, nums[k]) for k in waiting]} result={result}")
return result
def brute_force(nums):
out = []
for i, x in enumerate(nums):
out.append(next((y for y in nums[i + 1:] if y > x), -1))
return out
def demo():
nums = [2, 7, 3, 5, 4, 6, 8]
print("input:", nums)
stats = {"comparisons": 0, "pops": 0}
result = next_greater(nums, trace=True, stats=stats)
print("answer:", result, "| pushes:", len(nums), "| pops:", stats["pops"], "| comparisons:", stats["comparisons"])
print("duplicates [4, 4, 4]:", next_greater([4, 4, 4]))
print("descending [5, 4, 3]:", next_greater([5, 4, 3]))
print("empty []:", next_greater([]))
def random_check():
rng = random.Random(9)
for _ in range(2000):
nums = [rng.randint(-5, 5) for _ in range(rng.randint(0, 12))]
assert next_greater(nums) == brute_force(nums), nums
print("2000 random arrays (with duplicates and negatives) match the brute force")
for n in (1000, 2000, 4000):
nums = [rng.randint(0, 10**6) for _ in range(n)]
stats = {"comparisons": 0, "pops": 0}
next_greater(nums, stats=stats)
assert stats["pops"] <= n and stats["comparisons"] <= 2 * n
print(f"n={n}: pops={stats['pops']} (at most n), comparisons={stats['comparisons']} (at most 2n={2 * n})")
if __name__ == "__main__":
demo()
random_check()
Run, it prints:
input: [2, 7, 3, 5, 4, 6, 8]
i=0 value=2: waiting=[(0, 2)] result=[-1, -1, -1, -1, -1, -1, -1]
i=1 value=7: resolves index 0 (value 2)
i=1 value=7: waiting=[(1, 7)] result=[7, -1, -1, -1, -1, -1, -1]
i=2 value=3: waiting=[(1, 7), (2, 3)] result=[7, -1, -1, -1, -1, -1, -1]
i=3 value=5: resolves index 2 (value 3)
i=3 value=5: waiting=[(1, 7), (3, 5)] result=[7, -1, 5, -1, -1, -1, -1]
i=4 value=4: waiting=[(1, 7), (3, 5), (4, 4)] result=[7, -1, 5, -1, -1, -1, -1]
i=5 value=6: resolves index 4 (value 4)
i=5 value=6: resolves index 3 (value 5)
i=5 value=6: waiting=[(1, 7), (5, 6)] result=[7, -1, 5, 6, 6, -1, -1]
i=6 value=8: resolves index 5 (value 6)
i=6 value=8: resolves index 1 (value 7)
i=6 value=8: waiting=[(6, 8)] result=[7, 8, 5, 6, 6, 8, -1]
answer: [7, 8, 5, 6, 6, 8, -1] | pushes: 7 | pops: 6 | comparisons: 10
duplicates [4, 4, 4]: [-1, -1, -1]
descending [5, 4, 3]: [-1, -1, -1]
empty []: []
2000 random arrays (with duplicates and negatives) match the brute force
n=1000: pops=993 (at most n), comparisons=1985 (at most 2n=2000)
n=2000: pops=1995 (at most n), comparisons=3986 (at most 2n=4000)
n=4000: pops=3988 (at most n), comparisons=7978 (at most 2n=8000)
Worked trace
On [2, 7, 3, 5, 4, 6, 8]:
2waits.7arrives and is greater than 2, so index 0 gets 7. Stack:[7].3is smaller than 7, so it joins the stack:[7, 3].5is greater than 3, so index 2 gets 5; then 7 is not smaller than 5, so the popping stops.4joins:[7, 5, 4].6pops 4 (index 4 gets 6) and pops 5 (index 3 gets 6), and stops at 7.8pops 6 (index 5 gets 8) and 7 (index 1 gets 8) and empties the stack.8itself is pushed and never resolved, so its answer stays -1.- Final answer:
[7, 8, 5, 6, 6, 8, -1].
Why the total work is linear
The inner while loop looks like it could make the algorithm quadratic, but count the pops across the whole run instead of per element. Every index is pushed exactly once, so at most n pops can ever happen. The comparisons are the pops plus at most one failing comparison per outer iteration (the one that ends the loop), so at most n + n = 2n. In the run above, 7 elements gave 6 pops and 10 comparisons. For random arrays of 1000, 2000 and 4000 values, the counters printed pops below n and comparisons below 2n, and the program asserts both bounds. One individual iteration can pop many elements (the 8 popped two), but those pops were paid for when the elements were pushed. This is an amortized argument: the cost is averaged over the whole sequence, not bounded per step.
Complexity
Time O(n). Space O(n): the result array, plus a stack that can hold all n indices at once (a strictly descending array pushes everything and pops nothing).
Edge cases and common mistakes
- Empty array: the loops never run and the result is
[]. - Duplicates: use
<, not<=, if the question means strictly greater. With<=,[4, 4, 4]would wrongly give[4, 4, -1]. - Storing values instead of indices on the stack. You need the index to know where to write the answer.
- Negative numbers need no special handling; the random test includes them.
- The last element is always -1 because nothing lies to its right.
Running the code
python next_greater.py
Python 3.12, standard library only.
Unlock Full Question Bank
Get access to all Linked Lists, Stacks, and Queues interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.