progress

~/problems / Linked lists / Linked lists

Middle node with fast and slow pointers

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Using the provided ListNode class (val, next), write middle_node(head) that returns the middle node of a non-empty list, the second middle for even lengths. Return the original node and don't modify the list.

1 -> 2 -> 3 -> 4 -> 5         middle is the node 3
1 -> 2 -> 3 -> 4 -> 5 -> 6    middle is the node 4 (the second of 3 and 4)
7                             middle is the node 7

Up to 2 * 10^5 nodes. Do it in one pass with O(1) extra memory: no copying into a Python list.

⭐ Bonus: a speed test with 200,000 nodes earns a star for a single pass.

Show hint

move slow one step and fast two while fast and fast.next. When fast runs out, slow is in the middle.

Topic: Linked lists. Dummy heads, pointer rewiring, fast/slow pointers.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc