Workspace Middle Of The Linked List
0d
DSA Problem Sheet

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.

EXECUTION LAB

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 slow

Visualizer

Step 1 of 3
7active · slow, fast195

Inspect the current state

Move the slow cursor once for each two-node fast advance.

Variable watch

slow 0fast 0

Step explanation

Move the slow cursor once for each two-node fast advance.

comparisons 2reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

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 1A runner travelling twice as fast reaches the finish when a walker reaches halfway.
Hint 2Advance one cursor by two links for every one-link move of the other.
Hint 3Step 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?