We are given a linked list (like [2 → 4 → 7 → 8]
)
and a number k.
We must return the k-th node from the end.
Example:
[2,4,7,8]
, k = 1 → answer = 8
(last node)[2,4,7,8]
, k = 2 → answer = 7
(second last node)[2,4,7,8]
, k = 3 → answer = 4
(third last node)👉 Start Runner A k
steps ahead of Runner B.
Why?
Because then when Runner A reaches the end of the list,
Runner B will automatically be k steps behind → exactly at the node we want. ✅
Put Runner A and Runner B at the head (start of the list).
Move Runner A forward k
steps.
k
nodes ahead of Runner B.Move both runners forward together, one step at a time.
When Runner A reaches the end →
Runner B is standing at the k-th node from the end. 🎉