Final challenge: slow and fast
After this: Find the middle, detect a cycle and merge two sorted lists.
This challenge brings the tutorial together. It has three steps, and each step is scored on its own. All three use two pointers at the same time: you find the middle of a list in one walk, catch a list that loops back on itself, and merge two sorted lists by changing pointers instead of copying values. You can try as many times as you like, and hints work as they did in the lessons.
Imagine two runners on a track, one twice as fast as the other. When the fast runner reaches the end, the slow runner is halfway. Two variables can do the same on a list. We call them slow and fast, and both start at the head. At each step, fast moves two nodes and slow moves one. When fast cannot move any further, slow is at the middle. One walk is enough, so you do not have to count the nodes first.
Here it is on 1 → 2 → 3 → 4 → 5.
- Both start on 1.
- fast moves to 3, and slow moves to 2.
- fast moves to 5, and slow moves to 3.
- fast has no next node, so the walk stops. slow is on 3, the middle.
Here, slow and fast are variables that point at nodes. In later tutorials on arrays, you will meet "two pointers" that are really two indexes. The idea is alike, but those are position numbers, not pointers to nodes.
- Find the middleFind the middle of five nodes. At each step, fast moves two nodes and slow moves one. When fast cannot move any further, slow is in the middle.
Run an operation to begin.
The same function runs on five nodes and then on six. What prints?
def middle(head): slow = fast = head while fast is not None and fast.next is not None: fast = fast.next.next # two nodes per step slow = slow.next # one node per step return slow # even length: the second of the two middlesstatic Node middle(Node head) { Node slow = head, fast = head; while (fast != null && fast.next != null) { fast = fast.next.next; // two nodes per step slow = slow.next; // one node per step } return slow; // even length: the second of the two middles}print(middle(build([1, 2, 3, 4, 5])).value, middle(build([1, 2, 3, 4, 5, 6])).value)System.out.println(middle(build(1, 2, 3, 4, 5)).value + " " + middle(build(1, 2, 3, 4, 5, 6)).value);Suppose the last node points back at an earlier node, not at nothing. This is called a cycle. A walk on such a list goes round and round and never ends, because it never reaches the end marker.
The same two variables can catch this. On a plain list, fast reaches the end. In a cycle there is no end, so fast goes round and comes up behind slow. At each step fast moves two nodes and slow moves one, so the gap between them closes by exactly one node. That means fast cannot jump over slow. It must land on slow, and then the two point at the same node. If that happens, the list has a cycle.
- Detect a cycleRun the detector on a plain list. fast reaches the end, so there is no cycle.
- Link the tail back to 3
- Detect a cycle
Run an operation to begin.
The list is 1 → 2 → 3 → 4 → 5, and now the last node, 5, points back at 2 instead of 3. Run has_cyclehasCycle. Where do slow and fast meet?
def has_cycle(head): slow = fast = head while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if slow is fast: # they met: only a cycle makes that possible return True return False # fast found the end, so there is no cyclestatic boolean hasCycle(Node head) { Node slow = head, fast = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (slow == fast) return true; // they met: only a cycle makes that possible } return false; // fast found the end, so there is no cycle}Two sorted lists can become one sorted list without copying a single value. Look at the first node of each list, and link the one with the smaller value onto the end of the result. Then move that list forward by one node, and repeat. When one list runs out, link on whatever is left of the other.
Here it is with 1 → 4 and 2 → 3.
- Compare 1 and 2. Take 1.
- Compare 4 and 2. Take 2.
- Compare 4 and 3. Take 3.
- The second list has run out, so link on what is left, which is 4. The result is 1 → 2 → 3 → 4.
The code starts with an extra node called dummy, a stand-in first node that is not part of the result. It gives the variable tail somewhere to start, so the first link is not a special case. tail always points at the last node of the result, and the real first node is dummy.next.
What does this print?
def merge(a, b): dummy = Node(0) # a stand-in first node, so the first link is not a special case tail = dummy while a is not None and b is not None: if a.value <= b.value: tail.next = a # take the smaller node; nothing is copied a = a.next else: tail.next = b b = b.next tail = tail.next # the merged list grew by one node tail.next = a if a is not None else b # whatever is left is already sorted return dummy.next # the real head is after the stand-instatic Node merge(Node a, Node b) { Node dummy = new Node(0); // a stand-in first node, so the first link is not a special case Node tail = dummy; while (a != null && b != null) { if (a.value <= b.value) { tail.next = a; // take the smaller node; nothing is copied a = a.next; } else { tail.next = b; b = b.next; } tail = tail.next; // the merged list grew by one node } tail.next = a != null ? a : b; // whatever is left is already sorted return dummy.next; // the real head is after the stand-in}print(show(merge(build([1, 4, 8]), build([2, 3, 9, 10]))))System.out.println(show(merge(build(1, 4, 8), build(2, 3, 9, 10))));Complete merge. After tail.next is linked to the chosen node, tail must move onto that node, or the next link would overwrite this one.
def merge(a, b): dummy = Node(0) tail = dummy while a is not None and b is not None: if a.value <= b.value: tail.next = a a = a.next else: tail.next = b b = b.next ______________________ # ← move tail onto the node you linked tail.next = a if a is not None else b return dummy.nextstatic Node merge(Node a, Node b) { Node dummy = new Node(0); Node tail = dummy; while (a != null && b != null) { if (a.value <= b.value) { tail.next = a; a = a.next; } else { tail.next = b; b = b.next; } ______________________ // ← move tail onto the node you linked } tail.next = a != null ? a : b; return dummy.next;}- Find the middle and detect a cycle with slow and fast pointers, and merge two sorted lists by changing pointers.