Files

41 lines
2.3 KiB
Plaintext

Middle node and cycle detection with a slow and a fast pointer
==============================================================
Middle node of 1 -> 2 -> ... -> n (for even n, the second of the two middles):
n = 1 -> middle value 1 (index 0)
n = 2 -> middle value 2 (index 1)
n = 3 -> middle value 2 (index 1)
n = 4 -> middle value 3 (index 2)
n = 5 -> middle value 3 (index 2)
n = 6 -> middle value 4 (index 3)
n = 7 -> middle value 4 (index 3)
n = 8 -> middle value 5 (index 4)
Floyd's algorithm on 3 -> 2 -> 0 -> -4 whose last node links back to index 1:
list: 3 -> 2 -> 0 -> -4 -> ... (last node links back to index 1)
step 0 slow at index 0 fast at index 0
step 1 slow at index 1 fast at index 2
step 2 slow at index 2 fast at index 1
step 3 slow at index 3 fast at index 3
they meet at index 3 after 3 steps: there is a cycle
phase 2: probe at index 0, slow at index 3
phase 2: probe at index 1, slow at index 1
they meet again at index 1 after 1 steps: that is where the cycle starts
cycleStart value = 2, cycleLength = 3, hasCycle = true
plain 3 -> 2 -> 0 -> -4: hasCycle = false, cycleStart = null, cycleLength = 0
Why the second phase works. Tail length mu (nodes before the cycle) and cycle length lambda:
mu lambda | steps until they meet | meet at index | phase-2 steps | cycle starts at index
0 4 | 4 | 0 | 0 | 0
1 10 | 10 | 10 | 1 | 1
3 4 | 4 | 4 | 3 | 3
4 4 | 4 | 4 | 4 | 4
5 4 | 8 | 8 | 5 | 5
7 3 | 9 | 9 | 7 | 7
30 30 | 30 | 30 | 30 | 30
checked all 930 combinations of mu = 0..30 and lambda = 1..30: the formulas held every time.
Memory: on a 100000-node ring, a set of seen nodes holds 100000 entries before it finds the repeat;
Floyd holds exactly two references (slow and fast) and reaches the same answer: hasCycle = true