Data Structures & Algorithms practice
Data Structures & Algorithms ยท Linear Structures

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.

Q1Node And ReferenceEasyMust Do

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:

  1. Build three nodes by hand holding 10, 20, 30 and link them with a.next = b and b.next = c.
  2. Walk from a with while node is not None and print the values.
  3. Show that two names can hold the same node: alias = a.next, then print alias is b. Change b.val and print a.next.val to show the change comes through the other path.
  4. Show that a.next = b copied nothing: no node was created by the assignment.
  5. 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.
Q2Building, Walking And PrintingEasyMust Do

Write the three helpers every linked-list answer in this topic uses:

  1. from_list(values) builds a singly linked list from a Python list and returns the head (None if empty). Build from the back, so each new node points at the old head.
  2. to_list(head, limit=10**6) walks from the head and returns the values. It raises ValueError after limit nodes, as a guard against a cycle.
  3. show(head, limit=30) draws 1 -> 2 -> 3 -> None. If a node is met twice it ends with back to index i instead of looping forever, and past limit nodes 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.

Q3Length, Search And The k-th NodeEasy

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).

Q4Pushing To The Front, MeasuredEasy

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?

Q5A List Class With A TailMedium

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.

Q6Insert And Delete After A NodeEasyMust Do

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.

  1. Write insert_after(node, x, stats): new.next = node.next first, then node.next = new. Count assignments in stats["assign"].
  2. Write delete_after(node, stats): node.next = node.next.next, counted the same way. Return the removed value.
  3. Trace both with a show before and after on a 5-node list.
  4. Show the counts are the same at n = 10 and n = 10^5 (counts, not times), while finding the node to work on costs a walk.
  5. Show what happens if the two insert assignments are swapped.
  6. Add a comment on what happens to the unlinked node: C would call free(); CPython frees it when its last reference goes.
Q7Deleting By Value: The Head CaseEasy

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.

Q8The Dummy HeadEasyMust Do

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.

  1. Write remove_first(head, x), which removes the first node whose value equals x and returns the head, with a dummy head.
  2. Write remove_all(head, x) with a dummy head, which removes every node equal to x.
  3. Write the version without a dummy as well, and count the if statements in each version and say which special cases disappeared.
  4. Fuzz both against comprehension truths on 300 seeded lists, including empty, all equal to x, and x at the head and at the tail.

State in a docstring whether each function consumes its input.

Q9Inserting Into A Sorted ListEasy

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.

  1. Fuzz against bisect.insort on a Python list, 300 seeded cases, including the empty list and x smaller than, equal to and larger than everything.
  2. Count the hops to build a sorted list by n inserts of seeded random input (random.Random(12).sample(range(n), n)) at n = 1,000 and 2,000. Print the hops beside n^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.
Q10Singly Against DoublyEasy

A DNode adds a prev reference. Compare the two on the same operations and count reference assignments (an increment beside each one):

  1. 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.
  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.
  3. Memory: print sys.getsizeof of a Node and a DNode (CPython, slotted classes, Python 3.13).
  4. 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.

Q11A Doubly Linked List With SentinelsMediumMust Do

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:

  1. append(v) and appendleft(v), both returning the new node (a handle the caller can keep).
  2. pop() and popleft(), which raise IndexError when empty.
  3. remove_node(node), which removes any node given its handle and returns its value, in O(1).
  4. Iteration forwards (__iter__), reversed_values() for backwards, and len().
  5. check(), which walks forwards and backwards and asserts n.next.prev is n for 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.

Q12Deleting A Node You Only HoldMedium

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.

Q13Reversing A List, IterativelyEasyMust Do

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:

  1. Fuzz against a[::-1] on 300 seeded lists of length 0 to 15, including empty, one node and all-equal lists.
  2. Compare sets of ids before and after to prove no node was created and none was lost.
  3. Show that the old head becomes the tail (its next is None), 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.

Q14Reversing A List, RecursivelyMedium

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:

  1. Check it against the loop version on lists of length 0 to 800.
  2. At n = 2,000 the recursion raises RecursionError. Catch it and print only type(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.
  3. 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.

Q15Printing Backwards Three WaysEasy

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:

  1. backward_recursive(head, emit, stats): recurse to the end, emit on the way back.
  2. backward_stack(head, emit, stats): push the values onto a Python list used as a stack (DSA Topic 10), then pop.
  3. 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: record show(head) for that old head and show of the reversed head in snaps.

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.

Q16The Middle NodeEasyMust Do

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__).

Q17The n-th Node From The EndEasy

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.

Q18Floyd's Cycle Check On NodesEasy

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.

Q19A Circular ListEasy

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.

Q20Merging Two Sorted ListsEasyMust Do

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:

  1. Fuzz against sorted(a + b) on 300 seeded pairs of sorted lists, including empty and one-node lists.
  2. Compare sets of ids to prove no node was created, none was lost.
  3. Check stability with (key, label) records, comparing with sorted(..., key=...) on the left list followed by the right.
  4. Assert the comparison count is at most m + n - 1.
  5. 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).

Q21Removing Duplicates From A Sorted ListEasy

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.

  1. 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.
  2. 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.
  3. Fuzz both against comprehensions on 300 seeded sorted lists, including empty, one node, all equal and no duplicates.

State time and space.

Q22Comparing And Copying ListsEasy

Two linked lists are equal when their values match in order, so equality is a walk.

  1. Write same_values(a, b) that walks both lists at once (O(n)).
  2. Show that == on two plain nodes holding the same value is False: a class with no __eq__ compares identity.
  3. Write copy_list(head) that builds new nodes behind a dummy head with a tail reference.
  4. 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.
  5. Fuzz copy_list on 300 seeded lists: equal values, no shared nodes (compare sets of ids while both lists are alive), and changing the copy leaves the original alone.
Q23Why Linked Lists ExistEasy

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.

  1. 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 of Node(v, head).
  2. 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.
  3. Build the same sequence as a Python list, call .index("held") before and after insert(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.
  4. 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.
Q24Joining And Cutting In O(1)Medium

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.

  1. Write move_piece(p, h, q, r): the piece h..q sits right after p; cut it and paste it after r. Write move_back(p, h, q, r) for the reverse. Check both against a list model on 12 nodes.
  2. 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.
  3. Show that joined lists share nodes from then on: a change made through one shows in the other.
Q25Which List WhenMedium

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.

Q26Removing The n-th Node From The EndMediumMust Do

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):

  1. Put a dummy head in front of the list, so removing the real head needs no special case.
  2. Move lead forward n + 1 steps from the dummy. If lead is already None before a step, n is larger than the length: raise ValueError. n < 1 is a ValueError too.
  3. Start follow at the dummy and move both until lead runs off the end. follow now stands just before the target.
  4. 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.

Q27Partitioning Around A ValueMedium

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.

  1. Show the classic bug of forgetting to set the second group's last next to None: when the list's last node goes to the less-than-x group, the last node of the other group still points at a later node, and the result has a cycle. Print what show draws, and show that the wrong version is harmless when the last node is >= x.
  2. Fuzz the correct version on 300 seeded lists against two comprehensions, including empty, one node, all less than x, none less than x and a list where x equals every value.
  3. Check with sets of ids that no node was created. State time and space.
Q28Odd Positions, Then EvenEasy

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.

  1. 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).
  2. 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.

Q29Swapping PairsMedium

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.

Q30Rotating A ListMedium

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):

  1. Walk once to find the length L and the tail. If L is 0, return None.
  2. Use k % L. If that is 0, return the list untouched.
  3. Walk to the node at index L - k - 1, the new last node. Its next is the new head.
  4. 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.

Q31Removing Duplicates From An Unsorted ListEasy

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.

  1. dedup_seen(head): walk once with a set of values already met (DSA Topic 7) and unlink every node whose value is in it. State the time and space.
  2. 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 in stats["comparisons"].
  3. Run the in-place version on lists of distinct values at n = 500, 1,000 and 2,000, and assert the count is exactly n(n - 1) / 2. Then run both on n = 2,000 values 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.
  4. Show the one thing the in-place version can do and the set version cannot: values that are unhashable (lists) raise TypeError in a set, but == works.
  5. 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.
Q32Reversing A SublistMedium

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:

  1. Trace [1, 2, 3, 4, 5, 6] with left = 2, right = 5.
  2. Show why left = 1 needs the dummy head: print the result for left = 1 with the dummy, and for a copy of the function that returns the old head instead of dummy.next.
  3. 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.
Q33Reversing In Groups Of kHard

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.

  1. reverse_k_group(head, k): a loop. For each group, first look ahead k nodes (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.
  2. 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 for n nodes.
  3. At n = 2,000 run the recursive version with k = 1 and with k = 8. Catch RecursionError and print only the type name. Print the frames each needs (about n / k) next to the recursion limit, and say what that tells you.
  4. Fuzz both against a slicing oracle for k = 1 to 6 and n = 0 to 13, and print a short trace of the example above.
Q34Finding Where The Cycle StartsMediumMust Do

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.

  1. find_meeting(head): move slow by one node and fast by two; return the node where they meet, or None if fast reaches the end.
  2. 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.
  3. 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) and remove_cycle(head) (the new part here), which sets next to None on the node before the start, so the list becomes an ordinary list with all its nodes.
  4. Check everything with make_cycle for every pos from -1 to n - 1 and every n from 0 to 12, against cycle_truth: a walk with a dict from id to index that stops at the first repeated node.
  5. 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.

Q35Where Two Lists MeetMedium

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.

  1. meet_seen(a, b): put the ids of every node of a in a set, then walk b until a node is in it. State the space.
  2. 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.
  3. 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 walk m + n nodes in total and arrive together at the shared node, or together at None. Count the loop steps in stats["steps"] and show it never exceeds m + n + 1.
  4. Print a pair of lists with equal values that share nothing, and show that every finder returns None.
  5. 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..2 so equal values appear everywhere), including a shared part of length 0 and a shared first node.
Q36Palindrome With Extra SpaceEasy

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.

  1. is_pal_copy(head): copy the values into a Python list, then compare vals[i] with vals[n - 1 - i] by index (no reversed copy). State the space.
  2. is_pal_stack(head): with fast and slow pointers, push the first half of the values onto a list used as a stack (DSA Topic 10) while slow walks to the middle, skip the middle node when the length is odd, then pop while walking the second half. About n / 2 space.
  3. 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.
  4. Measure the peak memory of each with tracemalloc at n = 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.
Q37Palindrome In O(1) SpaceMediumMust Do

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):

  1. Find the middle with fast and slow (for an even length slow stops on the second middle; for an odd length on the middle node).
  2. Reverse the list from slow to the end in place. Do not cut the first half off: its last node still points at slow.
  3. Compare the first half with the reversed second half, walking while the reversed part has nodes.
  4. Reverse the second half again, in a finally block, 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:

  1. 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.
  2. Show what happens if step 4 is forgotten.
  3. 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.

Q38Reordering A ListMedium

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.

  1. reorder(head, cut=True): find the middle with fast and slow (the first half gets the extra node when the length is odd), cut the list after slow, reverse the second half, then interleave the two halves.
  2. With cut=False the function skips the cut. Run it on 5 nodes and print show() of the result: the first half's last node still points into the second half, and the result has a cycle.
  3. Write reorder_truth(a) on a Python list with two indexes, one from each end, and fuzz reorder against it for lengths 0 to 14 and 300 more seeded lengths up to 40.
Q39Adding Two NumbersMedium

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.

  1. add_lists(a, b): walk both lists together with a carry and a dummy head. Handle lists of different lengths and a final carry (99 + 1 = 100 needs a node that neither input had). An empty list means "no digits", and two empty lists give an empty list. Print the 99 + 1 result as one line.
  2. Check the "returns a new list" contract: assert that the result shares no node with either input (the two id sets are disjoint).
  3. Write to_digits(n) and from_digits(head) to convert, and check add_lists against Python's int on 500 seeded pairs of up to 30 digits, including 0 + 0 and all-nines cases, and check both inputs are unchanged afterwards.
  4. In a comment and in the output, say why this exists as a puzzle: Python's int never 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).

Q40Merge Sort On A Linked ListMediumMust Do

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.

  1. 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 in stats["comparisons"].
  2. merge_sort(head, key, stats, depth=0, trace=None): return the head of the sorted list. Split at the middle with fast starting at head.next (so two nodes split into one and one), cut the list, sort each half recursively, then merge. Record the deepest depth in stats. When trace is a list, append a cut line and a merge line for each call that splits, indented by depth.
  3. 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.
  4. Count the .next hops made by the fast/slow split at every level (stats["hops"]), for n = 2^4 up to 2^14 on shuffled input, and print the total beside n * log2(n); assert it stays within 2 * 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's mid = (lo + hi) // 2 costs 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 is log2(n) deep, so it is safe at 16,384 nodes, and only the merge would have been dangerous as a recursion.
  5. Check stability with (key, label) records against sorted(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).

Q41Insertion Sort On A Linked ListMedium

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:

  1. Fuzz it against sorted() on 300 seeded lists (size 0 included), and check stability with (key, label) records whose < looks at the key only.
  2. 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.
  3. 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.

Q42Merging k Sorted Lists, Two WaysMedium

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:

  1. 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.
  2. Count comparisons for k = 2, 4, 8, 16, 32, 64 with N = 2,048, and print a table with k * N beside it.
  3. Assert that both stay at or under k * N and say what the table shows.

State time and space.

Q43Flattening A Multilevel ListHardMust Do

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:

  1. 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's next, make the child list the parent's next, clear the child, and carry on. O(1) extra space. stats["visits"] counts every node step of both walks.
  2. flatten_stack(head): an explicit stack of "the rest" pointers (DSA Topic 10).
  3. 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.

Q44Copying A List With Random PointersMedium

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:

  1. Show the shallow mistake (copy.random = orig.random) and print that its copy points into the original.
  2. Fuzz the real version on 200 seeded lists (size 0 included): the copy's ids are disjoint from the original's, random_targets of both agree, and changing the copy leaves the original unchanged.

State time and space.

Q45An LRU Cache From A Map And A Doubly Linked ListMediumMust Do

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) raises ValueError if capacity < 1.
  • get(key) returns the value or -1, and a hit becomes the most recent.
  • put(key, value) updates in place or inserts, and evicts front.next when a new key finds the cache full.
  • keys() lists keys from least to most recently used, and check() walks forward and backward asserting n.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:

  1. Count reference writes per operation at capacity 10 and 1,000 and assert that the maximum is the same constant.
  2. Fuzz against an OrderedDict reference on 300 seeded sequences, comparing results and key order after every step, calling check() each time, and asserting that evictions really happened.

Explain why each part is needed, and state the costs.

Q46Inserting Into A Sorted Circular ListMedium

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:

  1. x fits between two neighbours: prev.val <= x <= cur.val.
  2. x is a new largest or smallest: it goes at the wrap point, where the values drop from the maximum to the minimum.
  3. 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.

Q47The Josephus CircleHard

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:

  1. Assert that josephus_linked(n, k) equals J + 1 for every n up to 300 and k up to 8, where J comes from DSA Topic 11's O(n) recurrence (J = 0, then J = (J + k) % m for m from 2 to n), and that its order matches the list-based removal order for n up to 40.
  2. For k = 2 assert the closed form: with n = 2^m + L the survivor is 2L + 1.
  3. 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.

Q48Sorting By Relinking, Not By ValuesHard

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 stable sort, 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:

  1. Fuzz all three against sorted() on 300 seeded lists (size 0 included) and assert that the node sorts are stable.
  2. 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.
  3. 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.

Q49Splitting A ListEasy

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):

  1. 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 (start fast at head.next, so slow stops on the first middle) and cut the front's last next.
  2. split_parts(head, k) returns a list of exactly k heads whose lengths differ by at most one, the first parts larger; when k > n the missing parts are None. It raises ValueError for k < 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.

Q50From Statement To PointersHard

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.

  1. delete_middle(head): remove the node at index n // 2.
  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); ValueError if k is out of range.
  3. insert_gcds(head): insert between every adjacent pair a node holding math.gcd of the two.
  4. double_number(head): the list holds the digits of a number, most significant first; return the list for twice the number.
  5. merge_between_zeros(head): the list starts and ends with 0, with no two zeros adjacent; replace each stretch between zeros by one node holding its sum.

State the time and space of each.

Q51Merge Sort Without RecursionHardMust Do

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):

  1. split(head, k): cut the list after its first k nodes and return the head of the rest (None if there is no rest). It changes the list it is given.
  2. merge(a, b, key, stats): the dummy-head merge, a loop, counting each comparison in stats["comparisons"].
  3. 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 with split, merge them, and attach the result behind the previous merged run. When trace is a list, append show(...) of the whole list after each width.
  4. merge_sort_top_down(head, key, stats, depth=0): the recursive version, recording its deepest depth.

Then:

  1. Trace 8 nodes, one line per width.
  2. Count comparisons of both versions for n = 2^4 .. 2^12 (they must be equal: the same runs are merged) and for other n (print both; do not assume they match).
  3. Fuzz stability and node reuse with (key, label) records on 400 seeded lists of 0 to 40 items, against sorted(key=...), comparing sets of ids before and after.
  4. Time both at n = 10^4 and 10^5 with best_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.

Q52Merging k Lists By HalvesMediumMust Do

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:

  1. merge_sequential(heads, stats): the fold.
  2. 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.
  3. merge_halves(heads, lo, hi, stats, depth=0): the recursive version on heads[lo:hi] (index range, no slicing), recording its deepest depth.

Then:

  1. Fuzz all three against sorted of all values on 300 seeded cases with k = 0 .. 9 lists 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.
  2. Count comparisons for N = 4,096 nodes split evenly into k = 2, 4, ..., 256 sorted lists. Print the fold, the halves, N * log2(k) and N * (k + 1) / 2, and the ratio fold/halves. Assert the bounds you claim.

State time and space (frames included).

Q53Copying With Random Pointers In O(1) Extra SpaceHardMust Do

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):

  1. Walk the list and insert a copy after every original: A, A', B, B', C, C'.
  2. Walk again and set each copy's random to original.random.next, which is the copy of the original's target (careful: random may be None).
  3. Walk once more and unweave: restore each original's next and 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):

  1. Fuzz 300 seeded cases of 0 to 12 nodes, with random being None, a different node or the node itself. Check: random_targets of 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.
  2. Show what happens if the unweave step forgets to restore the originals' next.
  3. Measure the peak extra memory with tracemalloc for both copies at n = 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.

Q54Array Against Linked List, MeasuredMediumMust Do

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):

  1. A full walk that sums the values of n = 200,000 items: a while loop over nodes, a for loop over a Python list, and sum() on the list.
  2. 200 random get(i) at n = 100,000: walk i nodes, against a[i].
  3. 1,000 inserts at a node you already hold (the middle one) against 1,000 list.insert at the middle index, at n = 10^4 and 10^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 at n = 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 first n where the list/linked ratio is 2x or more as the break-even.
  4. Walk to the middle, then insert (20 times), against list.insert at the middle, at n = 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.

Q55Memory Per NodeMedium

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:

  1. A Python list ([value] * n).
  2. A singly linked chain of slotted Node (val, next), the class used throughout this topic.
  3. The same chain of a plain class PlainNode with no __slots__.
  4. A doubly linked chain of slotted DNode (val, prev, next).
  5. A dict from the integers 0 .. n - 1 to slotted Entry(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.

Q56What OrderedDict Was DoingHard

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.

  1. Fuzz against OrderedDict on 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 call check(). Count how many KeyErrors the fuzz hit for each operation, and assert each was reached.
  2. Measure time per operation at 100 and at 10,000 keys, for move_to_end and 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 on n.

State time and space.

Q57A Least-Frequently-Used CacheHard

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:

  1. Entry(key, val, count) is a node of a doubly linked list. One sentinel list (front, back, helpers _link_after and _unlink) holds all the entries with the same use count, oldest at the front. Call that class Level.
  2. LFUCache keeps map (key to entry), levels (use count to its Level) and min_count, the smallest count that exists. A touch moves an entry from the level c to the level c + 1 (and bumps min_count if it emptied the lowest level). An insert evicts levels[min_count]'s oldest entry when full, then adds the new entry at count 1.
  3. LFUCache(capacity, stats, reset_min=True) counts every link or unlink in stats["links"]. With reset_min=False it forgets to set min_count back to 1 on an insert, the classic trap.

Then:

  1. 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 in stats["scanned"].
  2. Fuzz the cache against the truth on 300 seeded sequences of 60 operations (capacity 0 to 5, 9 keys), comparing every get result and the sorted key set after every step, with a check() on the cache each time. Harness exceptions count as failures. Assert that evictions happened.
  3. 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.
  4. 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.

Q58Adding Numbers Stored Most Significant FirstMedium

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:

  1. 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 a try/finally. Extra space: none beyond the result.
  2. 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.
  3. 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 deepest depth. A loop version is versions 1 and 2.

Then:

  1. Fuzz all three against Python's int on 500 seeded pairs of numbers with up to 30 digits (include 0, 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.
  2. 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.
  3. Print the extra space each version used (stack entries, frames) for two 500-digit numbers.

State time and space for each.

Q59Lists That Share Their TailsMedium

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:

  1. push(version, song) returns (song, version), a tuple used as a node (None is the empty list). Tuples cannot be changed, which is exactly what makes sharing safe. Write to_list_t(version) to walk one.
  2. 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).
  3. A recap row at n = 1,000 only: add up sys.getsizeof of 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. (tracemalloc is 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.
  4. Show why mutable nodes break sharing: two Node chains 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).
  5. "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 beyond i is the same object (is), and count the new tuples. Then, on the 1,000-song version, for i = 10, 100, 999: the new tuples set_at creates (i + 1, found by walking the new chain until a node of the old chain, bytes by the distinct-id getsizeof sum) against the 1,000-item list that a copied version needs. Assert the tuple count is i + 1.

State time and space.

Q60An Unrolled Linked ListHard

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:

  1. Blocks are Block(items, next). No block is ever empty and none holds more than B items.
  2. get(i) and pop(i) take 0 <= i < len; insert(i, x) takes 0 <= i <= len. Anything else raises IndexError (negative indices are rejected too).
  3. insert puts 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 than B, splits it in two halves.
  4. pop removes from one block; an emptied block is unlinked; and if the block and its next neighbour together hold at most max(2, B // 2) items, they are merged into one.
  5. check() asserts rule 1 and that the sizes add up.

Then:

  1. Fuzz it against a Python list on 300 seeded sequences of 60 operations for B in 2, 3, 4, 5 and 8 (small B makes splits and merges frequent), with check() after every step. Count the splits and merges and assert both happened.
  2. Measure at n = 100,000: 300 random-position inserts, then 300 random-position gets, for B = 16, 64, 256, 1024, 4096, against a Python list and 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.

Q61An Array-Backed Linked ListHard

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.

  1. ArrayLinkedList keeps two parallel lists, vals and nxt, with -1 playing the part of None. Fields: head, free and size.
  2. Unused slots are chained through nxt into a free list: _alloc pops the first free slot (or appends a new one when there is none), _release pushes a slot back. The free list is a linked stack (DSA Topic 10).
  3. API: push_front(x), insert_after(i, x), delete_after(i) and pop_front(). Each insert returns the slot index, which acts as a handle. Insert and delete at a held index are O(1).
  4. check() walks the list and the free list and asserts that together they cover every slot exactly once.
  5. 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).
  6. Measure at n = 10^5 items that all share one value object: bytes per item with tracemalloc and build time with best_of, against a chain of slotted Node objects. The hypothesis is that the array version uses fewer bytes. Print the numbers and write the conclusion from them.
Q62A Move-To-Front ListMedium

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.

  1. Write find(head, key, policy) for the policies "fixed", "mtf" and "transpose". It returns (head, steps, found), where steps counts the nodes visited.
  2. Fuzz all three policies against a Python list model on lists of 0 to 8 keys, about 400 searches per policy, hits and misses.
  3. Build a list of n = 500 distinct 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.
  4. Say what the result means for an LRU cache (DSA Topic 7): move-to-front is the recency order without the map.
Q63Next Greater Node, Then Removing Smaller OnesHard
  1. next_greater(head): for every node, the first larger value further along the list, or 0 if there is none. Use one walk and DSA Topic 10's monotonic stack of (index, value) pairs. Compare with an O(n^2) brute force.
  2. 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).
  3. remove_smaller_reverse(head): the same result in O(1) extra space: reverse the list, keep a running maximum while walking, delete what falls below it, reverse back.
  4. 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.
Q64Quicksort On A Linked ListHard

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.

  1. partition3, a loop that relinks every node into one of three dummy-headed lists, counting one comparison per node.
  2. quicksort (recursive, returns (head, tail)) and quicksort_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).
  3. Merge sort (top-down, the merge is a loop) for comparison.
  4. 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.
  5. At n = 2,000 sorted: catch the RecursionError from the recursive first-pivot version (print only its type name) and sort the same input with the loop version.
  6. Fuzz both versions and both policies for stability and node reuse on 300 seeded lists of (key, label) records, starting at size 0.
Q65A Sorted List With A FingerHard

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.

  1. FingerList: a doubly linked list with the sentinels front and back, the helpers _link_after and _unlink, a check() that verifies n.next.prev is n for every node, and insert(x, use_finger=True). A new value goes after the last value that is <= it. steps counts the nodes stepped over.
  2. Fuzz against sorted() on 400 seeded streams, starting at size 0, with equal values, in both modes.
  3. Counted work at n = 1,000: total steps from the finger and from the head, for streams where every value is within d places of its sorted position (d = 0, 5, 20) and for a fully shuffled stream.
  4. Measure at n = 10^5, d = 10: the finger list against bisect.insort on a Python list (build included for both). Which wins is the measurement: print both and write the verdict from the ratio.
Q66Reversing And Sorting A Doubly Linked ListMedium

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).

  1. reverse_d(head, tail): swap prev and next in 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 fail check_links with a message you print.
  2. sort_d(head, key): sort using only the next pointers (the merge sort on nodes from earlier in this topic, with a loop for the merge), then rebuild every prev in one extra walk. Return (head, tail). A wrong version that skips the rebuild must fail check_links too.
  3. Fuzz both on 300 seeded lists of (key, label) records, sizes 0 to 25: values reversed, links intact, sort stable and equal to sorted(key=...), and the same nodes (compare sets of ids).
Q67Three Ways To Find A CycleMedium

Three ways to ask "does this list have a cycle?":

  1. A seen-set of node ids: O(n) extra space.
  2. 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.
  3. 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:

  1. 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.
  2. Measure with tracemalloc the peak extra bytes each method needs on an acyclic list of 10^5 nodes, and the bytes per node with and without the flag field.
  3. 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 Node has no flag field).
  4. 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.
Q68The Largest Twin SumMedium

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).

  1. twin_sum_list(head): copy the values to a Python list and use indices. O(n) space.
  2. 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 folding pair_value(a, b) with better, then restore the list. An odd length raises ValueError before anything is changed; an empty list returns None.
  3. The largest twin sum is twin_fold with max; the palindrome check from earlier in this topic is the same walk with a different rule. Write both.
  4. 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.
  5. Measure the peak bytes of both versions at n = 10^5 with tracemalloc.
Q69Removing Zero-Sum RunsHard

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.

  1. 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 is 0. 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.
  2. 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.
  3. 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.
  4. Search all lists of length up to 6 over -2..2 for 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.
Q70When Not To Use A Linked ListMediumMust Do

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.

  1. Reverse a sequence (linked reversal against slicing), n = 10^5.
  2. Merge two sorted sequences (the dummy-head merge against sorted(a + b)), 5 * 10^4 each.
  3. A FIFO buffer (a linked queue with a tail against collections.deque), 10^5 enqueues then 10^5 dequeues.
  4. Remove the items that fail a test, multiples of 3 (a dummy-head filter against a comprehension), n = 10^5.
  5. Sort (linked merge sort against sorted), n = 5 * 10^4.
  6. An LRU cache of capacity 1,000 over 2 * 10^5 seeded operations (the hand-built map plus doubly linked list from earlier in this topic against OrderedDict; DSA Topic 7 owns the OrderedDict version).

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.

Q71Assignments In The Wrong OrderEasyMust Do

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) sets node.next = new and only then new.next = node.next, so the new node points to itself.
  • reverse_broken(head) flips cur.next = prev and then advances with cur = cur.next, following the link it has just flipped.
  • delete_after_broken(node) tidies the removed node first (victim.next = None, a C habit before free) and then relinks with node.next = victim.next, which is now None.
  1. Write all three broken functions and their fixes: insert_after, reverse and delete_after.
  2. Write an oracle for each on a plain Python list.
  3. 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.
  4. Check that each fix fails on no case.

State the rule that fixes all three in one sentence.

Q72The Head That Did Not ChangeMedium

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.

  1. For each of the three, call it, ignore the return value, and print show(h). Say what h now refers to: the tail of the reversed list, a list missing the new node, or a detached node.
  2. Write push_front_rebind(head, x), which assigns head = Node(x, head) inside the function and returns nothing, and show that the caller sees no change. Then write relabel_first(head, x), which sets head.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.
  3. Give two fixes. The first is to always assign the returned head. The second is a class LinkedList that owns self.head, with reverse(), push_front(x) and remove_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.

Q73The Tail That Went StaleHard

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": pop never updates tail.
  • "remove": remove(x) of the last node never updates tail.
  • "clear": clear() resets head and size but not tail.
  1. For each bug, fuzz seeded operation sequences against a Python list, with _check() after every operation, until one fails.
  2. 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.
  3. Replay that sequence without _check(), plus one append(9), and print the linked list beside the Python list: the 9 has vanished.
  4. 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.
Q74Recursion That Runs Out Of FramesHardMust Do

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 its next to 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.

  1. Run all three at 200, 400, 800 and 2,000 nodes, checking each result. For the merge, use two interleaved sorted lists of n / 2 nodes each, so the recursion goes the whole way down. Catch RecursionError and print only type(e).__name__, never the message or a depth.
  2. Write loop versions length_loop, reverse_loop and merge_loop, and check them on the same inputs.
  3. 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.
  4. Merge sort's split recursion is only log2(n) deep. Give merge_sort(head, merge, stats) the merge as a parameter, count the deepest split level in stats, 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.

Q75The Fast Pointer That Falls OffEasy

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:

  1. middle_swapped: while fast.next is not None and fast is not None. The order of the tests is wrong, so fast.next is read before fast is checked.
  2. delete_middle_bad: guards the empty list, then starts fast = head.next.next, which fails on a one-node list.
  3. middle_first_bad: the docstring promises the first middle for even lengths, but fast starts at head, which gives the second.
  4. has_cycle_bad: starts slow and fast at head and tests slow is fast before 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.

Q76The Walk That Never EndsMedium

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.

  1. Write length_unsafe(head, budget) and a generator iter_values(head, budget). Run length_unsafe, sum(iter_values(...)) and list(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.
  2. Run the kit's cycle-safe tools on the cyclic list: to_list with limit=100_000 (catch its ValueError and print its message), show, and Floyd's has_cycle. Print a table with one row per function, showing whether it is cycle-safe.
  3. 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. Write rotate_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 = None is missing). Search small inputs in order of size for the first one where the result has a cycle, and print it with show beside the true rotation.
  4. The fix is that rotation with new_last.next = None restored. Check it on every list of length 0 to 6 and every k from 0 to 2L + 1, running has_cycle on each result before reading it.
Q77The Node That Prints Itself To DeathHard

@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.

  1. Define DCNode as a plain @dataclass with fields val and next. Build chains of 150, 500 and 2,000 nodes and try repr(a), a == b (two separate chains with equal values) and copy.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 raise RecursionError?
  2. Build a two-node cycle and print its repr. Dataclasses guard repr against cycles, so it prints .... Then compare two separate but equal cycles with ==: there is no such guard there.
  3. Fix it. @dataclass(repr=False, eq=False) (or a plain class) keeps the default identity ==, and its default repr has a memory address in it, so do not print it. Use show() for printing. Write same_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). Write copy_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.

Q78Deleting By Copying The Next ValueMedium

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.
  1. Run put_new A to E, delete("C"), touch("D", 40), evict() three times, and keys() 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.
  2. Explain each wrong line, starting from this: after delete("C"), the handle for D refers to a detached node.
  3. 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 on Entry(key, val) nodes between two sentinels, front and back. Run the same script, check it against the truth, and fuzz it on 300 seeded operation sequences.
Q79The Doubly Linked Update Done HalfwayHard

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:

  1. "remove prev": remove_node fixes node.prev.next but not node.next.prev.
  2. "insert prev": insert_after forgets new.next.prev = new.
  3. "keep links": a removed node keeps its links, so removing it a second time "succeeds" again (and the size drops twice).
  4. "pop empty": popleft on an empty list skips the size check and unlinks a sentinel.
  5. "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.

Q80Identity Or EqualityMedium

Linked-list questions are usually about the same node (is), not an equal value (==). Here are three mistakes that compare the wrong thing:

  1. meet_by_value(a, b) finds where two lists meet with the length-offset method, but compares x.val == y.val instead of x is y. It reports the first position where the values happen to match.
  2. 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.)
  3. node in seen_nodes, where seen_nodes is 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.

Q81The Palindrome Check That Breaks The ListMedium

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.

  1. is_pal_no_restore(head): find the middle with fast and slow (for an even length slow stops on the second middle), reverse from slow in 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.
  2. is_pal_early_exit(head): restores the list after the comparison loop, but returns False from inside the loop at the first mismatch. Find, by enumerating every 0/1 list of length 0 to 8 with itertools.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.
  3. is_pal_restored(head): the restored check from earlier in this topic (the second reversal in try/finally), pasted in as the fix. Check on all those inputs that it answers like a == a[::-1], and that the caller's list has the same values and the same nodes in the same order afterwards.
  4. 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 at n = 1,001 and say what the stack version costs in extra space.

State time and space for each.

Q82Two Lists, One Set Of NodesMedium

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.

  1. merge(a, b): the dummy-head merge of two sorted lists, written to consume its inputs. After merged = merge(a, b) on 1 -> 3 -> 5 and 2 -> 4, print show(a), show(b) and show(merged). Count how many nodes a and b share with merged by comparing sets of id values (print the count, never an id).
  2. plus_last(head, x) claims in its docstring to return a new list with x added at the end, but it walks to the last node and links x there. Show that the caller's list grew, and that len of the "original" changed.
  3. with_front(head, x) returns Node(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.
  4. 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_copy builds a new chain. Check both with id sets: merge_copy result shares 0 nodes with the inputs, and plus_last_copy shares 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.

Q83The O(1) That Is NotHard

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.

  1. "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 at n = 1,000, 2,000 and 4,000. Compare it with delete_after(prev) when the node before the target is already held.
  2. "Appending is O(1)." Write append_walk(head, x, steps) (no tail reference) against append_tail(tail, x, steps), at the same three sizes.
  3. "len is O(1)." Write length(head, steps) that walks, and a loop while i < length(head, steps) that visits every index of a list, at n = 250, 500 and 1,000. Then fix it by asking for the length once.
  4. "Inserting in the middle beats list.insert." Write walk_then_insert(head, n, x, steps) (walk to the middle node, then link a new node after it) and run it at n = 1,000, 2,000 and 4,000. Then time it once at n = 100,000 (20 inserts, each one walking first) against 20 calls of list.insert at 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.

Q84Who Frees A NodeHard

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.

  1. A singly linked list: print traced memory after the build, then after del head. It should fall back to about where it began, with no gc.collect().
  2. 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.
  3. A doubly linked list built with prev and next: every pair of neighbours points at each other, which is a reference cycle. After del head, tail the memory stays; after gc.collect() it falls. Print whether gc.collect() found at least n unreachable objects, not the exact number.
  4. 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 next and show the memory falls. That is the fix for a removed node you still hold: clear its links.
  5. The build cost per node at n = 10^5 and n = 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.

Q85The Suite That Catches All Of ItHardMust Do

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).

  1. Write the helpers: a Report that records which checks failed, node_ids, has_cycle, and call(report, fn, *args) that runs a function and turns RecursionError into the recursion check and any other exception into crash.
  2. 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: _unlink forgets one prev), is_palindrome(head) (broken: leaves the second half reversed) and merge(a, b) (broken: takes from the right on ties; recursive).
  3. 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.
  4. 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 prev by links, the cycle by cycle, the unrestored list by restored, the right-on-ties merge by values alone, the recursive merge by recursion alone.

State time and space for the harness, and say which bugs only one check could catch.

Q86The Linked List LibraryMini-ProjectMust Do

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:

  1. Write both classes, with the shared behaviour (everything that is just a walk) written once in a base class on top of _walk() and node_at().
  2. Fuzz each class against a Python list on 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 reached IndexError, ValueError and an empty-list pop.
  3. Print a cost table from counted node visits at n = 1,000 and n = 2,000 for each method on each class, with the growth classified from the ratio (near 1: constant, near 2: linear). remove_node on a singly list cannot be constant (it needs the node before), and the table must show that.
  4. Name what replaces the library in real Python code.

State time and space per method in comments.

Q87The Text Editor BufferMini-ProjectMust Do

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 (front and back), plus a cursor kept as the node just left of the cursor (front means "at the start").
  • ListBuffer: a Python list of characters and a cursor index, editing with list.insert and del.
  • 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 one pop and one append.

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.

  1. Write the three classes, each with time and space comments per method.
  2. Fuzz all three against a plain str plus an index on 300 seeded edit scripts of 60 operations over short documents (0 to 6 characters at the start): compare text(), 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.
  3. Measure on a document of 2 * 10^5 characters 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 to text(). 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).
Q88The PlaylistMini-Project

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().

  1. Write the class. check() walks the circle both ways and asserts that it closes after exactly len(handles) steps and that handles and the circle hold the same nodes.
  2. Print a short session: add five songs, then show titles() after next, prev from the first song, move_up of the first song (the circle wraps, so it swaps with the last song), remove of the current song, and eight calls to song_ended() in each of the three modes starting from the same song (print the title playing after each call, or stop).
  3. 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 function fisher_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 of fisher_yates on three items each of the 6 orders appears between 800 and 1,200 times.
  4. 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 call check().

State time and space per method in comments.

Q89The Weighted Cache With ExpiryMini-Project

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 >= 1 bytes (else ValueError); clock is an injected object with an integer now, which the test advances (no wall time, Rule 8).
  • put(key, value, size, ttl=None): refuses with ValueError before touching anything if size < 1 or size > 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. expires is clock.now + ttl, or None for never.
  • get(key) returns the value or -1. An entry is expired when clock.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). With stop_at_live=True it 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, used is the bytes held, and check() walks both ways and asserts the dict, the list and used agree and used <= budget.
  1. Write the class and run a short story (budget 10) that prints keys(), used and the counters after an eviction, a refused entry and an expiry.
  2. Show when "sweep from the old end, stop at the first live entry" is right and when it is not: with one shared ttl and no get, expiry order equals list order; with mixed ttl values or after a get, the stop leaves expired entries behind. Print removed and examined for both sweeps in both situations.
  3. 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(), used and all four counters after each step, and calling check(). Assert the fuzz reached refusals, expiry at get, expiry in a sweep and an expired entry found at the old end during a put.

State time and space in comments.

Q90The Polynomial EngineMini-Project

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) and to_dict(p) between {exp: coef} and the list, and check_poly(p) asserting the two invariants.
  • add(p, q, cnt) and sub(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), then mul_one_at_a_time(p, q, cnt) (add the partial products to a running result) and mul_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 by pow(x, gap).
  • derivative(p) and to_text(p), which prints 3x^4 - 2x + 5, -x^2 + 1, x and 0 in those shapes.
  1. 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, evaluate at x in -2, 0, 1, 3, derivative, to_text and check_poly on every result. Harness exceptions count as failures; assert the fuzz hit an empty operand and a sum that cancelled a term to zero.
  2. 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 exponents 0..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 as O(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.

Q91The Linked Sorting BenchMini-Project

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 with split(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.
  1. Fuzz all five against sorted() on 300 seeded lists of sizes 0 to 30 (exceptions count as failures).
  2. Check stability with (key, label) records whose __lt__ compares keys only, on five input kinds at n = 2,000: random, sorted, reversed, few unique (4 keys) and all equal.
  3. Count comparisons and link writes on the five kinds: n = 2,000 for insertion sort and n = 10,000 for the rest. Print two tables. Then print, computed from the counts: insertion sort's cheap kinds against its random cost as a multiple of n^2; merge sort's comparisons against sorted()'s; quicksort against merge sort on random and on all-equal input.
  4. Time the four O(n log n) sorts on one random list of n = 50,000, each run rebuilding its list (the build is also timed alone and printed). Print each time as a multiple of the sorted() 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.

Q92The List VisualiserMini-Project

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 whose prev does 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's next and random as 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.

  1. Print one picture of each kind, including an empty list, a cycle, and a doubly linked list with one prev broken on purpose.
  2. Check: exact strings for two small lists; for every n from 0 to 11 and every cycle position (-1 to n - 1), the singly picture terminates with exactly n boxes; on 200 seeded multilevel specs the multilevel picture has one box per node.
  3. 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 names prev, cur and nxt are written under the boxes they reference.
  4. Draw Floyd's slow S and fast F stepping 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.

Q93The Train YardMini-Project

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): train b goes behind train a and the name b is retired: one join.
  • uncouple(name, car, new_name): car and 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 from first_car to last_car (in src's order) go to the end of dst.
  • turn(name): turn the train around in O(1) with a flipped flag. Every walk goes through one step(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.

  1. 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.
  2. Fuzz against a model that keeps each train as a Python list (turn is list.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.
  3. 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.

Q94The Order BookMini-Project

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).

  1. Trace four resting orders and one buy that sweeps two levels with a partial fill, then cancel an order twice.
  2. 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.
  3. 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.

Q95The Free-Space ManagerMini-Project

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 or None when nothing fits. n <= 0 raises ValueError.
  • 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 is O(1). It is DSA Topic 9's merging of touching intervals, done with two link checks. Freeing something that is not an allocated start raises ValueError.
  • free_blocks(), stats() (total free, largest block, block count) and check().
  1. Trace three allocations and three frees that leave a hole, merge on one side, then merge on both sides.
  2. 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.
  3. 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.

Q96Explaining It ColdInterview

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:

  1. A node and a reference: linking copies nothing.
  2. Singly against doubly: what it costs to unlink a node you hold.
  3. The dummy head: remove_all(head, x) with no head special case, shown on four inputs including the empty list.
  4. Iterative reversal.
  5. The fast and slow pair: the middle, and Floyd's cycle check (DSA Topic 4 proved why it works).
  6. Merging and merge sort: relinking, no new nodes (checked with id sets, never printed).
  7. The LRU cache from a dict and a doubly linked list, checked against OrderedDict (DSA Topic 7) on one short script.
  8. Why Python code rarely uses one: get(i) steps against a[i], and bytes per item from tracemalloc for 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.

Q97Diagnosing By ReasoningInterview

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.

  1. A merge of two sorted lists that forgets to hang the leftover run on the tail.
  2. A right rotation by k that never reduces k modulo the length L.
  3. A reversal in groups of k that also reverses the short last group.
  4. A multilevel flatten that splices each child list in but leaves the parent's child reference set.
  5. 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.

Q98Designing For OperationsInterview

The interviewer gives three APIs as complexity targets. Design each one, then fuzz it against a brute force.

  1. Front, middle and back. push_front, push_middle, push_back, pop_front, pop_middle and pop_back, all in O(1), with DSA Topic 11's definition: with m items, push_middle puts x at index m // 2 and pop_middle removes index (m - 1) // 2. Popping an empty queue raises IndexError. DSA Topic 11 kept two deques balanced. Here, use one sentinel doubly linked list and a reference mid to the node at index (m - 1) // 2, and work out for each operation whether mid moves one step forward, one step back, or stays. check() walks to index (m - 1) // 2 and asserts it is mid.
  2. A phone directory. get() hands out any available number or -1, check(n) and release(n), all O(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 raises ValueError. Several numbers can be right for get, so the fuzz checks properties: the number was free, and -1 comes back exactly when none is.
  3. The first unique number of a stream. add(x) and first_unique() (or -1), both O(1). DSA Topic 7 handled a character stream with an insertion-ordered dict plus a repeated set; its first() is O(1) only because at most 26 letters are live. For unbounded numbers, next(iter(d)) skips every deleted slot: time it after deleting n - 1 of n keys from the front, at n = 10^4 and 10^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.

Q99The Mock InterviewInterview

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:

  1. subtract(a, b) returning (sign, digits), where the result may be negative. Write compare(a, b) for magnitudes in one pass (careful: in a least-significant-first list, the deciding digit is the last difference seen) and strip for 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.
  2. times_digit(a, k) for one digit, then times(a, b) by schoolbook multiplication: one partial product per digit of b, shifted by pushing zeros onto the front, summed with add.
  3. Every function returns a new list and leaves its inputs unchanged. Check all of them against Python's int on 500 seeded pairs of up to 29 digits, including 0 and a == b, and check that no result has a leading zero.
  4. Why Python makes all of this unnecessary: int is unbounded. Print one line saying so; the 64-bit C long overflow was simulated in DSA Topics 4 and 6, so cite it rather than repeat it.

State time and space for every function.

Q100CapstoneInterviewMust Do

Build an inbox engine that uses every idea in this topic.

  • Timeline. Messages (id, time) come from k seeded 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 the inbox folder, a sentinel doubly linked list. Equal times keep source order.
  • Handles. A dict from message id to node makes delete, mark_read and move(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, in O(1) with a last_child reference. 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 *), and check() verifies every folder's links, sizes and owners, the handle map against the folders, and the panel.

Unknown ids raise KeyError.

  1. Build a 3-source inbox, run a short script, and print dump(), the panel and one thread.
  2. Write InboxTruth on plain lists and dicts (sorted rows for the build, list.remove for 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, with check() 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.
  3. Measure at N = 10^5 messages 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.
  4. 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.

Book my free session