Introduction
Working with linked lists can be tricky because you only move forward one step at a time. The runner technique helps solve problems where you need to compare or find elements at different speeds or positions in the list.
Imagine two runners on a track. One runs faster and the other slower. By watching where they meet or how far apart they are, you can learn about the track's length or if it loops back on itself.
┌───────────────┐ │ Linked List │ │ │ │ o → o → o → o → o → o → o → null │ ↑ ↑ │ slow fast └───────────────┘
class Node: def __init__(self, val): self.val = val self.next = None def find_middle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.val # Create linked list: 1 -> 2 -> 3 -> 4 -> 5 head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) print(find_middle(head))
runner technique in linked lists?slow moves one step and fast moves two steps, what value will slow point to when fast reaches the end?Pass the test and this pattern moves unknown