Middle of the Linked List
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.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
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 slowVisualizer
Step 1 of 3Inspect the current state
Move the slow cursor once for each two-node fast advance.
Variable watch
Step explanation
Move the slow cursor once for each two-node fast advance.
Worked explanation
A runner travelling twice as fast reaches the finish when a walker reaches halfway.
Guided solution
Advance one cursor by two links for every one-link move of the other.
O(n) time · O(1) auxiliary space
Examples
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
Progressive hints
Hint 1
A runner travelling twice as fast reaches the finish when a walker reaches halfway.Hint 2
Advance one cursor by two links for every one-link move of the other.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Stopping the fast runner one move too early picks the first middle for even lengths.
Interview follow-up
How would the fast pointer reveal a cycle?