Continue learning
Practice related DSA questions in the same topic.
Return the index of the middle node of the input-order list. For even lengths return the second middle. Return -1 when empty.
Return the index of the middle node of the input-order list. For even lengths return the second middle. Return -1 when empty.
def solve(values, target): if (len(values) == 0): return -1 slow = 0 fast = 0 while ((fast + 1) < len(values)): slow = (slow + 1) fast = (fast + 2) return slowMove the slow cursor once for each two-node fast advance.
Move the slow cursor once for each two-node fast advance.
A runner travelling twice as fast reaches the finish when a walker reaches halfway.
Advance one cursor by two links for every one-link move of the other.
O(n) time · O(1) auxiliary space
Worked example · {"values":[7,1,9,5],"target":0} ⇒ 2
Edge case 1 · {"values":[],"target":0} ⇒ -1
Edge case 2 · {"values":[2],"target":0} ⇒ 0
Stopping the fast runner one move too early picks the first middle for even lengths.
How would the fast pointer reveal a cycle?