Skip to content

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.

20 min read0/6 questions

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, so a + b = k·c, so a = 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.

Floyd on 1 → 2 → 3 → 4 → 5 → 6 → back to 3
1slow fast23456

currentwaitingdone

Both start at the head. Here a = 2 (head to entry 3) and the cycle 3, 4, 5, 6 has length c = 4.

1/8

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.

Python
class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def cycle_entry(head): slow = fast = head while fast and fast.next: slow, fast = slow.next, fast.next.next if slow is fast: break else: # loop ended without break: fast fell off the end return None p = head while p is not slow: # phase 2: both move one step p, slow = p.next, slow.next return p def find_duplicate(nums): slow = fast = 0 # index 0 is the head while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break p = 0 while p != slow: p, slow = nums[p], nums[slow] return p # 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> back to 3nodes = [ListNode(v) for v in range(1, 7)]for x, y in zip(nodes, nodes[1:]): x.next = ynodes[-1].next = nodes[2]assert cycle_entry(nodes[0]) is nodes[2]assert cycle_entry(ListNode(1, ListNode(2))) is Noneassert cycle_entry(None) is Nonesolo = ListNode(7); solo.next = soloassert cycle_entry(solo) is solo assert find_duplicate([1, 3, 4, 2, 2]) == 2assert find_duplicate([3, 1, 3, 4, 2]) == 3assert find_duplicate([2, 2, 2, 2, 2]) == 2print("cycle entry:", cycle_entry(nodes[0]).val)print("duplicate:", find_duplicate([3, 1, 3, 4, 2]))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
After slow and fast meet inside the cycle, why must phase 2 move both pointers one step at a time?
Need a nudge? A hint rules out a wrong answer.

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 3

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

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Python
class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def build(vals): dummy = tail = ListNode() for v in vals: tail.next = ListNode(v) tail = tail.next return dummy.next def to_list(node): out = [] while node: out.append(node.val) node = node.next return out def reverse(head): prev = None while head: head.next, prev, head = prev, head, head.next return prev def first_middle(head): slow = fast = head while fast.next and fast.next.next: slow, fast = slow.next, fast.next.next return slow def reorder(head): if not head or not head.next: return mid = first_middle(head) second = reverse(mid.next) mid.next = None # detach, or the weave loops forever first = head while second: a_next, b_next = first.next, second.next first.next = second second.next = a_next first, second = a_next, b_next def is_palindrome(head): if not head or not head.next: return True mid = first_middle(head) second = reverse(mid.next) a, b, ok = head, second, True while b: # second half is never longer if a.val != b.val: ok = False break a, b = a.next, b.next mid.next = reverse(second) # put the list back return ok for vals, want in [([1, 2, 3, 4], [1, 4, 2, 3]), ([1, 2, 3, 4, 5], [1, 5, 2, 4, 3]), ([1], [1]), ([1, 2], [1, 2])]: h = build(vals) reorder(h) assert to_list(h) == want, (vals, to_list(h)) for vals, want in [([1, 2, 2, 1], True), ([1, 2, 3, 2, 1], True), ([1, 2], False), ([], True), ([7], True)]: h = build(vals) assert is_palindrome(h) == want assert to_list(h) == vals # input is unchangedprint("reorder [1..5]:", end=" ")h = build([1, 2, 3, 4, 5]); reorder(h); print(to_list(h))
Output
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). Its next must 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.

Reverse in groups of k = 3 on 1..7
1
0
2
1
3
2
↑kth
4
3
↑group_next
5
4
6
5
7
6
group_prev = dummy

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.

1/5
Python
class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def build(vals): dummy = tail = ListNode() for v in vals: tail.next = ListNode(v) tail = tail.next return dummy.next def to_list(node): out = [] while node: out.append(node.val) node = node.next return out def reverse_k_group(head, k): dummy = ListNode(0, head) group_prev = dummy while True: kth = group_prev for _ in range(k): kth = kth.next if kth is None: return dummy.next # short last block stays as it is group_next = kth.next prev, cur = group_next, group_prev.next while cur is not group_next: nxt = cur.next cur.next = prev prev, cur = cur, nxt old_first = group_prev.next group_prev.next = kth group_prev = old_first def reverse_between(head, left, right): dummy = ListNode(0, head) before = dummy for _ in range(left - 1): before = before.next after = before for _ in range(right - left + 2): after = after.next # node just past the block (may be None) prev, cur = after, before.next while cur is not after: nxt = cur.next cur.next = prev prev, cur = cur, nxt before.next = prev return dummy.next assert to_list(reverse_k_group(build(range(1, 8)), 3)) == [3, 2, 1, 6, 5, 4, 7]assert to_list(reverse_k_group(build(range(1, 7)), 2)) == [2, 1, 4, 3, 6, 5]assert to_list(reverse_k_group(build([1, 2]), 3)) == [1, 2]assert to_list(reverse_k_group(build([1, 2, 3]), 1)) == [1, 2, 3]assert to_list(reverse_between(build([1, 2, 3, 4, 5]), 2, 4)) == [1, 4, 3, 2, 5]assert to_list(reverse_between(build([1, 2, 3]), 1, 3)) == [3, 2, 1]assert to_list(reverse_between(build([5]), 1, 1)) == [5]print(to_list(reverse_k_group(build(range(1, 8)), 3)))
Output
Press Run (⌘ Enter) to see what happens.
Put it in order5 steps

Put one round of the k-group loop in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Python
class Node: def __init__(self, val, next=None, random=None): self.val, self.next, self.random = val, next, random def copy_random_list(head): node = head while node: # 1. A -> A' -> B -> B' node.next = Node(node.val, node.next) node = node.next.next node = head while node: # 2. copy's random = random's copy if node.random: node.next.random = node.random.next node = node.next.next dummy = tail = Node(0) node = head while node: # 3. unzip and restore the original copy = node.next node.next = copy.next tail.next = copy tail, node = copy, node.next return dummy.next a, b, c = Node(7), Node(13), Node(11)a.next, b.next = b, ca.random, b.random, c.random = None, a, cout = copy_random_list(a)seen = []x, y = a, outwhile x: assert x is not y and x.val == y.val assert (y.random is None) == (x.random is None) if x.random: assert y.random is not x.random and y.random.val == x.random.val seen.append((y.val, y.random.val if y.random else None)) x, y = x.next, y.nextassert y is Noneassert a.next is b and b.next is c and c.next is None # original restoredassert copy_random_list(None) is Noneprint(seen)
Output
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:

ApproachTimeExtra space
Merge list 1 with 2, then the result with 3, and so onO(N·k)O(1)
Min-heap of the current front of each listO(N log k)O(k)
Divide and conquer: merge in pairs, then pairs of pairsO(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.

Predict the outputPython

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")
Need a nudge? Hints walk you through it.

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.

Python
import heapqimport random class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def build(vals): dummy = tail = ListNode() for v in vals: tail.next = ListNode(v) tail = tail.next return dummy.next def to_list(node): out = [] while node: out.append(node.val) node = node.next return out def add_two_numbers(a, b): dummy = tail = ListNode() carry = 0 while a or b or carry: total = (a.val if a else 0) + (b.val if b else 0) + carry carry, digit = divmod(total, 10) tail.next = ListNode(digit) tail = tail.next a = a.next if a else None b = b.next if b else None return dummy.next def merge_k_heap(lists): heap = [(node.val, i, node) for i, node in enumerate(lists) if node] heapq.heapify(heap) dummy = tail = ListNode() while heap: _, i, node = heapq.heappop(heap) tail.next = node tail = node if node.next: heapq.heappush(heap, (node.next.val, i, node.next)) return dummy.next def split(head, size): """Cut the list after `size` nodes and return the head of the rest.""" for _ in range(size - 1): if head is None: break head = head.next if head is None: return None rest = head.next head.next = None return rest def merge_onto(tail, a, b): """Merge a and b after tail; return the new tail.""" while a and b: if a.val <= b.val: tail.next, a = a, a.next else: tail.next, b = b, b.next tail = tail.next tail.next = a or b while tail.next: tail = tail.next return tail def sort_list(head): # bottom-up merge sort, O(1) extra space n, node = 0, head while node: n, node = n + 1, node.next dummy = ListNode(0, head) size = 1 while size < n: tail, cur = dummy, dummy.next while cur: left = cur right = split(left, size) cur = split(right, size) tail = merge_onto(tail, left, right) size *= 2 return dummy.next assert to_list(add_two_numbers(build([2, 4, 3]), build([5, 6, 4]))) == [7, 0, 8]assert to_list(add_two_numbers(build([9, 9, 9]), build([1]))) == [0, 0, 0, 1]assert to_list(add_two_numbers(build([5]), build([5]))) == [0, 1] lists = [build([1, 4, 5]), build([1, 3, 4]), build([2, 6]), None]assert to_list(merge_k_heap(lists)) == [1, 1, 2, 3, 4, 4, 5, 6]assert merge_k_heap([]) is None random.seed(1)for _ in range(200): vals = [random.randint(-50, 50) for _ in range(random.randint(0, 40))] assert to_list(sort_list(build(vals))) == sorted(vals)print(to_list(sort_list(build([4, 2, 1, 3, 0, 5]))))
Output
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 the pairs0/5 matched

Match each problem to the combination of moves it needs.

Choose an item, then its match on the other side.
Quick check
You merge k sorted lists of total size N by merging them in pairs, then merging the results in pairs, until one list is left. What is the time?
Need a nudge? A hint rules out a wrong answer.
Key terms
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 = None after a split so the two halves no longer share nodes.
group_prev
In k-group reversal, the node before the current block. Its next is 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.