Lesson 11 of 40Core patterns
Linked List Techniques
Find a cycle's entry, split at the right middle, reverse in groups, copy random pointers and sort a list, with the pointer bookkeeping that keeps each one correct.
In Linked Lists you learnt the four basic moves: the dummy head, prev/cur/nxt reversal, fast and slow pointers, and merging two sorted lists. Interview problems at the medium and hard level are almost always two or three of those moves glued together, and the bugs live in the glue: a pointer that is one node off, a half that was never detached, a group whose tail points at the wrong place. This lesson takes the problems that come up most (cycle entry, reorder, k-group reversal, random-pointer copy, merge k lists, sort list) and shows the exact bookkeeping that makes each one correct. The same habits matter at work whenever you edit a structure in place, from an LRU cache to an undo history.
Where does the cycle start?
Floyd's algorithm tells you a cycle exists when slow and fast meet. The follow-up interviewers ask next is "return the node where the cycle begins", in O(1) space. The trick is short: after the meeting, put one pointer back at the head, move both one step at a time, and they meet at the entry. Knowing why is what separates a memorised answer from an understood one.
Name the distances. Let a be the number of steps from the head to the cycle entry, c the length of the cycle, and b the number of steps from the entry to the meeting point. When they meet, slow has walked a + b. fast has walked twice as far, 2(a + b), and the only way to be ahead of slow on the same node is to have gone round the cycle some whole number of extra times, k:
2(a + b) = a + b + k·c, soa + b = k·c, soa = k·c - b.
Read the last line as a walk. k·c - b steps from the meeting point is the same as going back b steps (to the entry) and then going round the cycle k full times. So a pointer that starts at the meeting point and walks a steps lands on the entry. A pointer that starts at the head and walks a steps also lands on the entry. Start one at each and they meet exactly there.
Both start at the head. Here a = 2 (head to entry 3) and the cycle 3, 4, 5, 6 has length c = 4.
Find the Duplicate Number is the same algorithm in disguise. You get n + 1 integers, each in 1..n, and must find the repeated one without changing the array and in O(1) space. Treat each index i as a node whose next is nums[i]. Index 0 is never pointed at (no value is 0), so it is a head outside any cycle. Two indices hold the duplicate value, so two arrows point at the same node: that node is the cycle entry, and its index is the duplicate.
Press Run (⌘ Enter) to see what happens.slow and fast meet inside the cycle, why must phase 2 move both pointers one step at a time?Which middle, and why it matters
Linked Lists showed the standard loop, which stops slow on the second middle of an even-length list. Many problems need the first middle instead, because they split the list into two halves:
def first_middle(head): # head must not be None
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow # 1-2-3-4 gives 2; 1-2-3-4-5 gives 3The difference is fatal in merge sort. If you split 1 → 2 at the second middle, the left half is 1 → 2 and the right half is empty, so the recursion calls itself on the same two nodes forever. Splitting after the first middle always makes both halves non-empty for any list of length 2 or more. The rule of thumb: to split, stop at the first middle and cut after it (second = mid.next; mid.next = None).
Remove the nth node from the end
To remove the nth node from the end in one pass, keep a fixed gap between two pointers. Start both at a dummy node, move lead forward n + 1 steps, then move both until lead falls off the end. trail now sits on the node before the one to delete, which is exactly where you need to be to unlink it. The dummy handles the case where the node to delete is the head itself (n equals the length).
What does this print?
def first_middle(head):
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
class N:
def __init__(self, v, nxt=None):
self.val, self.next = v, nxt
h = N(10, N(20, N(30, N(40, N(50, N(60))))))
print(first_middle(h).val)Reorder and palindrome: three moves in a row
Reorder List turns L0 → L1 → ... → Ln into L0 → Ln → L1 → Ln-1 → ... in place. It is the cleanest example of combining moves: find the first middle, cut and reverse the second half, then weave the two halves together, taking one node from each in turn.
Palindrome Linked List in O(1) space uses the first two moves: find the middle, reverse the second half, then walk both halves comparing values. The part most candidates skip is restoring the list. A function called is_palindrome that leaves its input half-reversed is a bug in production code, because the caller still owns that list. Reverse the second half back and reattach it before returning. Saying this out loud is an easy signal of seniority.
Press Run (⌘ Enter) to see what happens.The one-line reverse uses a tuple assignment: Python evaluates the whole right side (prev, head, head.next) before assigning anything, so nothing is lost. It is compact, but in an interview the four-line version from Linked Lists is easier to explain and harder to get wrong.
Reversing a sublist and k-groups
Reverse Between reverses positions left..right and leaves the rest alone. Reverse Nodes in k-Group reverses every block of k nodes and leaves a short final block as it is. Both need the same four pointers, and naming them well is half the job:
group_prev: the node just before the block (the dummy for the first block). Itsnextmust end up pointing at the block's new first node.kth: the last node of the block. After reversal it becomes the first.group_next: the node just after the block. The block's old first node must end up pointing here.- The old first node: after reversal it is the block's tail, so it becomes the next
group_prev.
A neat detail: start the reversal with prev = group_next instead of None. Then the old first node is linked to the rest of the list automatically, and only group_prev.next needs fixing afterwards.
Walk k steps from group_prev (the dummy) to find kth = 3. If you fall off the end first, stop: the last block is too short.
Press Run (⌘ Enter) to see what happens.Put one round of the k-group loop in order.
- Tap the steps below in the right order.
Copy a list with random pointers
Each node has next and also random, which can point anywhere in the list or at None. You must build a deep copy where the new nodes' random pointers point at new nodes, never old ones.
The straightforward answer is a hash map from old node to new node: one pass creates every copy, a second pass sets copy.next = old_to_new[old.next] and copy.random = old_to_new[old.random]. That is O(n) time and O(n) extra space, it is easy to get right, and it is what you would write at work.
The follow-up asks for O(1) extra space (not counting the output). Interleave the copies into the original list so that each old node's next is its own copy: A → A' → B → B' → .... Now the copy of old.random is simply old.random.next, so no map is needed. A third pass separates the two lists and restores the original. Forgetting to restore it is the usual failure, and it fails silently because the copy looks right.
Press Run (⌘ Enter) to see what happens.Add Two Numbers, Merge k Lists and Sort List
Add Two Numbers stores digits in reverse order, so you add from the head like column addition. Two details matter: lists can be different lengths, and a final carry adds a node (5 + 5 becomes 0 → 1). The loop condition while a or b or carry covers both at once, and treating a missing node as 0 removes the special cases.
Merge k Sorted Lists has three answers, and interviewers like you to compare them. Let N be the total number of nodes:
| Approach | Time | Extra space |
|---|---|---|
| Merge list 1 with 2, then the result with 3, and so on | O(N·k) | O(1) |
| Min-heap of the current front of each list | O(N log k) | O(k) |
| Divide and conquer: merge in pairs, then pairs of pairs | O(N log k) | O(1) iterative |
The sequential version is slow because the early nodes are re-walked in every merge. Both fast versions do O(N) work per "level" across log k levels. In Python, the heap version needs a tie-breaker: if two fronts have the same value, heapq compares the next tuple item, and ListNode objects have no <, so it raises TypeError. Put a unique counter or the list index in the middle of the tuple.
What does this print?
import heapq
class ListNode:
def __init__(self, val):
self.val = val
heap = []
try:
heapq.heappush(heap, (1, ListNode(1)))
heapq.heappush(heap, (1, ListNode(1)))
print("ok", len(heap))
except TypeError:
print("TypeError")Sort List asks for O(n log n) time on a linked list. Merge sort is the natural fit: lists cannot be indexed, so quicksort and heapsort lose their advantages, but merging two sorted lists is O(1) extra space (you only relink). The top-down version (first middle, cut, sort each half, merge) is short, but its recursion is log n deep, so it uses O(log n) stack space. The bottom-up version merges runs of size 1, then 2, then 4, using a loop and a few pointers, so it is O(1) extra space. If the interviewer says "constant space", they mean bottom-up.
Press Run (⌘ Enter) to see what happens.How to approach a new list problem
Before you write code, draw five boxes and arrows and decide three things out loud. First, can the head change? If yes, use a dummy. Second, which existing move does each phase use? Most hard list problems are a pipeline: find (fast/slow or a gap), cut, reverse, merge or weave. Third, what do you need to save before you overwrite a pointer? Write those saves first in each loop.
Then test four lists by hand: empty, one node, two nodes, and an odd length of at least five. Two-node lists catch most middle and split bugs, and odd lengths catch most weave bugs. At work, the same habit applies to any in-place edit of linked data, such as moving an entry to the front of an LRU list: save, relink, then check the neighbours on both sides.
Match each problem to the combination of moves it needs.
- cycle entry
- The first node of a cycle reached from the head. Found in O(1) space by restarting one pointer at the head after Floyd's meeting.
- first middle
- For even lengths, the earlier of the two middles. Stop there to split a list into two non-empty halves.
- detach
- Setting
mid.next = Noneafter a split so the two halves no longer share nodes. - group_prev
- In k-group reversal, the node before the current block. Its
nextis set to the block's new first node. - interleaving
- Placing each copy right after its original (A, A', B, B') so a copy can be found without a hash map.
- bottom-up merge sort
- Merging runs of size 1, 2, 4 and so on in a loop. Sorts a linked list in O(n log n) time and O(1) extra space.