Patterns: lists and linked lists
This chapter 1 review covers three list and linked-list patterns: two pointers walking in from both ends, fast and slow pointers to find the middle or a cycle, and prev, cur and nxt to reverse a linked list, all O(n) time and O(1) extra space.
There seem to be endless list and linked-list problems: two-sum, the middle node, does it have a cycle, reverse a list, a palindrome list, remove the nth node from the end… But in interviews most of them come down to three patterns: two pointers walking in from both ends; fast and slow pointers, one taking one step and the other two; and three pointers turning each next round as they go. All three are O(n) time and O(1) extra space, saving the O(n) memory of "copy it into a list first", and they are exactly the answer interviewers want to hear.
Pattern 1: walk in from both ends
Find two numbers in a sorted list that add up to target. Brute force is two nested loops over n(n − 1)/2 pairs. A sorted list allows two pointers: lo on the far left, hi on the far right; if the sum is too small, lo moves right (for something bigger), if too big, hi moves left. Every step rules one number out: when the sum is too small, a[lo] falls short even with the biggest number, so it cannot pair with anything.
lo↑hi1lo, hi = 0, len(a) - 12while lo < hi:3 s = a[lo] + a[hi]4 if s == target:5 return lo, hi6 elif s < target:7 lo += 18 else:9 hi -= 1
Count both ways (400 odd numbers, looking for the last two):
1def two_sum_brute(a, target):2 looks = 03 for i in range(len(a)):4 for j in range(i + 1, len(a)):5 looks += 16 if a[i] + a[j] == target:7 return (i, j), looks8 return None, looks9 10def two_sum_sorted(a, target):11 looks = 012 lo, hi = 0, len(a) - 113 while lo < hi:14 looks += 115 s = a[lo] + a[hi]16 if s == target:17 return (lo, hi), looks18 elif s < target:19 lo += 120 else:21 hi -= 122 return None, looks23 24a = list(range(1, 801, 2))25print(two_sum_brute(a, 797 + 799))26print(two_sum_sorted(a, 797 + 799))27print(two_sum_sorted([1, 2, 4, 6, 8, 11], 14))
((398, 399), 79800) ((398, 399), 399) ((3, 4), 5)
The same pattern also does: reversing a list in place (swap lo and hi, then step inwards), checking for a palindrome, squaring a sorted array. The other kind has the two pointers walking the same way: lesson 2's k pointer (remove an element, move zeroes, remove duplicates from a sorted list).
In the sorted [1, 2, 4, 6, 8, 11], use lo and hi to find two numbers that add up to 10. How many times do you work out a[lo] + a[hi] before you find them?
Pick what goes in the blank: when the sum is too small, which pointer moves?
1def two_sum_sorted(a, target):2 lo, hi = 0, len(a) - 13 while lo < hi:4 s = a[lo] + a[hi]5 if s == target:6 return lo, hi7 elif s < target:8 9 else:10 hi -= 111 return None12 13print(two_sum_sorted([1, 2, 4, 6, 8, 11], 14))
lo += 1. Only when the sum is too big do you write hi -= 1.Remove duplicates from a sorted list
✓Finish dedup(a): a is sorted from small to large; remove the duplicates in place and return how many are kept, k, so that a[:k] is the result. Use two pointers walking the same way: k is the next position to write.
4 [1, 2, 3, 5] 1 [4] 0
1def dedup(a):2 if not a:3 return 04 k = 15 # i looks from 1 onwards: only values different from a[k - 1] are written to a[k]6 return k7 8a = [1, 1, 2, 3, 3, 3, 5]9k = dedup(a)10print(k, a[:k])11b = [4, 4, 4]12k = dedup(b)13print(k, b[:k])14print(dedup([]))
Pattern 2: fast and slow pointers
A linked list has no len to halve and no indexes. Let slow take 1 step at a time and fast take 2: when fast reaches the end, slow is right in the middle.
slow↓fast↓1slow = fast = head2while fast and fast.next:3 slow = slow.next4 fast = fast.next.next5return slow
The same two pointers can tell whether there is a cycle: in a list with a cycle, while cur never stops. With no cycle, fast reaches None first; with a cycle, once fast is in the loop it goes round and round, gaining 1 step on slow every turn, so sooner or later it catches slow.
slow↓fast↓1slow = fast = head2while fast and fast.next:3 slow = slow.next4 fast = fast.next.next5 if slow is fast:6 return True7return False
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def from_list(vals):7 head = None8 for v in reversed(vals):9 head = Node(v, head)10 return head11 12def middle(head):13 slow = fast = head14 while fast and fast.next:15 slow = slow.next16 fast = fast.next.next17 return slow18 19def has_cycle(head):20 slow = fast = head21 while fast and fast.next:22 slow = slow.next23 fast = fast.next.next24 if slow is fast:25 return True26 return False27 28print(middle(from_list([1, 2, 3, 4, 5])).val)29print(middle(from_list([1, 2, 3, 4, 5, 6])).val)30 31h = from_list([1, 2, 3, 4, 5])32print(has_cycle(h))33h.next.next.next.next.next = h.next.next # 5 points back to 334print(has_cycle(h))
3 4 False True
With an even count it stops on the second of the two middles (4 out of 6). For the first, change the condition to while fast.next and fast.next.next. Another variant, "remove the nth node from the end": fast goes n steps first, then both walk together, and when fast reaches the end, slow is just before the nth from the end.
With 4 nodes, where do the two versions of "find the middle" stop?
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def from_list(vals):7 head = None8 for v in reversed(vals):9 head = Node(v, head)10 return head11 12def middle(head):13 slow = fast = head14 while fast and fast.next:15 slow = slow.next16 fast = fast.next.next17 return slow18 19def middle_first(head):20 slow = fast = head21 while fast.next and fast.next.next:22 slow = slow.next23 fast = fast.next.next24 return slow25 26h = from_list([1, 2, 3, 4])27print(middle(h).val, middle_first(h).val)
while fast and fast.next: slow goes to 2 and 3 while fast goes to 3 and then None, so it stops on 3, the second middle. while fast.next and fast.next.next: when fast is on 3, fast.next.next is None, so there is only 1 step and slow stops on 2, the first middle. To cut a list in half (a palindrome list, merge sort) you usually want the first.Is there a cycle?
✓Finish has_cycle(head) with fast and slow pointers: return True if there is a cycle, False if not. Do not use a set of visited nodes.
False False True True
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def has_cycle(head):7 # slow takes 1 step, fast takes 2; fast reaching None means no cycle, catching slow means a cycle8 return False9 10a = Node(1, Node(2, Node(3, Node(4))))11print(has_cycle(a), has_cycle(None))12 13b = Node(1, Node(2, Node(3, Node(4))))14b.next.next.next.next = b.next # 4 points back to 215c = Node(9)16c.next = c # pointing at itself17print(has_cycle(b), has_cycle(c))
Pattern 3: reversing a linked list
Three pointers: prev is the head of the part already reversed, cur is the node being handled, and nxt remembers cur's next first. Remember first, then repoint: once cur.next has changed, nxt is the only thing still pointing at the old next node.
prev↓cur↓nxt↓1prev, cur = None, head2while cur:3 nxt = cur.next4 cur.next = prev5 prev = cur6 cur = nxt7return prev
Forget nxt, writing cur.next = prev then cur = cur.next, and cur goes back to prev: every node after it is lost.
| Pattern | Used for | Time | Extra space |
|---|---|---|---|
| In from both ends (lo, hi) | a pair in a sorted list, reversing, palindromes | O(n) | O(1) |
| Two pointers the same way (i, k) | removing in place, moving zeroes, removing duplicates from a sorted list | O(n) | O(1) |
| Fast and slow pointers | the middle node, cycles, the nth from the end | O(n) | O(1) |
| Three pointers reversing | reversing a list, palindrome lists (reverse the second half) | O(n) | O(1) |
In interviews: for a linked-list problem, draw 3 or 4 nodes on paper and every step's arrows before writing code; afterwards, walk through it with an empty list, one node and two nodes. "Why is fast sure to catch slow?": once both are in the loop, the gap shrinks by 1 each turn, so fast cannot jump past.
Put the four lines inside the reversing loop in order so that 1 → 2 → 3 → 4 is turned round and the program prints [4, 3, 2, 1].
prev = curcur = nxtcur.next = prevnxt = cur.next
[4, 3, 2, 1]
nxt = cur.next: remember the next node first, because once cur.next changes it is gone. Then cur points back at prev, and finally prev and cur step forward together. prev = cur must come before cur = nxt, or prev gets the next node.Reverse a linked list
✓Finish reverse(head): reverse the list in place and return the new head. For an empty list return None.
[5, 4, 3, 2, 1] [7] []
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def from_list(vals):7 head = None8 for v in reversed(vals):9 head = Node(v, head)10 return head11 12def to_list(head):13 out = []14 while head:15 out.append(head.val)16 head = head.next17 return out18 19def reverse(head):20 # prev = None, cur = head; each turn: remember nxt, point cur back at prev, move on one21 return head22 23print(to_list(reverse(from_list([1, 2, 3, 4, 5]))))24print(to_list(reverse(from_list([7]))))25print(to_list(reverse(None)))
How you write it at work
These patterns are mostly for linked lists and for problems that forbid extra space. With an ordinary list and no limit on space, there are more direct ways:
1def two_sum(nums, target):2 seen = {} # value -> index3 for i, x in enumerate(nums):4 if target - x in seen:5 return seen[target - x], i6 seen[x] = i7 return None8 9print(two_sum([8, 3, 11, 6, 1], 14))10 11a = [1, 2, 3, 4]12b = a[::-1] # a new list: O(n) time, O(n) space13a.reverse() # in place: O(n) time, O(1) space14print(a, b, list(reversed(b)))15print(a[len(a) // 2]) # the middle of a list: O(1)
(1, 2) [4, 3, 2, 1] [4, 3, 2, 1] [1, 2, 3, 4] 2
- Two-sum on an unsorted list: a dict of the numbers seen so far, one O(n) pass; sorting first and then two pointers is O(n log n), and scrambles the indexes too.
- Reversing:
a.reverse()works in place,a[::-1]makes a new list, andreversed(a)gives only an iterator that walks backwards, with no new list. - The middle of a list is just
a[len(a) // 2]; fast and slow pointers are only needed on a linked list.
nums is not sorted and you want the indexes of two numbers that add up to target. What is the most direct way at work?
target - x has been seen. Sorting first and then using two pointers costs O(n log n), and after sorting the indexes are no longer the original ones, so you would have to keep track of them as well. Two nested loops are O(n²), not O(n).Summary
Three patterns for lists and linked lists
- A pair in a sorted list: lo and hi walk in from both ends, ruling one out each step, O(n)
- Fast and slow pointers: when fast reaches the end, slow is in the middle; slow is fast means a cycle
- Reversing a linked list: remember nxt first, then point cur back at prev, and all three move on
- All O(n) time, O(1) extra space; draw it first, then check with empty, 1 and 2 nodes
1while lo < hi: # in from both ends2 ...3slow, fast = slow.next, fast.next.next # fast and slow4nxt = cur.next; cur.next = prev # reverse5prev, cur = cur, nxt
Chapter 1 quick check
Five questions: references and copies, how many an insert moves, how many a resize copies, inserting in a linked list, and an LRU cache. Work out what each prints yourself, then pick an option.
After [[0] * 2] * 2, a shallow copy is made, then one cell changes and the copy gets one more item. What does it print?
1a = [[0] * 2] * 22b = a[:]3a[0][0] = 14b.append([5])5print(a, len(a))
[[0] * 2] * 2 point at the same row, so changing a[0][0] changes both rows. b = a[:] is a new outer list, and appending to b does not affect a, so a still has 2 items.Every insert(0, x) moves everything already there back one slot. What does it print?
1moves = 02a = []3for x in range(5):4 moves += len(a)5 a.insert(0, x)6print(a, moves)
Starting at capacity 1, doubling and copying everything across whenever it is full. After 10 appends, what does it print?
1cap, size, copies = 1, 0, 02for x in range(10):3 if size == cap:4 copies += size5 cap *= 26 size += 17print(cap, copies)
A 9 is inserted after p, then a 0 is added at the front. What does it print?
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6head = Node(1, Node(2, Node(3)))7p = head.next8p.next = Node(9, p.next)9head = Node(0, head)10out = []11cur = head12while cur:13 out.append(cur.val)14 cur = cur.next15print(out)
head.next, the 2. Node(9, p.next) links the back first (9 points at 3), then is assigned to p.next (2 points at 9): 1 → 2 → 9 → 3. head = Node(0, head) is push_front, so 0 goes to the front.The cache remembers at most 2 results, and the calls are 1 2 3 1 2 3. How many times does the function body really run?
1from functools import lru_cache2 3calls = 04 5@lru_cache(maxsize=2)6def f(x):7 global calls8 calls += 19 return x10 11for x in [1, 2, 3, 1, 2, 3]:12 f(x)13print(calls)