Linked Lists: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
A linked list is made of nodes. Each node holds a value and a reference to the next node (a pointer in C). DSA Topic 10 built a stack from a node whose link was called below; here the same idea becomes a whole structure, so the link is called next.
Write class Node with __slots__ = ("val", "next") and a constructor Node(val, next=None). Then:
- Build three nodes by hand holding 10, 20, 30 and link them with
a.next = bandb.next = c. - Walk from
awithwhile node is not Noneand print the values. - Show that two names can hold the same node:
alias = a.next, then printalias is b. Changeb.valand printa.next.valto show the change comes through the other path. - Show that
a.next = bcopied nothing: no node was created by the assignment. - Count the steps needed to reach the k-th node for k = 0, 1, 2, and say how this differs from
values[k]on a Python list.
Write the three helpers every linked-list answer in this topic uses:
from_list(values)builds a singly linked list from a Python list and returns the head (Noneif empty). Build from the back, so each new node points at the old head.to_list(head, limit=10**6)walks from the head and returns the values. It raisesValueErrorafterlimitnodes, as a guard against a cycle.show(head, limit=30)draws1 -> 2 -> 3 -> None. If a node is met twice it ends withback to index iinstead of looping forever, and pastlimitnodes it ends with....
Explain each line in a comment. Round-trip fuzz to_list(from_list(a)) == a on 200 seeded lists including empty and one item. Then show a four-node list whose tail points back to index 1. Never print a node itself.
Write three walks over a singly linked list: length(head), contains(head, x) and get(head, i). get raises IndexError for i past the end and for a negative i.
Make get count its hops, and print the hops for i = 0, n // 2 and n - 1 at n = 1,000. Then answer: why is the cost O(i) here, when a[i] on a Python list is one address calculation? What would binary search (DSA Topic 3 simulated such a container) cost on a chain? Finally show the difference between two equal values (==) and the very same node (is).
push_front(head, x) makes one new node that points at the old head and returns it as the new head. That is one allocation and one assignment: O(1). (DSA Topic 10 used the same move as a linked stack.) Write it, and push the numbers 0..4 to see the list grow at the front.
Then measure pushing n items to the front, for n = 10^4 and n = 10^5, on four contenders: linked nodes, list.insert(0, x), collections.deque.appendleft (DSA Topic 11) and "append, then reverse once". Use best_of (min of 3), build each container fresh inside the timed function, print every time and every ratio to the linked version, and write the conclusion only from those printed numbers. A hypothesis to test: the gap between insert(0) and the linked version grows with n. What should real code use?
Appending by walking to the end costs O(n) per append, so building a list of n nodes that way is O(n^2). Count the hops for n = 500, 1,000, 2,000 and compare with (n - 1)(n - 2)/2.
Then write SinglyLinkedList with fields head, tail and size, and these methods: append, appendleft, popleft, pop (from the back), len() read from size, iteration by a generator method (__iter__), and a repr (__repr__) that returns the show picture. pop from the back needs the node before the tail, so it walks: count its hops. A _check() method recounts the nodes and asserts head, tail and size. Fuzz 300 seeded operation sequences against a Python list, calling _check() after every operation. With a head and a tail this is a FIFO queue, the subject of DSA Topic 11.
Given a node, linking a new node after it is two assignments, and the order matters. Given a node, deleting the one after it is one assignment.
- Write
insert_after(node, x, stats):new.next = node.nextfirst, thennode.next = new. Count assignments instats["assign"]. - Write
delete_after(node, stats):node.next = node.next.next, counted the same way. Return the removed value. - Trace both with a
showbefore and after on a 5-node list. - Show the counts are the same at
n = 10andn = 10^5(counts, not times), while finding the node to work on costs a walk. - Show what happens if the two insert assignments are swapped.
- Add a comment on what happens to the unlinked node: C would call
free(); CPython frees it when its last reference goes.
Write remove_first(head, x) that removes the first node whose value equals x and returns the head. It has no dummy node yet, so it has three cases:
- the list is empty: return
None - the head matches: return
head.next - a later node matches: stop at the node before it and relink
Test each case, including x absent. Also write a version that forgets the head case and show, on the smallest failing input a search finds, its wrong output beside the correct one. The caller must assign the returned head: show what happens when it does not.
Removing a value from a singly linked list without help has a special case: the head has no node before it, so only the caller can drop it. A dummy head fixes that: make a throwaway node before the head, dummy = Node(None, head), work from it so that every deletion is "delete the node after prev", and return dummy.next.
- Write
remove_first(head, x), which removes the first node whose value equalsxand returns the head, with a dummy head. - Write
remove_all(head, x)with a dummy head, which removes every node equal tox. - Write the version without a dummy as well, and count the
ifstatements in each version and say which special cases disappeared. - Fuzz both against comprehension truths on 300 seeded lists, including empty, all equal to
x, andxat the head and at the tail.
State in a docstring whether each function consumes its input.
Write insert_sorted(head, x) for a list sorted ascending: start from a dummy head, walk until prev.next.val > x, and link the new node after prev. Values equal to x stay in front of the new node, like bisect_right (DSA Topic 3). Prove the order of equals is kept by storing (key, label) pairs ordered by key alone.
- Fuzz against
bisect.insorton a Python list, 300 seeded cases, including the empty list andxsmaller than, equal to and larger than everything. - Count the hops to build a sorted list by
ninserts of seeded random input (random.Random(12).sample(range(n), n)) atn = 1,000and2,000. Print the hops besiden^2/4. The walk is O(n) per insert, so the whole build grows like n^2: that is insertion sort (DSA Topic 9). Merge sort on lists comes later in this topic.
A DNode adds a prev reference. Compare the two on the same operations and count reference assignments (an increment beside each one):
- Singly insert-after: expected 2. Singly delete-after: expected 1. Doubly insert-after (an interior node): expected 4. Doubly delete-this-node (interior): expected 2.
- Deleting a given node from a singly linked list needs the node before it, so it walks from the head: count the hops for the last node of 1,000. A doubly linked node reaches both neighbours itself.
- Memory: print
sys.getsizeofof aNodeand aDNode(CPython, slotted classes, Python 3.13). - Walking backwards from the tail is free on a doubly linked list. Check it against the reversed Python list.
The end nodes need None checks here. The next question removes them with sentinels.
A doubly linked list keeps two references per node, prev and next, so a node reaches both neighbours itself. The awkward part of a bare doubly linked list is the ends: the head has no prev and the tail has no next, so every operation needs None checks. A sentinel fixes that. Two permanent nodes, front and back, hold no value and are never removed, so every real node always has a real prev and a real next.
Write class DList (with a DNode that has __slots__ = ("val", "prev", "next") and __init__(val, prev=None, next=None)) that owns two sentinels named front and back. The first real node is front.next and the last is back.prev. Two private helpers do all the linking: _link_after(node, new) and _unlink(node), and neither has a None check. Then build:
append(v)andappendleft(v), both returning the new node (a handle the caller can keep).pop()andpopleft(), which raiseIndexErrorwhen empty.remove_node(node), which removes any node given its handle and returns its value, in O(1).- Iteration forwards (
__iter__),reversed_values()for backwards, andlen(). check(), which walks forwards and backwards and assertsn.next.prev is nfor every node, and that the size matches.
Fuzz it against a plain Python list on 300 seeded operation sequences (sequences of length 0 to 40), calling check() after every operation and counting any exception as a failure. Assert that the fuzz really popped from an empty list at least once. Name what you would use in real Python code.
You are handed a node of a singly linked list, and no head. Deleting it the usual way needs the node before it, which you cannot reach. There is a trick: copy the next node's value into this node, then unlink the next node. Write delete_held(node) that does it in O(1).
Show three things the trick costs. 1. It cannot delete the tail: show what the naive code does there, and make delete_held raise ValueError instead. 2. It removes a different node object from the one you meant: an outside reference to the node you meant to delete is still in the list, now holding the next value, and an outside reference to the old next node points at a detached node (print both). 3. A doubly linked node does not need the trick: write remove_dnode(head, tail, node) using prev and next, which removes exactly the node you hold, including at either end, and returns the new (head, tail).
Check the singly version against del a[i] for every list length 2 to 8 and every index but the last, and the doubly version for every index.
Reversing a singly linked list means flipping every next link. The classic loop keeps three references: prev (the head of the reversed part so far), cur (the head of the rest), and nxt (a saved copy of cur.next, because flipping the link would lose it).
Write reverse_list(head, trace=False). Each step does three things in order: save nxt = cur.next, point cur.next back at prev, advance both. With trace=True, print show(prev) and show(cur) after every step, so the invariant is visible: prev heads the reversed part and cur heads the rest. Trace it on a 5-node list.
Then check it:
- Fuzz against
a[::-1]on 300 seeded lists of length 0 to 15, including empty, one node and all-equal lists. - Compare sets of
ids before and after to prove no node was created and none was lost. - Show that the old head becomes the tail (its
nextisNone), and that the function consumes its input: the caller's old head variable now sees a one-node list.
Name the library call for a Python list.
Reverse a list by trusting the recursion: reverse the rest (head.next onwards), which returns the new head, then hook the old head behind the reversed rest with head.next.next = head; head.next = None. The base case is an empty list or a single node.
Write reverse_rec(head, depth=0, trace=None). When trace is a list, append one line per call, indented by depth, showing the list each call received, and one line per return showing what it returned. Trace it on 4 nodes. Then:
- Check it against the loop version on lists of length 0 to 800.
- At n = 2,000 the recursion raises
RecursionError. Catch it and print onlytype(e).__name__, never the message or a depth. Show the list is untouched after the failure (all the relinking happens while unwinding), and that the loop version handles 2,000 without trouble. - State the cost: O(n) time and O(n) space, because n frames are alive at the deepest point.
Say, in a comment, what raising sys.setrecursionlimit does (moves the cliff, does not remove it) without doing it here. This is DSA Topic 8's recursion-limit lesson on nodes.
Print the values of a singly linked list tail first (there are no backward links), leaving the list as you found it. Write three versions that each call an emit(value) function instead of print, so the output can be collected:
backward_recursive(head, emit, stats): recurse to the end, emit on the way back.backward_stack(head, emit, stats): push the values onto a Python list used as a stack (DSA Topic 10), then pop.backward_reverse(head, emit, stats, snaps): reverse the list in place, walk it, reverse it back. While it is emitting, a list reader holding the old head sees a changed list: recordshow(head)for that old head andshowof the reversed head insnaps.
Every version records stats["peak"], the most extra items it holds at once (recursion depth, stack length, or 0). Check all three on lists of length 0 to 12, print the peaks for n = 8, then run them at n = 5,000, where the recursive one raises RecursionError (print type(e).__name__ only). Say which survive and why.
An array has len(a) // 2. A linked list has no length until you walk it, so the middle is found with two references: slow takes one step and fast takes two. When fast reaches the end, slow is halfway. This is DSA Topic 4's midpoint in one pass, now on nodes.
Write middle_second(head) (fast and slow both start at head) and middle_first(head) (fast starts at head.next). For an even length they pick different middles: state which is which, and check both for every length 0 to 12 against index n // 2 and (n - 1) // 2 (give the nodes distinct values equal to their index). Return None for an empty list.
The loop test is fast is not None and fast.next is not None. Show that the order matters: swap the two tests and catch the exception on an even-length list (print type(e).__name__).
Find the n-th node from the end of a singly linked list (n = 1 is the last node) in one pass with the gap pointer from DSA Topic 4: lead moves n steps first, then lead and follow move together until lead runs off the end. follow is then on the answer.
Write nth_from_end(head, n) returning (node, hops), where hops counts every .next step. It raises ValueError if n < 1 or n is larger than the length. Also write nth_two_pass(head, n) that counts the length L and then walks L - n steps, with the same return shape. Check both against a[-n] for lengths 0 to 12 and n from 0 to length + 2, expecting ValueError exactly when n < 1 or n is larger than the length. Assert that both versions take exactly 2L - n hops, and say what the one-pass version does and does not gain.
A singly linked list has a cycle when some node's next leads back to an earlier node, so a plain walk never reaches None. Floyd's tortoise and hare finds one with two references: slow moves 1, fast moves 2. If there is a cycle they meet inside it; if not, fast reaches None. DSA Topic 4 proved that the pointers meet, so cite it and do not re-prove it here.
Write has_cycle(head) returning (found, steps) with steps the number of loop rounds. Test it with make_cycle for every length 0 to 10 and every pos from -1 (no cycle) to n - 1, against an oracle that walks the list with a set of ids (DSA Topic 7's seen-set) and says True when it meets a node twice. Assert that Floyd's rounds never exceed n. State the costs: Floyd is O(n) time and O(1) space, the seen-set O(n) time and O(n) space.
Then write the version a student might write by comparing values (slow.val == fast.val) instead of identity, search small no-cycle lists for the first one it gets wrong, and print it.
In a circular singly linked list the last node points back to the first. Keep a reference to the last node only: last.next is the first, so append (new node after last, then last moves to it) and appendleft (new node after last, last stays) are both O(1), and no tail walk is ever needed.
Write class CircularList with last and size, and append, appendleft, popleft (raises IndexError when empty), rotate() (the first node becomes the last: one step of last = last.next), values() and first(). A walk must stop when it is back where it started. show(cl.first()) on a non-empty list ends in back to index 0.
Fuzz it against collections.deque (rotate(-1) is the same move) on 300 seeded sequences. Then use rotate for a round-robin of three jobs with time slices, as in DSA Topic 11, and compare the order of service with a deque version. State the costs.
Two sorted singly linked lists merge into one by relinking, not copying. Keep a dummy head (a node made inside the call and thrown away, so the first real node needs no special case) and a tail pointer. Each round take the smaller front node, link it after tail, and advance. When one list runs out, attach the rest of the other in one assignment.
Write merge(a, b, key=None, stats=None) that consumes both inputs: the result reuses their nodes, and stats["comparisons"] counts the key comparisons. On ties it takes from the left list, so the merge is stable (DSA Topic 9's rule). Then:
- Fuzz against
sorted(a + b)on 300 seeded pairs of sorted lists, including empty and one-node lists. - Compare sets of ids to prove no node was created, none was lost.
- Check stability with
(key, label)records, comparing withsorted(..., key=...)on the left list followed by the right. - Assert the comparison count is at most
m + n - 1. - Build a broken variant that takes the right node on ties, and print the smallest failure next to the truth.
State the costs, and why DSA Topic 2's array merge needed O(m + n) extra space where this one needs O(1).
In a sorted linked list all equal values sit side by side, so one pass is enough. Write dedupe_sorted(head): when cur.next.val == cur.val, unlink cur.next and stay on cur; otherwise advance. Keep one copy of each value.
- Show the bug that advances after an unlink as well. Find the smallest input where it differs from the truth by searching all sorted lists of length 0 to 4 over the values 0 to 2, and print both outputs.
- Write
remove_all_duplicated(head): drop every value that appears more than once, keeping only the values that were unique. It can remove the head, so use a dummy head. - Fuzz both against comprehensions on 300 seeded sorted lists, including empty, one node, all equal and no duplicates.
State time and space.
Two linked lists are equal when their values match in order, so equality is a walk.
- Write
same_values(a, b)that walks both lists at once (O(n)). - Show that
==on two plain nodes holding the same value isFalse: a class with no__eq__compares identity. - Write
copy_list(head)that builds new nodes behind a dummy head with a tail reference. - Show what
copy.copy(head)does: it copies only the first node and shares the rest, so changing the copy's second value changes the original too. - Fuzz
copy_liston 300 seeded lists: equal values, no shared nodes (compare sets ofids while both lists are alive), and changing the copy leaves the original alone.
A Python list is one block of references: inserting at the front moves every reference, and growing may move the whole block (amortised O(1) append, DSA Topic 1). A linked list allocates one object per item and never moves the others. That buys O(1) insert and delete at a node you already hold, nodes that keep their identity (you can hold a handle to one), and O(1) joins. It costs O(n) to reach the i-th item, and an object per item.
Topic 10 already measured the cost side (tracemalloc bytes per item, list against slotted nodes: "a node costs several times a list slot"), and this topic's memory-per-node question measures it again with sys.getsizeof. Do not repeat it. Measure the benefit side: handles.
- Build a list of 5 values, hold the node that carries
"held"(not the head), and push 1,000 more items to the front with a loop ofNode(v, head). - After the pushes, walk the measured number of links from the new head and print, as booleans, that you arrive at the held node (
is) and that its value is unchanged. - Build the same sequence as a Python
list, call.index("held")before and afterinsert(0, v)1,000 times, and print how far the item's index moved and whether the old index still names the item. The list gives the item a new position, the linked list leaves the node where it is. - Print what the linked list charges for this: reaching the held node from the new head now takes 1,000 more steps (count the walk). State time and space.
With a head and a tail reference, joining two linked lists is one assignment, whatever their lengths: tail_a.next = head_b. a + b copies both lists; a.extend(b) copies b. Cutting a piece out after a held node and pasting it after another held node is also a constant number of assignments, the move a text editor makes when it cuts and pastes.
- Write
move_piece(p, h, q, r): the pieceh..qsits right afterp; cut it and paste it afterr. Writemove_back(p, h, q, r)for the reverse. Check both against a list model on 12 nodes. - Measure the join and a cut-and-paste round trip on lists of 10^4 and 10^5 nodes (the moved piece is half the list) against list slicing. The nodes are built and held outside the timer. The hypothesis: the linked time stays roughly flat as n grows ten times, and the list time grows. Print the numbers and let the code state a verdict only where they support it.
- Show that joined lists share nodes from then on: a change made through one shows in the other.
Cost eight operations on four structures: a Python list, a collections.deque (DSA Topic 11), a singly linked list with head and tail, and a doubly linked list with head and tail. The operations: index the middle item, append, appendleft, popleft, insert after a held middle item, delete a held middle item, search for the last item, and join a second list of the same size onto the end.
Each cell is a count, not a time: references moved, nodes read, or references written. Work it out at n = 1,000 and n = 2,000, so growth is shown by the two numbers and not asserted. The linked structures run for real: walks and every pointer assignment have a counter beside them (c counts reads, w counts writes); the list and deque costs are a model (labelled) because their C code cannot be counted from Python, but the real operation still runs and is checked.
Label a row O(1) when the cost barely changes between the two sizes and O(n) when it about doubles, then print which operations a linked list wins outright. End with the verdict for Python code.
Remove the n-th node from the end of a singly linked list (n = 1 removes the last node; n equal to the length removes the head) in one pass. DSA Topic 4 introduced the gap pointer on arrays; here it runs on nodes.
Write remove_nth_from_end(head, n):
- Put a dummy head in front of the list, so removing the real head needs no special case.
- Move
leadforwardn + 1steps from the dummy. Ifleadis alreadyNonebefore a step,nis larger than the length: raiseValueError.n < 1is aValueErrortoo. - Start
followat the dummy and move both untilleadruns off the end.follownow stands just before the target. - Unlink the target with one assignment and return
dummy.next.
Fuzz it against del a[-n] for every n from 1 to the length on 200 seeded lists (including empty, one node and equal values), and check that n = 0 and n = len + 1 raise. State time and space.
Rearrange a linked list so every node with a value less than x comes first, then all the others, with each group keeping its original order (the partition is stable). DSA Topic 2's in-place array partition was not stable; a linked list gets stability for free.
Write partition(head, x) with two dummy heads and two tails: append each node to one group or the other by relinking it, then join the groups. It consumes its input and creates no node.
- Show the classic bug of forgetting to set the second group's last
nexttoNone: when the list's last node goes to the less-than-xgroup, the last node of the other group still points at a later node, and the result has a cycle. Print whatshowdraws, and show that the wrong version is harmless when the last node is>= x. - Fuzz the correct version on 300 seeded lists against two comprehensions, including empty, one node, all less than
x, none less thanxand a list wherexequals every value. - Check with sets of ids that no node was created. State time and space.
Regroup a linked list so the nodes at index 0, 2, 4, ... come first (in order) and the nodes at index 1, 3, 5, ... follow (in order). Do it in one pass with two tails, relinking the existing nodes: no node is created and no value is moved.
Write regroup(head). Keep first_tail on the nodes at even indexes and second_tail on the nodes at odd indexes; remember where the second group starts, link the first group's tail to it at the end, and make sure the second group ends in None.
- Trace it on 7 nodes by printing each group after each round, from its head up to its own tail (the groups still share the not-yet-grouped nodes behind their tails).
- Fuzz against
a[0::2] + a[1::2]for every length from 0 to 12 plus 300 seeded lists. Check with id sets that no node was created.
State time and space.
Swap every two adjacent nodes of a linked list (1,2,3,4 becomes 2,1,4,3); an odd last node stays where it is. Write swap_pairs(head) by relinking, with a dummy head and a prev pointer. Pay attention to the order of the three assignments for each pair.
Then write the tempting shortcut swap_pair_values(head), which swaps the values of each pair and leaves the nodes where they are. It prints the same list, but a reference held to a node now sees a different value. Show both on [1, 2, 3, 4] while holding a reference to the node that started with value 1.
Fuzz swap_pairs against slicing on 300 seeded lists (including empty, one node and an odd length), and check that no node was created. State time and space for both and say which one a handle-based structure (an LRU cache's map from key to node) can use.
Rotate a singly linked list to the right by k places: [1,2,3,4,5] rotated by 2 is [4,5,1,2,3]. k can be larger than the length, and the empty list stays empty.
Write rotate_right(head, k):
- Walk once to find the length
Land the tail. IfLis 0, returnNone. - Use
k % L. If that is 0, return the list untouched. - Walk to the node at index
L - k - 1, the new last node. Itsnextis the new head. - Cut there, and join the old tail to the old head.
Fuzz against a[-k:] + a[:-k] (careful with k % L == 0) for k from 0 to 2L + 1 on every length from 0 to 8 and on 200 seeded lists. Show a huge k such as 10^12 + 2 working in O(L). State time and space, and check that no node was created.
Remove duplicate values from an unsorted singly linked list, keeping the first node of each value. Both versions below consume the input (the result reuses the input's nodes) and return the head. The head is never removed, because the first node of any value is kept, so no dummy head is needed.
dedup_seen(head): walk once with asetof values already met (DSA Topic 7) and unlink every node whose value is in it. State the time and space.dedup_inplace(head, stats): no extra set. For each node, walk the rest of the list and unlink later nodes with an equal value. Count every comparison instats["comparisons"].- Run the in-place version on lists of distinct values at
n = 500,1,000and2,000, and assert the count is exactlyn(n - 1) / 2. Then run both onn = 2,000values drawn from only 10 distinct values and print the counts: the in-place cost depends on how many duplicates there are, the set version's does not. - Show the one thing the in-place version can do and the set version cannot: values that are unhashable (lists) raise
TypeErrorin a set, but==works. - Fuzz both against
list(dict.fromkeys(a))on 400 seeded lists of length 0 to 20, and check that the result is made of the original nodes only.
Reverse the nodes from position left to position right of a singly linked list in one pass, using the classic 1-based positions (left = 1 is the head). The function consumes its input (same nodes, relinked) and returns the new head.
The trick: walk a prev reference (starting on a dummy head) to the node just before left. Let first be the node at left. It stays put and slowly sinks to the end of the sublist, while the node right after it is moved to the front of the sublist (right behind prev), once per step. After right - left steps the sublist is reversed.
Write reverse_between(head, left, right, trace=None). When trace is a list, append show() of the whole list after each move. Raise ValueError (before changing anything) unless 1 <= left <= right <= n. Then:
- Trace
[1, 2, 3, 4, 5, 6]withleft = 2, right = 5. - Show why
left = 1needs the dummy head: print the result forleft = 1with the dummy, and for a copy of the function that returns the oldheadinstead ofdummy.next. - Fuzz against slicing for every valid
(left, right)on lists of length 0 to 8, and check that every invalid pair raises and leaves the list unchanged.
Reverse a singly linked list k nodes at a time: each full group of k nodes is reversed, and a short last group (fewer than k nodes) stays as it is. [1, 2, 3, 4, 5, 6, 7] with k = 3 becomes [3, 2, 1, 6, 5, 4, 7]. Both versions consume the input and return the head; both raise ValueError if k < 1.
reverse_k_group(head, k): a loop. For each group, first look aheadknodes (stop if the list ends early, since reversing a short group would be wrong), then reverse the group, then stitch it between the previous group's tail and the rest. Use a dummy head.reverse_k_group_rec(head, k): the same idea written recursively, so each call reverses one group and trusts the call for the rest. Say how many frames it needs fornnodes.- At
n = 2,000run the recursive version withk = 1and withk = 8. CatchRecursionErrorand print only the type name. Print the frames each needs (aboutn / k) next to the recursion limit, and say what that tells you. - Fuzz both against a slicing oracle for
k = 1to6andn = 0to13, and print a short trace of the example above.
DSA Topic 4 proved that Floyd's two pointers meet inside a cycle, and proved the trick that finds the cycle's first node. Here the same idea runs on nodes. Write the pieces below and check them exhaustively.
find_meeting(head): moveslowby one node andfastby two; return the node where they meet, orNoneiffastreaches the end.cycle_start(head): after they meet, put one reference back on the head and step both by one node at a time. They meet at the cycle's first node. Restate the one-line distance identity in a comment and cite DSA Topic 4 for the proof.cycle_length(start)(walk once round),tail_length(head, start)(the nodes before the start; DSA Topic 4 measured both lengths on an index chain, and on nodes each is one short walk) andremove_cycle(head)(the new part here), which setsnexttoNoneon the node before the start, so the list becomes an ordinary list with all its nodes.- Check everything with
make_cyclefor everyposfrom-1ton - 1and everynfrom 0 to 12, againstcycle_truth: a walk with a dict fromidto index that stops at the first repeated node. - Print the two edge cases: the cycle that is the whole list, and a single node pointing to itself.
State time and space for each function.
Two singly linked lists can share a tail: from some node on, both lists are the very same nodes (the shape of a Y). Find the first shared node, or None if the lists never meet. The comparison is by identity (is): two nodes with equal values in different places are not a meeting.
Use the kit's make_y to build the shapes, and write three finders. None of them changes either list.
meet_seen(a, b): put the ids of every node ofain a set, then walkbuntil a node is in it. State the space.meet_offset(a, b): measure both lengths, move the pointer of the longer list ahead by the difference, then walk both together until they are the same node.meet_switch(a, b, stats): two pointers; when one falls off the end of its list it continues on the other list's head. Both then walkm + nnodes in total and arrive together at the shared node, or together atNone. Count the loop steps instats["steps"]and show it never exceedsm + n + 1.- Print a pair of lists with equal values that share nothing, and show that every finder returns
None. - Fuzz all three on 400 seeded shapes (the two private parts have length 0 to 6, the shared part 0 to 5, values from
0..2so equal values appear everywhere), including a shared part of length 0 and a shared first node.
A singly linked list cannot be read backwards, so a palindrome check needs a trick. Write the two baselines that spend extra space, so the O(1)-space answer later in this topic has something to beat. Neither changes the list.
is_pal_copy(head): copy the values into a Python list, then comparevals[i]withvals[n - 1 - i]by index (no reversed copy). State the space.is_pal_stack(head): withfastandslowpointers, push the first half of the values onto a list used as a stack (DSA Topic 10) whileslowwalks to the middle, skip the middle node when the length is odd, then pop while walking the second half. Aboutn / 2space.- Check both on odd and even lengths, on the empty list and on one node, and against
a == a[::-1]on 300 seeded lists over a two-letter alphabet. - Measure the peak memory of each with
tracemallocatn = 100,000(a palindrome, so the whole list is compared), building the list before tracing starts. Print the bytes, the ratio, and conclude from the numbers you printed.
Check whether a singly linked list reads the same backwards using O(1) extra space: no copy of the values and no stack. The list is changed while the check runs, so the function must put it back before it returns.
Write is_palindrome(head, peek=None, restore=True) (restore=False skips step 4; step 6 uses it):
- Find the middle with
fastandslow(for an even lengthslowstops on the second middle; for an odd length on the middle node). - Reverse the list from
slowto the end in place. Do not cut the first half off: its last node still points atslow. - Compare the first half with the reversed second half, walking while the reversed part has nodes.
- Reverse the second half again, in a
finallyblock, so the caller gets its list back even if a comparison raises.
When peek is a list, append show(head) while the second half is reversed, to see what any other reader of the list would see. Then:
- Check the caller's list is unchanged by values and by node identity (the same nodes in the same order) before and after, on odd and even lengths, on the empty list and on one node.
- Show what happens if step 4 is forgotten.
- Fuzz against
a == a[::-1]on 500 seeded lists over a two-letter alphabet.
State time and space, and say why the temporary change matters when anything else is reading the list.
Reorder L0 -> L1 -> ... -> Ln into L0 -> Ln -> L1 -> Ln-1 -> L2 -> ...: first, last, second, second-to-last, and so on. Change the links, never the values, and use O(1) extra space. [0, 1, 2, 3, 4] becomes [0, 4, 1, 3, 2]. The function consumes its input and returns the head.
reorder(head, cut=True): find the middle withfastandslow(the first half gets the extra node when the length is odd), cut the list afterslow, reverse the second half, then interleave the two halves.- With
cut=Falsethe function skips the cut. Run it on 5 nodes and printshow()of the result: the first half's last node still points into the second half, and the result has a cycle. - Write
reorder_truth(a)on a Python list with two indexes, one from each end, and fuzzreorderagainst it for lengths 0 to 14 and 300 more seeded lengths up to 40.
A non-negative integer is stored in a linked list one digit per node, least significant digit first: 342 is 2 -> 4 -> 3. Add two such numbers and return the sum in the same format. The function returns a new list and leaves both inputs alone.
DSA Topic 2 added digit arrays, most significant first, with the same or carry loop; here the digits are nodes stored least significant first, so the walk goes forward with no index.
add_lists(a, b): walk both lists together with acarryand a dummy head. Handle lists of different lengths and a final carry (99 + 1 = 100needs a node that neither input had). An empty list means "no digits", and two empty lists give an empty list. Print the99 + 1result as one line.- Check the "returns a new list" contract: assert that the result shares no node with either input (the two
idsets are disjoint). - Write
to_digits(n)andfrom_digits(head)to convert, and checkadd_listsagainst Python'sinton 500 seeded pairs of up to 30 digits, including0 + 0and all-nines cases, and check both inputs are unchanged afterwards. - In a comment and in the output, say why this exists as a puzzle: Python's
intnever overflows, but a 30-digit number does not fit a 64-bit integer, so digit lists are how a fixed-width language adds big numbers. Show what a 64-bit integer keeps of one of the sums (its low 64 bits).
Why is least-significant-first the convenient order? Name what a list stored most significant first would need (a reversal, or a stack from DSA Topic 10).
Merge sort is the natural sort for a linked list: splitting needs no indexing (a fast/slow walk finds the middle) and merging relinks nodes, so no buffer is needed (DSA Topic 9 measured the array version's O(n) buffer in its top-down merge sort, and named linked data as a reason to write your own sort). Write it on nodes.
merge(a, b, key, stats): the dummy-head merge from earlier in this topic, written as a loop, taking from the left list on ties so the sort is stable. Count each comparison instats["comparisons"].merge_sort(head, key, stats, depth=0, trace=None): return the head of the sorted list. Split at the middle withfaststarting athead.next(so two nodes split into one and one), cut the list, sort each half recursively, then merge. Record the deepestdepthinstats. Whentraceis a list, append acutline and amergeline for each call that splits, indented by depth.- Trace 8 nodes: use
show()to print the node picture of each cut (the left and right halves after the split), not a comparison log. - Count the
.nexthops made by thefast/slowsplit at every level (stats["hops"]), forn = 2^4up to2^14on shuffled input, and print the total besiden * log2(n); assert it stays within2 * n * log2(n), since each level costs about 1.5 hops per node minus 3 per sublist, so the ratio climbs toward 1.5 as n grows (1.29 at 16,384). The split costs O(n) per level, where the array'smid = (lo + hi) // 2costs O(1), so the total stays O(n log n). Keep the comparison count as one assert (same recurrence as DSA Topic 9's top-down merge sort). The recursion islog2(n)deep, so it is safe at 16,384 nodes, and only the merge would have been dangerous as a recursion. - Check stability with
(key, label)records againstsorted(key=...), and check that the sort made no new nodes (same ids before and after), on empty, one-node, all-equal, sorted and reversed lists as well as random ones.
State time and space (frames, buffers).
DSA Topic 9's insertion sort shifted array items one place to the right. On a linked list nothing shifts: a node is moved into a growing sorted list behind a dummy head by changing two references, and the only cost is the walk that finds its place.
Write insertion_sort(head, stats=None, finger=False) that consumes its input (the result reuses the same nodes) and puts stats["comparisons"] in the dict. Equal values go after the equal ones already placed, so the sort is stable. Then:
- Fuzz it against
sorted()on 300 seeded lists (size 0 included), and check stability with(key, label)records whose<looks at the key only. - Count comparisons at n = 2,000 on strictly ascending, strictly descending and seeded random input. The walk starts at the front, so ascending input is the worst case and descending the best, the opposite of the array version. Assert the exact counts the argument predicts.
- Add the fix: with
finger=True, remember the node inserted last, and when the new value is not smaller than it, start the walk there instead of at the front. Count again, and assert that the result is identical to the plain version.
State time and space for the best, worst and random cases.
You have k sorted linked lists holding N nodes in total. Two plain ways to merge them, with no heap (a heap does it in O(N log k), which is DSA Topic 15, named only):
merge_one_at_a_time(lists, counter): merge list 1 with list 2, the result with list 3, and so on, using the dummy-head merge of two sorted lists.merge_by_scanning(lists, counter): at every step scan the k current heads and take the smallest.
Both consume their inputs, take from the earlier list on ties, and add every key comparison to counter[0]. Then:
- Fuzz both against
sorted()of all the values on 300 seeded cases with k from 0 to 6, empty lists among them, and check that no node was created. - Count comparisons for k = 2, 4, 8, 16, 32, 64 with N = 2,048, and print a table with
k * Nbeside it. - Assert that both stay at or under
k * Nand say what the table shows.
State time and space.
An MNode has next and child. A node's child starts a lower child list, which may have children of its own. Flatten the structure into one list in which each child list follows its parent, and set every child to None. For [1, 2, [3, 4, [5]], 6] that gives 1 -> 2 -> 3 -> 4 -> 5 -> 6. A child list is still just a list, and flattening is a walk over lists.
Write three versions, each taking the head and returning the flattened head:
flatten_inplace(head, stats): at a node with a child list, walk to the child list's last node, join that node to the parent'snext, make the child list the parent'snext, clear the child, and carry on. O(1) extra space.stats["visits"]counts every node step of both walks.flatten_stack(head): an explicit stack of "the rest" pointers (DSA Topic 10).flatten_rec(head): recursion with one frame per nesting level, not per node.
Check all three against flatten_truth on 300 seeded specs (the empty spec included), then measure visits on a deep spec (40 nested levels) and a wide one (1,000 nodes each with a two-node child list). Assert the in-place version never visits a node more than twice.
State time and space for each version.
An RNode has next and random, and random points to any node of the same list or to None (it may point to the node itself). A deep copy is a new list in which every random points to the copy of its target, never to an original.
Write copy_random(head) with a dict from each original node to its copy (DSA Topic 7's dict; DSA Topic 8 copied nested data with shared parts the same way). Two passes: create every copy, then wire next and random through the dict. Then:
- Show the shallow mistake (
copy.random = orig.random) and print that its copy points into the original. - Fuzz the real version on 200 seeded lists (size 0 included): the copy's ids are disjoint from the original's,
random_targetsof both agree, and changing the copy leaves the original unchanged.
State time and space.
DSA Topic 7 built an LRU cache on OrderedDict and named this version. Build it by hand. A dict maps each key to its Entry node, and a doubly linked list with two permanent sentinels, front and back, keeps the entries in recency order: the least recently used is front.next, the most recent is back.prev. Use DSA Topic 7's API:
LRUCache(capacity)raisesValueErrorifcapacity < 1.get(key)returns the value or-1, and a hit becomes the most recent.put(key, value)updates in place or inserts, and evictsfront.nextwhen a new key finds the cache full.keys()lists keys from least to most recently used, andcheck()walks forward and backward assertingn.next.prev is n, that the count matches the dict, and that each key maps to its node.
All linking goes through two helpers, _link_after(node, new) and _unlink(node). Then:
- Count reference writes per operation at capacity 10 and 1,000 and assert that the maximum is the same constant.
- Fuzz against an
OrderedDictreference on 300 seeded sequences, comparing results and key order after every step, callingcheck()each time, and asserting that evictions really happened.
Explain why each part is needed, and state the costs.
A circular list has no None: the last node points back to the first. Here the values go round in sorted order, but you are given any node of the circle, not necessarily the smallest. Write insert_sorted_circular(start, x) that inserts x and returns a node of the circle (start itself, or the new node when the circle was empty). Three cases:
xfits between two neighbours:prev.val <= x <= cur.val.xis a new largest or smallest: it goes at the wrap point, where the values drop from the maximum to the minimum.- Every value is equal (or there is one node), so no pair qualifies: after one full lap, insert anywhere.
An empty circle becomes a one-node circle. Fuzz against sorted insertion on 300 seeded circles, starting from every node of each circle, and check that no old node was lost.
State time and space.
DSA Topic 11 simulated the Josephus problem with deque.rotate and then found the O(n) recurrence. Here the circle is built out of nodes. n people numbered 1 to n stand in a circle and every k-th person leaves, until one is left. Write josephus_linked(n, k, order=None) on a circular chain of Nodes: walk k - 1 steps to the node before the victim and unlink the next one, O(k) per removal and O(nk) in total. If order is a list, append each victim to it. josephus_deque and josephus_list are DSA Topic 11's two simulations (rotate(-(k - 1)) then popleft(), and i = (i + k - 1) % len(a) with del a[i]): paste them as timing contenders; order_truth is Topic 11's list-based removal order, pasted as the order oracle, with a one-line comment above each saying so.
All three raise ValueError for n < 1 or k < 1. Then:
- Assert that
josephus_linked(n, k)equalsJ + 1for every n up to 300 and k up to 8, whereJcomes from DSA Topic 11's O(n) recurrence (J = 0, thenJ = (J + k) % mfor m from 2 to n), and that itsordermatches the list-based removal order for n up to 40. - For k = 2 assert the closed form: with n = 2^m + L the survivor is 2L + 1.
- Count the work (node steps against references moved by
del) at n = 10^4 and 5 * 10^4 for k = 3, then time all three with min-of-3 and print the ratios.
Say which is faster only if the printed ratio supports it.
DSA Topic 9 asked when you would still write your own sort. For a linked list there is a real answer: when handles must stay valid. A handle is a reference to a node kept outside the list. Three ways to sort a list of Rec records (which compare by key only):
sort_by_values(head, stats): copy the values out,sorted()them, write them back. The nodes stay and the values move.sort_by_nodes(head, stats): collect the nodes in a Python list, sort that by value with a stablesort, and relink. The nodes move and each keeps its value.merge_sort(head, stats): the top-down merge sort on the list, with a loop merge.
All three consume their input. stats counts value_writes and link_writes (every .val = and every .next = assignment, merge sort's cuts included). Then:
- Fuzz all three against
sorted()on 300 seeded lists (size 0 included) and assert that the node sorts are stable. - Keep a handle to every original node and count how many handles now see a different value after each sort. Assert that the value-copy sort breaks some and the other two break none.
- Print the counted writes, then time each sort on 10^4 and 10^5 random ints with min-of-3 (the list is rebuilt inside the timed call, so the build is included; the build alone is printed too).
Say which is faster only if the printed ratio supports it.
Cutting a list into pieces is a walk and one assignment per cut. Write two functions, both consuming the input (the pieces reuse its nodes):
split_half(head)is the merge sort's split from earlier in this topic; paste it. It returns(front, back)where the front takes the extra node when the length is odd. Use the fast and slow pair (startfastathead.next, soslowstops on the first middle) and cut the front's lastnext.split_parts(head, k)returns a list of exactlykheads whose lengths differ by at most one, the first parts larger; whenk > nthe missing parts areNone. It raisesValueErrorfork < 1.
Show what happens if split_parts forgets its cuts (print the first part's length beside the correct size), print the part sizes for n = 10 at k = 3, 4 and 11, then fuzz both against slicing for n from 0 to 15 and k from 1 to 6. State time and space.
Five short statements. For each, name the pattern before writing any code, then solve it with no node created beyond what the statement asks for (a printed table lists statement, pattern and cost). Each is fuzzed against a Python-list brute force on 200 seeded lists, size 0 included.
delete_middle(head): remove the node at indexn // 2.swap_kth(head, k): swap the values of the k-th node from the front and the k-th from the end (1-based);ValueErrorifkis out of range.insert_gcds(head): insert between every adjacent pair a node holdingmath.gcdof the two.double_number(head): the list holds the digits of a number, most significant first; return the list for twice the number.merge_between_zeros(head): the list starts and ends with0, with no two zeros adjacent; replace each stretch between zeros by one node holding its sum.
State the time and space of each.
The top-down merge sort on a linked list is log2(n) frames deep, which is safe, but it still needs a call stack. A bottom-up merge sort needs none: treat every node as a sorted run of width 1, merge neighbouring runs into runs of width 2, then 4, 8, and so on until one run covers the list. It needs no buffer either, because the merge relinks nodes (DSA Topic 9 gave the array version a buffer of n items).
Write these, all on nodes, all stable (a tie takes the node from the left run):
split(head, k): cut the list after its firstknodes and return the head of the rest (Noneif there is no rest). It changes the list it is given.merge(a, b, key, stats): the dummy-head merge, a loop, counting each comparison instats["comparisons"].merge_sort_bottom_up(head, key, stats, trace=None): widths 1, 2, 4, ... with a dummy head. For each width, walk the list, cut off a left run and a right run withsplit, merge them, and attach the result behind the previous merged run. Whentraceis a list, appendshow(...)of the whole list after each width.merge_sort_top_down(head, key, stats, depth=0): the recursive version, recording its deepestdepth.
Then:
- Trace 8 nodes, one line per width.
- Count comparisons of both versions for
n = 2^4 .. 2^12(they must be equal: the same runs are merged) and for othern(print both; do not assume they match). - Fuzz stability and node reuse with
(key, label)records on 400 seeded lists of 0 to 40 items, againstsorted(key=...), comparing sets of ids before and after. - Time both at
n = 10^4and10^5withbest_of(the build of the list is inside the timed function for both). The hypothesis: the clock is close, so the real difference is space, not time. Print the ratios and write the verdict from them.
State time and space for each function.
The obvious way to merge k sorted lists is to fold: merge list 1 with list 2, then the result with list 3, and so on. The accumulated list gets longer every step, so each node is compared again and again. The cheaper plan keeps the merges balanced: merge the lists in pairs, then the merged lists in pairs, until one is left. That is log2(k) rounds, and every round touches each of the N nodes about once, so the total is O(N log k). (A heap reaches the same bound, DSA Topic 15; here you only use merge.)
Write these, with a dummy-head merge(a, b, stats) that is a loop and counts comparisons in stats["comparisons"]. Every function consumes its lists (the result reuses their nodes) and returns the head of the merged list, None when there is nothing to merge:
merge_sequential(heads, stats): the fold.merge_rounds(heads, stats): a loop of rounds. Each round merges neighbours in pairs, and an odd list out is carried to the next round. Count the rounds.merge_halves(heads, lo, hi, stats, depth=0): the recursive version onheads[lo:hi](index range, no slicing), recording its deepestdepth.
Then:
- Fuzz all three against
sortedof all values on 300 seeded cases withk = 0 .. 9lists of length 0 to 6, including empty lists and many ties. Also check stability by list order: with(value, list_index)records, equal values must come out in list order. - Count comparisons for
N = 4,096nodes split evenly intok = 2, 4, ..., 256sorted lists. Print the fold, the halves,N * log2(k)andN * (k + 1) / 2, and the ratio fold/halves. Assert the bounds you claim.
State time and space (frames included).
An RNode has val, next and random, where random is a reference to any node of the same list (or to itself, or None). A deep copy must give every copy node a random that points at the copy of the original's target, never at an original. The usual answer keeps a dict from each original node to its copy (two passes). You can drop the dict by using the list's own links as the map: weave each copy in right after its original.
Write copy_with_dict(head) and copy_by_weaving(head). Both return the head of a new list and leave the original exactly as it was. For the weaving one, use these steps (label them # STEP 1 to # STEP 3 in the code):
- Walk the list and insert a copy after every original:
A, A', B, B', C, C'. - Walk again and set each copy's
randomtooriginal.random.next, which is the copy of the original's target (careful:randommay beNone). - Walk once more and unweave: restore each original's
nextand link the copies together. The original list must be exactly as before.
Then check, with the build_random and random_targets helpers below (these are # STEP 4 to # STEP 6 in the code):
- Fuzz 300 seeded cases of 0 to 12 nodes, with
randombeingNone, a different node or the node itself. Check:random_targetsof the copy equals the original's, the two lists share no node (disjoint sets of ids), the original's values, links and randoms are unchanged (compare ids and targets before and after), and changing the copy's values leaves the original alone. - Show what happens if the unweave step forgets to restore the originals'
next. - Measure the peak extra memory with
tracemallocfor both copies atn = 10^5, and print bytes per node beyond the finished copy. The hypothesis is that the dict version needs a lot more, and the weaving version needs almost nothing beyond the copy itself. Write the conclusion from the printed numbers.
State time and space.
Textbooks say a linked list beats an array at insertion and loses at indexing. In CPython the array is a Python list: one block of references that list.insert shifts with a single C memmove. A linked node is a whole Python object reached by following references. So the textbook table needs checking. Build the honest table for these operations (label them # STEP 1 to # STEP 4 in the code):
- A full walk that sums the values of
n = 200,000items: awhileloop over nodes, aforloop over a Python list, andsum()on the list. - 200 random
get(i)atn = 100,000: walkinodes, againsta[i]. - 1,000 inserts at a node you already hold (the middle one) against 1,000
list.insertat the middle index, atn = 10^4and10^5. Rebuild the structure for every timed run (the inserts change it), with the build outside the timer. Then find the break-even with rows atn = 500, 1000, 2000, 4000: the size must stay fixed, so each of the 1,000 steps is an insert followed by a delete of the item just inserted (list.pop(mid), and a delete after the held node). Print the ratio on those rows with no verdict, and print the firstnwhere the list/linked ratio is 2x or more as the break-even. - Walk to the middle, then insert (20 times), against
list.insertat the middle, atn = 100,000.
Time with min-of-3. Print every time and ratio. Give a verdict on a row only when the ratio is 2x or more either way; otherwise print no verdict: within 2x. The break-even rows and the walk against the for loop print the ratio only: both of those are Python-level loops, and their ratio sits too close to 2x to call. The hypotheses to test: the list wins rows 1 (against sum), 2 and 4; the linked list wins row 3 by a ratio that grows with n; the walk against a Python for loop may tie. Write the conclusion from the printed numbers.
A Python list stores one 8-byte reference per item in a single block. A linked list stores a whole object per item, and each object carries its own references. How big is that, really? Measure with tracemalloc (it counts what the allocator hands out, including hidden attribute storage) and compare with sys.getsizeof (one object only).
DSA Topic 10 measured a slotted node against a list; rows 1 and 2 repeat that as the baseline, and the rest are new.
Build n = 100,000 items, all holding the same value object, so only the structure is counted and not the values:
- A Python list (
[value] * n). - A singly linked chain of slotted
Node(val,next), the class used throughout this topic. - The same chain of a plain class
PlainNodewith no__slots__. - A doubly linked chain of slotted
DNode(val,prev,next). - A dict from the integers
0 .. n - 1to slottedEntry(key, val, prev, next)nodes, the layout of the LRU cache. The int keys are part of the layout, so they are counted.
For each, print the tracemalloc bytes per item and, beside it, sys.getsizeof of one node (or of the list or dict divided by n). The hypotheses to test: slots save a large share of a plain node, each extra reference costs about 8 bytes, and sys.getsizeof under-reports a plain instance. Assert only what you can defend (slots smaller than plain, the doubly node bigger than the singly node by a few bytes), and write the rest of the conclusion from the printed numbers.
DSA Topic 7 built an LRU cache on collections.OrderedDict and used move_to_end without asking how it works. Now build the thing itself. MiniOrderedDict is a dict from key to a link node, plus a doubly linked list of those links with two sentinels (front and back, helpers _link_after and _unlink) that holds the order. This is the design CPython's OrderedDict uses: a hash table beside a doubly linked list of its keys (labelled CPython; the exact C layout is not what you are copying).
Write the class with these members (dunders in backticks): __setitem__ (an existing key keeps its place and only changes value), __getitem__, __delitem__, __iter__ (insertion order), __len__, __contains__, get(key, default=None), move_to_end(key, last=True), popitem(last=True) and a check() that walks forward and backward and asserts n.next.prev is n for every link and that the dict and the list hold the same keys. Missing keys raise KeyError, and so does popitem on an empty dict.
- Fuzz against
OrderedDicton 500 seeded operation sequences of 40 steps over 8 keys: compare every return value and every exception type, the key order after each step, and callcheck(). Count how manyKeyErrors the fuzz hit for each operation, and assert each was reached. - Measure time per operation at 100 and at 10,000 keys, for
move_to_endand for assigning an existing key, on both classes. Use min-of-3 and a fixed list of keys. Print nanoseconds per operation, the growth between the sizes for each class, and the ratio between the classes (print it with no clock verdict: the point is the growth, not the winner). Both should grow far less than the 100x a linear structure would show: the number of steps does not depend onn.
State time and space.
An LRU cache evicts the key used longest ago. An LFU cache evicts the key used least often, and breaks ties by evicting the least recently used among them. Every get and every put of an existing key counts as a use. Cache API as in DSA Topic 7: get(key) returns the value or -1, put(key, value), and a capacity of 0 stores nothing.
Build it with O(1) work per operation:
Entry(key, val, count)is a node of a doubly linked list. One sentinel list (front,back, helpers_link_afterand_unlink) holds all the entries with the same use count, oldest at the front. Call that classLevel.LFUCachekeepsmap(key to entry),levels(use count to itsLevel) andmin_count, the smallest count that exists. A touch moves an entry from the levelcto the levelc + 1(and bumpsmin_countif it emptied the lowest level). An insert evictslevels[min_count]'s oldest entry when full, then adds the new entry at count 1.LFUCache(capacity, stats, reset_min=True)counts every link or unlink instats["links"]. Withreset_min=Falseit forgets to setmin_countback to 1 on an insert, the classic trap.
Then:
- Write
LFUTruth: a dict of key to[value, count, last-use tick]that finds the victim by scanning every key for the smallest(count, tick). Count the entries it looks at instats["scanned"]. - Fuzz the cache against the truth on 300 seeded sequences of 60 operations (capacity 0 to 5, 9 keys), comparing every
getresult and the sorted key set after every step, with acheck()on the cache each time. Harness exceptions count as failures. Assert that evictions happened. - Run the same sequences with
reset_min=False: count the failures, find a minimal failing sequence by deleting one operation at a time while it still fails (each step strictly shortens it), and print it with both key sets. - Count work per operation at capacity 10, 100 and 1,000 on 10,000 seeded operations (80% of the traffic on a fifth of the capacity's worth of keys, the rest spread over ten times the capacity). Print links per operation for the cache and entries scanned per operation for the truth. Assert what the counts support.
State time and space.
Earlier in this topic the digits were stored least significant first, so a walk from the head meets the units digit first and the carry flows forward. Now the digits are stored most significant first (123 is 1 -> 2 -> 3), which is how people write numbers. The carry must flow from the far end towards the head, but a singly linked list only walks forward. Three ways around that, each returning a new list in most-significant-first order, and each leaving both inputs exactly as they were:
add_by_reversing(a, b): reverse both lists in place, add digit by digit from the head with a carry (building the answer by pushing each new digit onto the front, which leaves it most significant first with no final reversal), and reverse both inputs back in atry/finally. Extra space: none beyond the result.add_with_stacks(a, b, stats): walk each list once, pushing its digits onto a Python list used as a stack (DSA Topic 10), then pop both stacks together. The inputs are never touched. Record the stack sizes.add_recursive(a, b, stats): pad the shorter list with leading zero nodes (new nodes that point at the original, so the original is unchanged), then recurse to the end and add on the way back, returning(carry, node). One frame per digit; record the deepestdepth. A loop version is versions 1 and 2.
Then:
- Fuzz all three against Python's
inton 500 seeded pairs of numbers with up to 30 digits (include0, an empty list as zero, equal lengths, and a carry out of the top digit). After each call check that both inputs have the same values and the same node ids as before. - At 800 digits the recursive version works; at 2,000 digits it raises
RecursionError. Show both (catch it, print the type name only), and show that the two loop versions handle 2,000 and 20,000 digits. - Print the extra space each version used (stack entries, frames) for two 500-digit numbers.
State time and space for each.
A linked list that nobody changes can be shared. Pushing a song onto the front of an unchanging chain makes a new head that points at the old chain: O(1) time, no copy, and the old chain is still a perfectly good list (it is the previous version). This is how functional languages keep lists, and it is the same Y shape you met when two lists meet in a shared tail. DSA Topic 10 built every version of a stack this way and measured shared nodes against list copies; here the nodes are tuples, and we change a version.
Build a playlist history of n versions, where version k is the first k songs added, newest first:
push(version, song)returns(song, version), a tuple used as a node (Noneis the empty list). Tuples cannot be changed, which is exactly what makes sharing safe. Writeto_list_t(version)to walk one.- Build 1,000 versions as shared chains, and 1,000 versions as copied Python lists (
[song] + previous). Check that versions hold the right songs in both, and that two versions pushed onto the same base share it (is). - A recap row at
n = 1,000only: add upsys.getsizeofof every distinct tuple or list, counting a shared tuple once (an id set), for the shared chains and the copied lists. The song strings are the same for both and are left out. (tracemallocis a poor tool here: CPython may recycle small tuples from a free list.) Print the bytes and the ratio, and assert the shared total is far smaller. - Show why mutable nodes break sharing: two
Nodechains that share a base, then change a value of the base and print both versions. Then try the same change on a tuple node and catch the error (type name only). - "Changing" one song in a persistent chain copies only the path down to it: write
set_at(version, i, song), show that the old version is unchanged, that the tail beyondiis the same object (is), and count the new tuples. Then, on the 1,000-song version, fori = 10, 100, 999: the new tuplesset_atcreates (i + 1, found by walking the new chain until a node of the old chain, bytes by the distinct-idgetsizeofsum) against the 1,000-item list that a copied version needs. Assert the tuple count isi + 1.
State time and space.
A plain linked list pays an object per item and a pointer walk per index. A Python list pays a memmove per insert. An unrolled linked list splits the difference: a linked list of blocks, each block a Python list of at most B items. get(i) skips whole blocks (it walks n / B blocks, not n nodes), and insert(i, x) changes one small block (O(B)). (CPython's collections.deque is built the same way: a doubly linked list of 64-item blocks, labelled CPython; DSA Topic 11.)
Write UnrolledList(B) with these rules:
- Blocks are
Block(items, next). No block is ever empty and none holds more thanBitems. get(i)andpop(i)take0 <= i < len;insert(i, x)takes0 <= i <= len. Anything else raisesIndexError(negative indices are rejected too).insertputs the item into the block it falls in (an index at a block boundary goes to the end of the earlier block) and, if the block now holds more thanB, splits it in two halves.popremoves from one block; an emptied block is unlinked; and if the block and its next neighbour together hold at mostmax(2, B // 2)items, they are merged into one.check()asserts rule 1 and that the sizes add up.
Then:
- Fuzz it against a Python list on 300 seeded sequences of 60 operations for
Bin 2, 3, 4, 5 and 8 (smallBmakes splits and merges frequent), withcheck()after every step. Count the splits and merges and assert both happened. - Measure at
n = 100,000: 300 random-position inserts, then 300 random-positiongets, forB = 16, 64, 256, 1024, 4096, against a Pythonlistand against the plain linked list (only 20 operations for the plain one, because each walks about 50,000 nodes; print microseconds per operation for every row). Rebuild the structure for each timed run, with the build outside the timer. Print every time and ratio, and a verdict only where a ratio is far from 1. Which structure wins each operation is the measurement.
State time and space.
C programs and databases often keep a linked list without allocating one object per node: the nodes are slots in arrays, and a "pointer" is an index. Build that in Python.
ArrayLinkedListkeeps two parallel lists,valsandnxt, with-1playing the part ofNone. Fields:head,freeandsize.- Unused slots are chained through
nxtinto a free list:_allocpops the first free slot (or appends a new one when there is none),_releasepushes a slot back. The free list is a linked stack (DSA Topic 10). - API:
push_front(x),insert_after(i, x),delete_after(i)andpop_front(). Each insert returns the slot index, which acts as a handle. Insert and delete at a held index areO(1). check()walks the list and the free list and asserts that together they cover every slot exactly once.- Fuzz the API against a Python list for 6,000 seeded steps (start from empty), and assert that the arrays never grow past the largest size reached (freed slots are reused).
- Measure at
n = 10^5items that all share one value object: bytes per item withtracemallocand build time withbest_of, against a chain of slottedNodeobjects. The hypothesis is that the array version uses fewer bytes. Print the numbers and write the conclusion from them.
A self-organising list rearranges itself while it is searched. After a successful search, move-to-front moves the found node to the head: O(1) once found, because the search already holds the node before it. Transpose swaps the found node with the one before it.
- Write
find(head, key, policy)for the policies"fixed","mtf"and"transpose". It returns(head, steps, found), wherestepscounts the nodes visited. - Fuzz all three policies against a Python list model on lists of 0 to 8 keys, about 400 searches per policy, hits and misses.
- Build a list of
n = 500distinct keys in a shuffled order and run 5,000 requests two ways: a skewed stream (80% of requests go to 10 hot keys) and a uniform stream. Print the average nodes visited per request for each policy. Then, for the skewed stream, add a steady-state column: run 60,000 requests and average the last 20,000. Count steps, do not time them. - Say what the result means for an LRU cache (DSA Topic 7): move-to-front is the recency order without the map.
next_greater(head): for every node, the first larger value further along the list, or0if there is none. Use one walk and DSA Topic 10's monotonic stack of(index, value)pairs. Compare with anO(n^2)brute force.remove_smaller_stack(head): delete every node that has a strictly larger value somewhere to its right. Keep nodes in order. Use a stack of nodes (O(n)space).remove_smaller_reverse(head): the same result inO(1)extra space: reverse the list, keep a running maximum while walking, delete what falls below it, reverse back.- Both removals consume the input and reuse its nodes. Fuzz everything on 400 seeded lists of 0 to 14 values from a small range (so equal values occur), and check that no new node was made.
Partition a list into three lists (keys less than, equal to, greater than a pivot), sort the first and the last, and join the three. It is stable, and duplicates cost nothing extra. DSA Topic 9 showed quicksort's sorted-input worst case, the three-way partition and random pivots on arrays; on nodes the three-way split relinks instead of swapping, so it is stable and needs no index arithmetic.
partition3, a loop that relinks every node into one of three dummy-headed lists, counting one comparison per node.quicksort(recursive, returns(head, tail)) andquicksort_loop(DSA Topic 8's explicit stack in place of recursion: a stack of tasks, no recursion), with a pivot policy:"first"(the head) or"random"(a node found by a walk: one walk to count the nodes and at most one more to reach the pivot, O(n) and at most two walks, the same order as one partition).- Merge sort (top-down, the merge is a loop) for comparison.
- At
n = 800: print comparisons for three inputs (random, sorted, all equal) for first-pivot quicksort, random-pivot quicksort and merge sort, and the recursion depth of each quicksort run. - At
n = 2,000sorted: catch theRecursionErrorfrom the recursive first-pivot version (print only its type name) and sort the same input with the loop version. - Fuzz both versions and both policies for stability and node reuse on 300 seeded lists of
(key, label)records, starting at size 0.
A sorted doubly linked list can remember the last node it inserted, its finger, and start the next search there, walking forward or back. The cost is O(1 + distance). When values arrive nearly in order, the distance is small. DSA Topic 9's insertion sort is adaptive for the same reason. The insertion sort on a list earlier in this topic kept a one-way finger on a singly list; a doubly linked list lets the finger walk back as well.
FingerList: a doubly linked list with the sentinelsfrontandback, the helpers_link_afterand_unlink, acheck()that verifiesn.next.prev is nfor every node, andinsert(x, use_finger=True). A new value goes after the last value that is<=it.stepscounts the nodes stepped over.- Fuzz against
sorted()on 400 seeded streams, starting at size 0, with equal values, in both modes. - Counted work at
n = 1,000: total steps from the finger and from the head, for streams where every value is withindplaces of its sorted position (d= 0, 5, 20) and for a fully shuffled stream. - Measure at
n = 10^5,d = 10: the finger list againstbisect.insorton a Python list (build included for both). Which wins is the measurement: print both and write the verdict from the ratio.
A doubly linked list has two links to keep right in every node, so each operation has two ways to go wrong. Use the doubly linked kit (DNode, from_list_d, check_links).
reverse_d(head, tail): swapprevandnextin every node in one pass, then swap head and tail. Return(new_head, new_tail). A wrong version that forgets to swap head and tail must failcheck_linkswith a message you print.sort_d(head, key): sort using only thenextpointers (the merge sort on nodes from earlier in this topic, with a loop for the merge), then rebuild everyprevin one extra walk. Return(head, tail). A wrong version that skips the rebuild must failcheck_linkstoo.- Fuzz both on 300 seeded lists of
(key, label)records, sizes 0 to 25: values reversed, links intact, sort stable and equal tosorted(key=...), and the same nodes (compare sets of ids).
Three ways to ask "does this list have a cycle?":
- A seen-set of node ids:
O(n)extra space. - A visited flag stored in each node. It looks like
O(1)extra space, but it needs a field in every node, and the flag has to be reset before the next question. - Floyd's two pointers (DSA Topic 4 proved the meeting; here they run on nodes):
O(1)extra space.
DSA Topic 7 compared a seen-set with Floyd on a value walk (memory and calls); here the new option is a flag stored in the node.
Write all three, each also returning its count of .next reads. Then:
- Count the reads on a list with a long tail and a short cycle, and on a list with a short tail and a long cycle.
- Measure with
tracemallocthe peak extra bytes each method needs on an acyclic list of10^5nodes, and the bytes per node with and without the flag field. - Show the flag's reset bug (a second search on the same list), and show what happens when the nodes are not yours to change (a slotted
Nodehas no flag field). - Fuzz that all three agree on 300 seeded lists, starting at size 0. Brent's variant (DSA Topic 4) is named in a comment only.
In a list of even length n, node i and node n - 1 - i are twins. The largest twin sum is the biggest value(i) + value(n - 1 - i).
twin_sum_list(head): copy the values to a Python list and use indices.O(n)space.twin_fold(head, pair_value, better):O(1)extra space. Find the second-half start with fast and slow, reverse the second half, walk both halves together foldingpair_value(a, b)withbetter, then restore the list. An odd length raisesValueErrorbefore anything is changed; an empty list returnsNone.- The largest twin sum is
twin_foldwithmax; the palindrome check from earlier in this topic is the same walk with a different rule. Write both. - Fuzz on 300 seeded even-length lists (from 0 nodes) with negative values: the answer matches, the list is exactly as before (same values, same nodes, same order), and odd lengths raise.
- Measure the peak bytes of both versions at
n = 10^5withtracemalloc.
Remove runs of consecutive nodes whose values sum to 0, again and again, until none are left. [1, 2, -3, 3, 1] can become [3, 1] or [1, 2, 1]: more than one result is right.
remove_zero_runs(head): prefix sums (DSA Topic 6) with a dict (DSA Topic 7) from each prefix sum to the last node having it, behind a dummy head whose prefix is0. A second walk links each node to the node after the last one that shares its prefix.O(n)time and space. It consumes the input and reuses its nodes.remove_zero_runs_brute(values): repeatedly delete the shortest zero-sum run (the leftmost on ties), on a Python list,O(n^2)per pass.- The fuzz cannot compare the two outputs. It checks properties of the fast result on 400 seeded lists (sizes from 0, values in -3..3): no zero-sum run remains, the survivors are a subsequence of the input in order and are the original nodes, and the total is unchanged.
- Search all lists of length up to 6 over
-2..2for the first input where the two methods give different results, print it, and check that both results have no zero-sum run and the same total.
Linked lists get most of their fame from O(1) insertion and deletion. In CPython, a Python list moves its references with one C memmove, and a node is a whole Python object, so the plain tool often wins anyway. Settle it with six whole tasks. Each is solved first with this topic's linked list and then with the plain Python tool. The data arrives and leaves as a Python list for the first, second, fourth and fifth task; the third and sixth run a script of operations.
- Reverse a sequence (linked reversal against slicing),
n = 10^5. - Merge two sorted sequences (the dummy-head merge against
sorted(a + b)),5 * 10^4each. - A FIFO buffer (a linked queue with a tail against
collections.deque),10^5enqueues then10^5dequeues. - Remove the items that fail a test, multiples of 3 (a dummy-head filter against a comprehension),
n = 10^5. - Sort (linked merge sort against
sorted),n = 5 * 10^4. - An LRU cache of capacity 1,000 over
2 * 10^5seeded operations (the hand-built map plus doubly linked list from earlier in this topic againstOrderedDict; DSA Topic 7 owns theOrderedDictversion).
Use best_of (min of 3), build inputs outside the timed function unless the conversion is part of the task, and check that both solutions give the same result. Print time for each, the ratio, a verdict for the first five tasks from the rule "ratio >= 2: plain tool wins; <= 1/2: linked list wins; otherwise no verdict: within 2x" (the LRU row gets no verdict, because both of its sides are doubly linked lists, and prints the label "both linked: constant factor only"), and the lines of code each solution needs. Write the closing sentence from the printed rows, and say where the linked list stays useful: the held-node insert, measured in the array-against-linked-list question earlier in this topic, is where the linked list stays: inside OrderedDict for the LRU, and hand-built for a cursor in an editor buffer.
Most linked-list bugs have one cause: a reference is overwritten before the value it held was saved. Once the last reference to the rest of a list is gone, nothing can reach those nodes again. Here are three bugs with that cause, each written the way a student would write it:
insert_after_broken(node, x)setsnode.next = newand only thennew.next = node.next, so the new node points to itself.reverse_broken(head)flipscur.next = prevand then advances withcur = cur.next, following the link it has just flipped.delete_after_broken(node)tidies the removed node first (victim.next = None, a C habit beforefree) and then relinks withnode.next = victim.next, which is nowNone.
- Write all three broken functions and their fixes:
insert_after,reverseanddelete_after. - Write an oracle for each on a plain Python list.
- Search every input in order of size (lists of length 0 to 6, every position) and report, for each broken function, how many cases fail and the smallest failing input. Print the broken result with
show()(it is cycle-safe) beside the truth. Any exception counts as a failure. - Check that each fix fails on no case.
State the rule that fixes all three in one sentence.
Three functions from this topic return a new head: reverse(head), push_front(head, x), and remove_first(head, x) when the head itself holds x. A caller that writes reverse(h) instead of h = reverse(h) still holds the old first node.
- For each of the three, call it, ignore the return value, and print
show(h). Say whathnow refers to: the tail of the reversed list, a list missing the new node, or a detached node. - Write
push_front_rebind(head, x), which assignshead = Node(x, head)inside the function and returns nothing, and show that the caller sees no change. Then writerelabel_first(head, x), which setshead.val = x, and show that the caller does see that change. Explain the difference: Python passes each argument as a reference, and the function gets its own copy of that reference (C passes a pointer the same way). Changing the object shows through. Rebinding the local name does not. - Give two fixes. The first is to always assign the returned head. The second is a class
LinkedListthat ownsself.head, withreverse(),push_front(x)andremove_first(x)methods that update it and return nothing that could be ignored. Fuzz the class against a Python list on 300 seeded operation sequences, and assert that the fuzz removed a matching head at least 50 times.
The ignored head was shown briefly earlier in this topic, in the head case of deleting by value. Here it covers every function that returns a head.
A SinglyLinkedList with head, tail and size must keep all three true after every operation. Forget the tail in one place and the class still looks fine, until a later append hangs the new node on a node that is no longer in the list. That item is then gone.
Write the class with append, appendleft, popleft, pop (from the back), remove(x) (the first x, ValueError if absent, like list.remove), clear() and _check(), which recounts the nodes and asserts head, tail and size. A bugs argument switches on one of three slips:
"pop":popnever updatestail."remove":remove(x)of the last node never updatestail."clear":clear()resetsheadandsizebut nottail.
- For each bug, fuzz seeded operation sequences against a Python list, with
_check()after every operation, until one fails. - Shrink the failing sequence: delete one operation at a time and keep the deletion while the sequence still fails. Every accepted step makes it strictly shorter, so the shrinker stops. Print the smallest sequence.
- Replay that sequence without
_check(), plus oneappend(9), and print the linked list beside the Python list: the 9 has vanished. - Show that the fixed class passes 500 sequences, and assert that the fuzz really hit a pop of a one-node list, a remove of the last node and a clear of a non-empty list.
Three recursive list functions look harmless:
length_rec(head):1 + length_rec(head.next).reverse_rec(head): reverse the rest, then hook the old head on behind it.merge_rec(a, b): take the smaller front node and set itsnextto the merge of what is left.
Each one makes one frame per node. The merge is m + n frames deep, not log n. Python stops at its recursion limit (DSA Topic 8), so this is a correctness bug at sizes a loop finds trivial.
- Run all three at 200, 400, 800 and 2,000 nodes, checking each result. For the merge, use two interleaved sorted lists of
n / 2nodes each, so the recursion goes the whole way down. CatchRecursionErrorand print onlytype(e).__name__, never the message or a depth. - Write loop versions
length_loop,reverse_loopandmerge_loop, and check them on the same inputs. - Raise the limit to 3,000 inside
try/finally. Show that 2,000 now passes and 4,000 still fails: the cliff moved, it did not go away. Then run the loops at 10^5. - Merge sort's split recursion is only
log2(n)deep. Givemerge_sort(head, merge, stats)the merge as a parameter, count the deepest split level instats, and show that it fails on 10^4 nodes with the recursive merge and sorts 10^5 nodes with the loop merge.
State time and space for each function. For the recursive ones, count the frames as space.
Fast/slow code (DSA Topic 4, here on nodes) breaks at the ends of a list, on 0, 1 and 2 nodes. Here are four bugs a student writes:
middle_swapped:while fast.next is not None and fast is not None. The order of the tests is wrong, sofast.nextis read beforefastis checked.delete_middle_bad: guards the empty list, then startsfast = head.next.next, which fails on a one-node list.middle_first_bad: the docstring promises the first middle for even lengths, butfaststarts athead, which gives the second.has_cycle_bad: startsslowandfastatheadand testsslow is fastbefore moving them, so every list of two or more nodes "has a cycle".
The middle node from earlier in this topic showed bug 1 by hand; here a search finds all four the same way.
Write each one with its fix (middle_second, delete_middle, middle_first, has_cycle). Give node i the value i, so a returned node names its index. Test every length 0 to 6 (and, for the cycle check, every pos from -1 to n - 1 with make_cycle) against an oracle on indices. Any exception counts as a failure. Print a table of failures, each with its smallest failing input, the broken output and the truth. Then assert that every fix passes.
On a list with a cycle, while node is not None never ends. A length function, sum() over a generator of values, and list() of that generator all hang (and list() also eats memory until the machine gives up). You cannot let a practice answer hang, so give each unsafe walk a step budget: a Budget object whose tick() raises OutOfSteps after 100,000 steps.
- Write
length_unsafe(head, budget)and a generatoriter_values(head, budget). Runlength_unsafe,sum(iter_values(...))andlist(iter_values(...))on a 5-node list and on the same list with its tail linked back to index 2. Print what each returns or raises. - Run the kit's cycle-safe tools on the cyclic list:
to_listwithlimit=100_000(catch itsValueErrorand print its message),show, and Floyd'shas_cycle. Print a table with one row per function, showing whether it is cycle-safe. - Bugs make cycles too: the partition and the odd/even regroup from earlier in this topic make a cycle when they forget the final
None. Here is one not shown yet. Writerotate_right_bad(head, k): the rotation from earlier in this topic, with its cut removed. It links the old tail to the old head but never cuts the new tail (new_last.next = Noneis missing). Search small inputs in order of size for the first one where the result has a cycle, and print it withshowbeside the true rotation. - The fix is that rotation with
new_last.next = Nonerestored. Check it on every list of length 0 to 6 and every k from 0 to 2L + 1, runninghas_cycleon each result before reading it.
@dataclass writes a __repr__ and an __eq__ for you, and both use every field. For a node, one field is next. So repr(node) calls repr(node.next), which calls repr on the node after that, and so on: one nested call (or more) per node. == does the same. copy.deepcopy also goes down the chain one level at a time.
- Define
DCNodeas a plain@dataclasswith fieldsvalandnext. Build chains of 150, 500 and 2,000 nodes and tryrepr(a),a == b(two separate chains with equal values) andcopy.deepcopy(a)on each. Print only"ok"or the exception's type name, never the message or a depth. Print a table: which calls return, and which raiseRecursionError? - Build a two-node cycle and print its
repr. Dataclasses guardrepragainst cycles, so it prints.... Then compare two separate but equal cycles with==: there is no such guard there. - Fix it.
@dataclass(repr=False, eq=False)(or a plain class) keeps the default identity==, and its defaultreprhas a memory address in it, so do not print it. Useshow()for printing. Writesame_shape(a, b)as an iterative equality that also handles cycles (two lists are equal when their values match and their cycles return to the same index). Writecopy_chain(head)as an iterative copy that keeps cycles: a dict maps each old node to its copy, as in DSA Topic 8's deep copy with a memo. Check both at 2,000 nodes and on cycles.
This is CPython 3.13 behaviour. Each node costs one or more Python frames (repr pays for its cycle guard's wrapper too), and that count changes between versions, so the sizes where it breaks move. Label it, and do not quote a depth.
Deleting a node you only hold was shown earlier in this topic. The trick copies the next node's contents into this node, then unlinks the next node. It is O(1), but the node object that leaves the list is the next one, not the one you held. That breaks anything that keeps handles (references to nodes kept outside the list).
Build a small recency list the way a cache would, as a singly linked list of SEntry(key, val) nodes from oldest to newest, plus a handles dict from key to node:
put_new(key, val)appends at the tail.delete(key)uses the copy trick through the handle. It falls back to an O(n) walk for the tail, which the trick cannot delete.touch(key, val)deletes and re-appends, which makes the key the newest.evict()deletes the oldest key and returns it.
- Run
put_newA to E,delete("C"),touch("D", 40),evict()three times, andkeys()after each step. Print each result beside the truth from a Python list of(key, val)pairs. Also print how many handles refer to a node that is detached or holds a different key. - Explain each wrong line, starting from this: after
delete("C"), the handle forDrefers to a detached node. - Show that the honest O(1) delete is the doubly linked list's
_unlink(remove_node in the sentinel list from earlier in this topic). Write the same cache onEntry(key, val)nodes between two sentinels,frontandback. Run the same script, check it against the truth, and fuzz it on 300 seeded operation sequences.
A doubly linked list has two links per node, so every change makes two sets of edits, one for each direction. Do half of them and a forward walk can still look perfect. Here are five bugs:
"remove prev":remove_nodefixesnode.prev.nextbut notnode.next.prev."insert prev":insert_afterforgetsnew.next.prev = new."keep links": a removed node keeps its links, so removing it a second time "succeeds" again (and the size drops twice)."pop empty":poplefton an empty list skips the size check and unlinks a sentinel."move order":move_to_back(node)links the node at the back before unlinking it from its old place.
Write a sentinel DList (front, back, _link_after, _unlink, check()) with append, insert_after, remove_node, popleft and move_to_back, and a bug argument that switches on one of the five. Give each bug a short script that reaches it, and run every script against a Python list. Print a catch table: for each bug, what the script raised (if anything), whether a forward walk agrees with the Python list, whether a backward walk agrees, and whether check() passes. A walk that raises or never ends counts as a catch. The walks carry a step limit, because a broken list can contain a cycle.
The fix pattern is to set a removed node's prev and next to None, and have _unlink refuse a node whose prev is None. A second removal then fails loudly, with ValueError. Show it, and fuzz the fixed class on 300 seeded sequences.
Linked-list questions are usually about the same node (is), not an equal value (==). Here are three mistakes that compare the wrong thing:
meet_by_value(a, b)finds where two lists meet with the length-offset method, but comparesx.val == y.valinstead ofx is y. It reports the first position where the values happen to match.has_cycle_seen_values(head)walks the list and keeps a set of the values it has seen (node.val in seen) instead of the nodes, so a repeated value looks like a revisit. (The value-comparing Floyd check appeared with Floyd's cycle check earlier in this topic.)node in seen_nodes, whereseen_nodesis a Python list, compares with==after an identity check. For a node class that defines__eq__by value (VNode), that says a fresh node with an equal value was "seen". The test is O(n) for every node, even when it gives the right answer.
For 1 and 2, search small inputs in order of size (values from 0..1), using the kit's make_y and make_cycle, and print the smallest one each gets wrong beside the truth. For the meeting point, also print the smallest shape that really does share a tail. For 3, give a "visited before?" walk a list of seen nodes. Show the wrong answer with VNode, and count the __eq__ calls a VNode list makes against a set of ids at n = 200. Fix all three with is and sets of ids, and fuzz the fixes on 300 seeded shapes.
The O(1)-space palindrome check from earlier in this topic puts the list back in a finally block; here is what each shortcut costs. Two plausible versions skip that last step, and a stack version wastes half its work. Write all of them and look at the damage.
is_pal_no_restore(head): find the middle with fast and slow (for an even lengthslowstops on the second middle), reverse fromslowin place, compare, and return the answer without reversing back. This is the restore-free check from earlier in this topic. Call it twice on the same head[1, 2, 2, 1]and print both answers: the second call answers differently.is_pal_early_exit(head): restores the list after the comparison loop, but returnsFalsefrom inside the loop at the first mismatch. Find, by enumerating every 0/1 list of length 0 to 8 withitertools.product, the shortest input on which the caller's list differs afterwards. Print it, the picture afterwards, and how many inputs of that length are damaged.is_pal_restored(head): the restored check from earlier in this topic (the second reversal intry/finally), pasted in as the fix. Check on all those inputs that it answers likea == a[::-1], and that the caller's list has the same values and the same nodes in the same order afterwards.is_pal_full_stack(head), the naive version of the half-stack check from earlier in this topic: push every value on a Python list, then walk again and compare each node with a pop. Count comparisons for this version and for the half-comparing one atn = 1,001and say what the stack version costs in extra space.
State time and space for each.
Relinking functions do not copy: they rearrange the nodes they were given, so the "other" list you still hold is now a piece of the result. Show it, count it and fix it.
merge(a, b): the dummy-head merge of two sorted lists, written to consume its inputs. Aftermerged = merge(a, b)on1 -> 3 -> 5and2 -> 4, printshow(a),show(b)andshow(merged). Count how many nodesaandbshare withmergedby comparing sets ofidvalues (print the count, never anid).plus_last(head, x)claims in its docstring to return a new list withxadded at the end, but it walks to the last node and linksxthere. Show that the caller's list grew, and thatlenof the "original" changed.with_front(head, x)returnsNode(x, head). It creates one node and shares all the others; that is fine when it is documented. Print how many nodes it creates and how many it shares (by id sets); sharing a mutable tail leaks changes, as shown with shared tails earlier in this topic, so do not repeat that demo.- Fixes:
merge_copy(a, b)copies both inputs first (new nodes, same values) and then merges, so the inputs are untouched and share no node with the result;plus_last_copybuilds a new chain. Check both with id sets:merge_copyresult shares 0 nodes with the inputs, andplus_last_copyshares 0 nodes and leaves the input at its old length.
State time and space for each, and say in one sentence which of the two designs (consume, or copy) costs extra space.
Four sentences that appear in linked-list tutorials, each true only under a condition the code often breaks. Test each one by doubling n and printing the growth of counted node visits (a deterministic count, so the ratios do not wobble), then add one direct timing of the fourth claim against a Python list.
- "Deleting from a linked list is O(1)." Write
delete_value(head, x, steps)(search first, then unlink the first match) and run it for the last value atn = 1,000,2,000and4,000. Compare it withdelete_after(prev)when the node before the target is already held. - "Appending is O(1)." Write
append_walk(head, x, steps)(no tail reference) againstappend_tail(tail, x, steps), at the same three sizes. - "
lenis O(1)." Writelength(head, steps)that walks, and a loopwhile i < length(head, steps)that visits every index of a list, atn = 250,500and1,000. Then fix it by asking for the length once. - "Inserting in the middle beats
list.insert." Writewalk_then_insert(head, n, x, steps)(walk to the middle node, then link a new node after it) and run it atn = 1,000,2,000and4,000. Then time it once atn = 100,000(20 inserts, each one walking first) against 20 calls oflist.insertat the middle index, min-of-3. The linked list and the list are built outside the timed function and grow by 20 items per run, which does not change the picture; say so in a comment. The held-node case was measured in the array-against-linked-list question earlier in this topic.
For every claim print the claim, the counts (or times), the doubling ratios and a verdict computed from them: a count ratio near 1 is constant, near 2 is linear and near 4 is quadratic; a time ratio of 2 or more gives a verdict and anything less prints no verdict: within 2x. Do not write a verdict the printed numbers do not show.
In C, free(node) returns a removed node's memory by hand, and forgetting it leaks. Python has no free. CPython (the standard interpreter, 3.13 here) keeps a reference count on every object and frees an object the moment the count reaches 0; a separate cycle collector (the gc module) finds groups of objects that only point at each other. Measure what that means for linked lists with tracemalloc (traced memory in bytes), without weak references and without __del__ (both come much later in Python).
Use n = 100,000 nodes of the slotted Node and DNode classes, values taken from one shared list of ints built before measuring, so the ints are not counted as node memory. Disable the cycle collector with gc.disable() inside try/finally that restores it, and do all the measuring inside that block.
- A singly linked list: print traced memory after the build, then after
del head. It should fall back to about where it began, with nogc.collect(). - A node unlinked from a living list: cut the middle half out of the singly list with one assignment and show the memory falls at once.
- A doubly linked list built with
prevandnext: every pair of neighbours points at each other, which is a reference cycle. Afterdel head, tailthe memory stays; aftergc.collect()it falls. Print whethergc.collect()found at leastnunreachable objects, not the exact number. - One stale handle: keep a reference to a node near the front of a singly list, drop the head, and show the rest of the list stays alive. Then clear the handle's
nextand show the memory falls. That is the fix for a removed node you still hold: clear its links. - The build cost per node at
n = 10^5andn = 10^6, with the collector on and off (min of 3; the build and the freeing of the list are inside the timed function). Print the four times per node and the on/off ratios, and give no clock verdict: the ratios move between runs and machines, and the counted memory above is what carries the lesson.
Label what is CPython behaviour. State time and space for the build, and say what a C version would do differently.
By now each linked-list bug has a favourite symptom: a lost rest, a stale tail, a half-updated prev, a list left reversed, a merge that is not stable, a recursion that runs out of frames. Build one checking harness that any list function or class can be run through, and prove it works by feeding it correct versions (it must stay silent) and broken versions (each must be caught, and the table must say by which check).
The harness has these checks, reported by name: values (the result matches a Python-list model), nodes (no node was created or lost that should not have been, compared by sets of ids), links (a class's own check() holds after every operation: size, tail, and n.next.prev is n both ways), cycle (Floyd's pair finds no cycle), restored (an input that was promised back has the same values and the same nodes in the same order), recursion (the function survives a 2,000-node input without a RecursionError) and crash (any other exception).
- Write the helpers: a
Reportthat records which checks failed,node_ids,has_cycle, andcall(report, fn, *args)that runs a function and turnsRecursionErrorinto therecursioncheck and any other exception intocrash. - Write five subjects, each as a correct version plus broken versions:
insert_at(head, i, x)(broken: the rest of the list is dropped; the two assignments are in the wrong order), a singly list class with a tail (broken: popping the last node leaves the tail stale), a sentinel doubly list class (broken:_unlinkforgets oneprev),is_palindrome(head)(broken: leaves the second half reversed) andmerge(a, b)(broken: takes from the right on ties; recursive). - Write a trial for each subject. Each runs seeded edge shapes (empty, one node, two nodes, all equal, the target at the head, the middle and the tail) and random shapes with
random.Random(12), and the class trials run operation scripts against a Python list model. - Run every version through its trial, print a table with one row per version and one column per check, and assert that every correct version has no failures and every broken version is caught. Assert the check that must catch each bug: the half-updated
prevbylinks, the cycle bycycle, the unrestored list byrestored, the right-on-ties merge byvaluesalone, the recursive merge byrecursionalone.
State time and space for the harness, and say which bugs only one check could catch.
Build a small list library: SinglyLinkedList (head, tail and size) and DoublyLinkedList (two sentinels, front and back) behind one list-like interface, so the same fuzz and the same cost table run on both. The slotted Node and DNode classes from earlier in this topic are the links.
Methods (dunders in backticks): append, appendleft, pop (from the end), popleft, insert(i, x) (clamping like list.insert), remove(x), index(x), extend, reverse() in place, __len__, __getitem__ and __setitem__ with negative indices, __iter__, __reversed__, __contains__, and handles: node_at(i), insert_after(node, x) and remove_node(node). node_at on the doubly list walks from the nearer end. Errors match list: IndexError for a bad index or popping an empty list, ValueError for remove or index of a missing value. Each list counts its node visits in self.visits, and has a _check() (singly) or check() (doubly) that recounts size and links.
The work, in order:
- Write both classes, with the shared behaviour (everything that is just a walk) written once in a base class on top of
_walk()andnode_at(). - Fuzz each class against a Python
liston 500 seeded operation sequences of 30 steps: compare every return value and exception type, the whole list forward and backward, and call the class's check after every step. Exceptions inside the harness count as failures. Assert that the fuzz reachedIndexError,ValueErrorand an empty-list pop. - Print a cost table from counted node visits at
n = 1,000andn = 2,000for each method on each class, with the growth classified from the ratio (near 1: constant, near 2: linear).remove_nodeon a singly list cannot be constant (it needs the node before), and the table must show that. - Name what replaces the library in real Python code.
State time and space per method in comments.
A text editor keeps the document in a buffer and edits it at a cursor. Build three buffers behind one interface and compare them:
LinkedBuffer: a doubly linked list of characters between two sentinels (frontandback), plus a cursor kept as the node just left of the cursor (frontmeans "at the start").ListBuffer: a Python list of characters and a cursor index, editing withlist.insertanddel.GapBuffer: DSA Topic 10's two-stack text editor (before the cursor, and after it reversed), rebuilt here as the comparison: two Python lists used as stacks, the characters before the cursor and the characters after it stored reversed, so that moving the cursor by one is onepopand oneappend.
Interface: insert(ch), backspace(), delete(), left(), right(), home(), end(), mark(), cut(), paste(), text() and cursor_index() (for tests). mark() remembers the cursor; cut() removes the characters between the mark and the cursor (either order) and keeps them as the clipboard, and raises ValueError if there is no mark; paste() inserts the clipboard at the cursor and consumes it. Any insert, backspace or delete clears the mark. In LinkedBuffer the clipboard is a pair of held nodes, so cut detaches the segment and paste joins it back with a constant number of writes; finding which end of the range comes first steps both ends at once, so it costs the length of the range, not the length of the document. Undo is DSA Topic 10's idea and is only named here.
- Write the three classes, each with time and space comments per method.
- Fuzz all three against a plain
strplus an index on 300 seeded edit scripts of 60 operations over short documents (0 to 6 characters at the start): comparetext(),cursor_index()and the exception type after every step. Count and assert that the script reached: backspace at the start, delete at the end, cut without a mark, a non-empty cut with the cursor before the mark, and a non-empty paste. - Measure on a document of
2 * 10^5characters with the cursor in the middle: building the buffer, 2,000 edits near the cursor (inserts, backspaces, deletes and one-step moves, the same seeded script for all three, on a fresh buffer for each run), and one call totext(). Time each piece on its own with min-of-3, check that the three buffers end with the same text, print the times and the ratio of the slowest buffer to the second slowest, and name the slowest only when that ratio is 2x or more (the two faster ones may be close, so do not rank them).
A music player's queue is a circular doubly linked list: after the last song comes the first, and "previous" from the first goes to the last. Build Playlist with no sentinels (the circle has no end to guard), using the kit's DNode with the title as val. The list has a current node (None when the playlist is empty), a dict handles from title to node, a run_start node, and a mode that is "off", "one" or "all".
Methods: add_after_current(title) (the first song becomes current; titles are unique, so a repeated title raises ValueError), remove(title) (removing the current song makes the next one current, and removing run_start hands that role to its next song; an unknown title raises KeyError), next() and prev() (always wrap), jump(title) through handles in O(1), move_up(title) and move_down(title) (swap a song with its neighbour by relinking, not by copying titles), song_ended() (what the player does when a song finishes: mode "one" stays, "all" keeps wrapping, "off" stops before it would return to the song where the run began, which is the first song added or the last jump, and returns False), shuffle(rng) and titles() (the titles starting from the current song, going forward) and check().
- Write the class.
check()walks the circle both ways and asserts that it closes after exactlylen(handles)steps and thathandlesand the circle hold the same nodes. - Print a short session: add five songs, then show
titles()afternext,prevfrom the first song,move_upof the first song (the circle wraps, so it swaps with the last song),removeof the current song, and eight calls tosong_ended()in each of the three modes starting from the same song (print the title playing after each call, orstop). shuffle(rng)is Fisher-Yates over a Python list of the nodes (current song first), then relinks the circle; the Fisher-Yates step is a separate functionfisher_yates(items, rng). Check that a shuffle keeps the same nodes and the same current node, that the same seed on a Python list gives the same circle, and that over 6,000 seeded runs offisher_yateson three items each of the 6 orders appears between 800 and 1,200 times.- Fuzz 400 seeded sequences of 40 operations against a Python list plus the current title: after every step compare
titles()(the model rotated to start at the current title), the backward walk, and the exception type, and callcheck().
State time and space per method in comments.
DSA Topic 7's cache service counted entries on an OrderedDict. A real cache counts bytes and forgets things that are too old. Build WeightedCache from the pieces of this topic: a dict from key to Entry and a doubly linked list with two sentinels (front, back; helpers _link_after and _unlink) that keeps recency order, the least recently used next to front. Each Entry has key, val, size, expires, prev and next.
WeightedCache(budget, clock):budget >= 1bytes (elseValueError);clockis an injected object with an integernow, which the test advances (no wall time, Rule 8).put(key, value, size, ttl=None): refuses withValueErrorbefore touching anything ifsize < 1orsize > budget. Otherwise it drops an existing entry for the key (an update, not an eviction), then evicts from the old end until the new entry fits, then links the new entry as the most recent.expiresisclock.now + ttl, orNonefor never.get(key)returns the value or-1. An entry is expired whenclock.now >= expires; an expired entry is dropped (a miss and an expiration), a live one becomes the most recent (a hit).sweep(stop_at_live=False)walks from the old end and drops expired entries; it returns(removed, examined). Withstop_at_live=Trueit stops at the first live entry.- Counters
hits,misses,evictions,expirations. An entry found expired at the old end during eviction counts as an expiration, not an eviction.keys()lists from least to most recently used,usedis the bytes held, andcheck()walks both ways and asserts the dict, the list andusedagree andused <= budget.
- Write the class and run a short story (budget 10) that prints
keys(),usedand the counters after an eviction, a refused entry and an expiry. - Show when "sweep from the old end, stop at the first live entry" is right and when it is not: with one shared
ttland noget, expiry order equals list order; with mixedttlvalues or after aget, the stop leaves expired entries behind. Print removed and examined for both sweeps in both situations. - Fuzz against a list-based truth (a Python list of
[key, value, size, expires]searched linearly, written separately) on 500 seeded sequences of 40 operations at budget 30, comparing every return value, exception type,keys(),usedand all four counters after each step, and callingcheck(). Assert the fuzz reached refusals, expiry atget, expiry in a sweep and an expired entry found at the old end during aput.
State time and space in comments.
A sparse polynomial such as 3x^1000 - 2x + 5 has three terms, not 1,001 coefficients. Store it as a singly linked list of Node((coef, exp)) in strictly decreasing exponent, with no zero coefficients; the zero polynomial is the empty list (None). Python's int is unbounded, so exact coefficients never overflow (a C long would).
Write these, each returning a new list (none consumes its inputs; say so in the docstring):
from_dict(d)andto_dict(p)between{exp: coef}and the list, andcheck_poly(p)asserting the two invariants.add(p, q, cnt)andsub(p, q, cnt): a merge with a dummy head. Equal exponents combine, a zero sum is dropped.cnt[0]counts exponent decisions (one per step of the main loop).scale(q, c, e)(multiply by a single term), thenmul_one_at_a_time(p, q, cnt)(add the partial products to a running result) andmul_by_halves(p, q, cnt)(merge the partial products in rounds of pairs).evaluate(p, x)by Horner's rule along the list: between two terms the exponent drops by a gap, so multiply bypow(x, gap).derivative(p)andto_text(p), which prints3x^4 - 2x + 5,-x^2 + 1,xand0in those shapes.
- Assert the text of four hand-written polynomials, then fuzz everything against a dict-of-exponents model on 300 seeded pairs (0 to 6 terms, exponents 0 to 8, coefficients -3 to 3):
add,sub, both products,evaluateatxin-2, 0, 1, 3,derivative,to_textandcheck_polyon every result. Harness exceptions count as failures; assert the fuzz hit an empty operand and a sum that cancelled a term to zero. - Count the exponent decisions of the two products for two shapes: sparse (60 terms each, exponents drawn from
range(10**6), so nearly every product term is new) and dense (all exponents0..59, so partial products overlap and the running result stays short). Print the counts and their ratio for each shape. Say which method the counts favour in each shape, from the printed numbers, and name the heap-based merge of k lists asO(N log k)(DSA Topic 15), where N = n * m is the number of partial-product terms before any combine.
State time and space for each function.
Put every linked-list sort from this topic behind one interface: sort(head, c) takes a head, returns the sorted head, reuses the input's nodes (it consumes its input), compares values with < only, and adds to a counter c = [comparisons, link writes]. The five contenders, each cited, not re-derived:
insertion_sort: the dummy-head insertion sort with the remembered point (start the walk at the node inserted last when the new value is not smaller than it).merge_sort_td: top-down merge sort (split with fast and slow, merge with the dummy-head merge written as a loop).merge_sort_bu: bottom-up merge sort withsplit(head, k).quick_sort: three-list quicksort (less, equal, greater) with a random pivot node, seeded.via_sorted: the nodes into a Python list,list.sort(key=), relink.
- Fuzz all five against
sorted()on 300 seeded lists of sizes 0 to 30 (exceptions count as failures). - Check stability with
(key, label)records whose__lt__compares keys only, on five input kinds atn = 2,000: random, sorted, reversed, few unique (4 keys) and all equal. - Count comparisons and link writes on the five kinds:
n = 2,000for insertion sort andn = 10,000for the rest. Print two tables. Then print, computed from the counts: insertion sort's cheap kinds against its random cost as a multiple ofn^2; merge sort's comparisons againstsorted()'s; quicksort against merge sort on random and on all-equal input. - Time the four
O(n log n)sorts on one random list ofn = 50,000, each run rebuilding its list (the build is also timed alone and printed). Print each time as a multiple of thesorted()route. Give a clock verdict only where the measured ratio is at least 2.5x; among the hand sorts, say "no clock verdict" if they are within 2x of each other and let the counts carry the comparison.
State time and space for every function, best and worst where they differ.
Write a small ASCII visualiser for every kind of list in this topic. No re and no captured stdout: every picture is built as a string with join and printed.
draw_singly(head):[1|*]-->[2|*]-->[3|*]-->None; a list with a cycle ends in--> back to [v] (index i).draw_doubly(head):None<--[1]<->[2]<->[3]-->None; a link whoseprevdoes not point back is drawn-->?, so a half-updated list shows where it broke.draw_multilevel(head): one line per level, each child list drawn under its parent's box after a| child list of [v]line.draw_random(head): the boxes, then a table of each node'snextandrandomas indices.
All of them must terminate on a cycle (use a dict keyed by id(node)) and must never print an id or a default repr, so the output is identical on every run.
- Print one picture of each kind, including an empty list, a cycle, and a doubly linked list with one
prevbroken on purpose. - Check: exact strings for two small lists; for every
nfrom 0 to 11 and every cycle position (-1ton - 1), the singly picture terminates with exactlynboxes; on 200 seeded multilevel specs the multilevel picture has one box per node. - Draw the frames of the iterative reversal of
1..5: the boxes stay in their original left-to-right places, each link is drawn the way it points now (-->,<--or a gap), and the namesprev,curandnxtare written under the boxes they reference. - Draw Floyd's slow
Sand fastFstepping on a 6-node list whose tail links back to index 2, one frame per step, until they meet; print the step count and the meeting node's value.
State time and space for each drawing function.
A rail yard keeps each train as a doubly linked list of cars between two sentinels (front and back), and a dict of handles from car id to its node. Each node also records the name of the train it is on, so a bad move can be refused in O(1).
Yard methods:
add_train(name, cars).couple(a, b): trainbgoes behind trainaand the namebis retired: one join.uncouple(name, car, new_name):carand every car behind it become a new train, facing the same way: one cut at a held node.move_block(src, first_car, last_car, dst): the cars fromfirst_cartolast_car(insrc's order) go to the end ofdst.turn(name): turn the train around inO(1)with aflippedflag. Every walk goes through onestep(node)method that respects the flag, so a turn costs nothing until something walks or splices. When two trains facing different ways are coupled, physically reverse the shorter one first and say that this is where the deferred cost is paid.
Refuse with ValueError: an unknown train, a car that is not on the source train, coupling a train to itself, a block whose last car comes before its first (an empty block), and duplicate names or cars.
- Trace a short session: couple a turned train onto another, uncouple, move a block, and show three refused moves. Call
check()(links, sizes and owners) on every train. - Fuzz against a model that keeps each train as a Python list (
turnislist.reverse()) on 300 seeded scripts of 40 steps: compare the exception type and every train after every step, and assert that turns, couples, uncouples, moves, refusals and empty blocks were all reached. - Count link writes: two turns and one couple of same-facing trains at 10 and at 10,000 cars per train. The links must not grow with the train; print the relabelling cost beside them, which does.
State time and space per method.
Build a small matching engine.
- Each price level is a FIFO doubly linked list of resting orders between two sentinels, oldest first (time priority).
- A dict from order id to its node makes
cancel(oid)O(1)to unlink. - The prices on each side are kept in a sorted Python list with
bisect(DSA Topic 3). Best bid is the highest buy price and best ask the lowest sell price. Name the production choice: a balanced search tree (DSA Topic 14) or a heap (DSA Topic 15).
submit(oid, side, price, qty) matches an incoming order against the other side: best price first, oldest first within a price, with partial fills at the resting order's price. It returns the fills as (maker id, taker id, price, qty) and rests whatever is left. A filled order is unlinked and its handle dropped, and a level that empties is removed. A duplicate id, a bad side or a quantity of 0 or less raises ValueError; cancel of an unknown id returns False. Add depth() (every level from best to worst, with its orders and quantities) and check() (links, counts, sorted prices, and a book that is never crossed).
- Trace four resting orders and one buy that sweeps two levels with a partial fill, then cancel an order twice.
- Fuzz against
NaiveBook, which keeps all resting orders in one Python list and scans it for the best match each time, on 300 seeded streams of 60 events. Compare every fill list, every cancel result, every exception type and the whole depth after every event. Assert that the fuzz reached fills, partial fills, cancels of known and unknown ids, refused orders and emptied levels. - Count the link writes of one cancel from the middle of a level of 10 orders and of 10,000 orders.
State time and space per method.
Simulate a memory allocator over total units. The free blocks (start, size) form a sentinel doubly linked list in address order, and two free blocks never touch.
allocate(n): first fit takes the first block big enough; best fit takes the smallest block big enough (the lowest address on a tie) and may stop early on an exact fit. Allocate from the block's start, unlink a block that becomes empty, and return the start orNonewhen nothing fits.n <= 0raisesValueError.free(start): walk to the block's place, insert it, and merge it with a free neighbour on either side. Once the place is found the merge isO(1). It is DSA Topic 9's merging of touching intervals, done with two link checks. Freeing something that is not an allocated start raisesValueError.free_blocks(),stats()(total free, largest block, block count) andcheck().
- Trace three allocations and three frees that leave a hole, merge on one side, then merge on both sides.
- Fuzz both fits against a bitmap model (a Python list of booleans, scanned for runs of free units) on 300 seeded scripts over 0 to 64 units. Compare every return value, exception type and the free-block list with the bitmap's maximal free runs. Assert that the fuzz reached no-fit allocations, exact fits, two-sided merges and bad frees.
- On 10 seeded workloads of 4,000 operations over 10,000 units (slightly more allocations than frees), report for each fit the failed allocations, the average number of free blocks, the fragmentation (
1 - largest free block / total free, averaged) and the free-list nodes visited. Name a winner on failures only if they differ by at least 1.2x; otherwise say so and let the walking cost decide.
State time and space per method.
An interviewer says: "Tell me about linked lists." Give the explanation as eight short points, each one backed by two or three printed lines from code you write on the spot:
- A node and a reference: linking copies nothing.
- Singly against doubly: what it costs to unlink a node you hold.
- The dummy head:
remove_all(head, x)with no head special case, shown on four inputs including the empty list. - Iterative reversal.
- The fast and slow pair: the middle, and Floyd's cycle check (DSA Topic 4 proved why it works).
- Merging and merge sort: relinking, no new nodes (checked with id sets, never printed).
- The LRU cache from a dict and a doubly linked list, checked against
OrderedDict(DSA Topic 7) on one short script. - Why Python code rarely uses one:
get(i)steps againsta[i], and bytes per item fromtracemallocfor a chain of slotted nodes against a list (labelled CPython).
End with what you would use instead, and when a hand-built list still pays. State time and space for every function.
Five list functions, each with one bug. For each one, write down before running anything what goes wrong and the smallest input that shows it. Then confirm the prediction with a brute-force search over small inputs, shortest first, and fix the bug.
- A merge of two sorted lists that forgets to hang the leftover run on the tail.
- A right rotation by
kthat never reduceskmodulo the lengthL. - A reversal in groups of
kthat also reverses the short last group. - A multilevel flatten that splices each child list in but leaves the parent's
childreference set. - A cycle-start search that, after the pointers meet, moves both back to the head.
Each function takes fixed=True/False. For each bug, print the prediction beside the input the search found and assert they match. Then show the fix passing every small input and 300 seeded random inputs (exceptions count as failures). State time and space for every function.
The interviewer gives three APIs as complexity targets. Design each one, then fuzz it against a brute force.
- Front, middle and back.
push_front,push_middle,push_back,pop_front,pop_middleandpop_back, all inO(1), with DSA Topic 11's definition: withmitems,push_middleputsxat indexm // 2andpop_middleremoves index(m - 1) // 2. Popping an empty queue raisesIndexError. DSA Topic 11 kept two deques balanced. Here, use one sentinel doubly linked list and a referencemidto the node at index(m - 1) // 2, and work out for each operation whethermidmoves one step forward, one step back, or stays.check()walks to index(m - 1) // 2and asserts it ismid. - A phone directory.
get()hands out any available number or-1,check(n)andrelease(n), allO(1). Use a free list: available numbers are a singly linked list used as a stack (DSA Topic 10's linked stack, used as an allocator), with one flag per number so a double release is ignored. Releasing an out-of-range number raisesValueError. Several numbers can be right forget, so the fuzz checks properties: the number was free, and-1comes back exactly when none is. - The first unique number of a stream.
add(x)andfirst_unique()(or-1), bothO(1). DSA Topic 7 handled a character stream with an insertion-ordered dict plus arepeatedset; itsfirst()isO(1)only because at most 26 letters are live. For unbounded numbers,next(iter(d))skips every deleted slot: time it after deletingn - 1ofnkeys from the front, atn = 10^4and10^5, beside the linked version. Keep the values seen exactly once in a doubly linked list, oldest first, with a dict from value to node and a set of repeated values. The brute force recounts the stream after every add.
Trace each design briefly, then run 300 seeded scripts per design (exceptions count as failures), and assert that the empty-pop and full-directory cases were reached. State time and space per method.
The interview starts with the classic: two non-negative numbers stored as linked lists of digits, least significant digit first, added into a new list. The add with a carry, and the most-significant-first version with two stacks, were built earlier in this topic. Carry them over in a few lines each, then take the follow-ups:
subtract(a, b)returning(sign, digits), where the result may be negative. Writecompare(a, b)for magnitudes in one pass (careful: in a least-significant-first list, the deciding digit is the last difference seen) andstripfor leading zeros, which sit at the end of the list. DSA Topic 2 did compare and multiply-by-digit on digit arrays, most significant first; here the order is reversed.times_digit(a, k)for one digit, thentimes(a, b)by schoolbook multiplication: one partial product per digit ofb, shifted by pushing zeros onto the front, summed withadd.- Every function returns a new list and leaves its inputs unchanged. Check all of them against Python's
inton 500 seeded pairs of up to 29 digits, including 0 anda == b, and check that no result has a leading zero. - Why Python makes all of this unnecessary:
intis unbounded. Print one line saying so; the 64-bit Clongoverflow was simulated in DSA Topics 4 and 6, so cite it rather than repeat it.
State time and space for every function.
Build an inbox engine that uses every idea in this topic.
- Timeline. Messages
(id, time)come fromkseeded sources, each already sorted by time. Link each source as a chain and merge the chains by halves (pairs of chains, then pairs of results:O(N log k); a heap gives the same bound, DSA Topic 15). Then link the result in one walk into theinboxfolder, a sentinel doubly linked list. Equal times keep source order. - Handles. A dict from message id to node makes
delete,mark_readandmove(mid, folder)O(1). A move is a cut from one folder's list and a join onto the end of another's.arrive(mid, time)appends new mail. - Replies.
reply(parent, rid)appends to the child list of a message or of another reply, inO(1)with alast_childreference.thread(mid)flattens the replies for display as(depth, rid)pairs, each child list right after its parent, with an explicit stack and without relinking anything. - Recently opened.
open(mid)marks the message read and moves it to the new end of a panel. The panel is a map plus doubly linked LRU with a capacity. Deleting a message removes it from the panel. dump()prints one cycle-safe line per folder (unread marked*), andcheck()verifies every folder's links, sizes and owners, the handle map against the folders, and the panel.
Unknown ids raise KeyError.
- Build a 3-source inbox, run a short script, and print
dump(), the panel and one thread. - Write
InboxTruthon plain lists and dicts (sorted rows for the build,list.removefor moves, deletes and the panel). Fuzz on 300 seeded scripts of 30 operations (including empty inboxes and bad ids) and compare every return value, exception type, folder, read flag and panel after every step, withcheck()each time. Exceptions in the harness count as failures. Assert that the fuzz reached deletes of messages with replies, panel evictions, nested replies and moves. - Measure at
N = 10^5messages from 16 sources: the build, 500 opens with a full panel of 5,000, 300 deletes by id, and one full scan of the inbox. Opens and deletes change the structure, so each run starts from a fresh build and a pre-filled panel that are not timed. Print the times, the ratio truth / linked, and a verdict only where the ratio is at least 2x either way. - End with the table's lesson, worked out from the verdicts: where the linked structure paid off and where a list would do.
State time and space for every method.
Stuck? Solve it with a mentor.
Your first 1-on-1 session is free.