A fixed gap between two pointers

Linked Lists

A fixed gap between two pointers

Counting from the end without knowing the length: start one pointer early and keep the distance.

Key idea

The gap never changes

Position from the end is awkward because you only discover the end by reaching it. The two-pass answer counts the length, then walks again. The one-pass answer keeps two pointers a fixed distance apart.

Advance the lead pointer k steps first. Then move both together. When the lead reaches the end, the trailing pointer is exactly k behind it, which is k from the end.

Gotcha

The gap is off by one from what you expect

Advancing the lead k steps leaves the trailing pointer on the node k from the end counting the last node as 1. Advancing k + 1 steps leaves it on the node before that one.

Which you want depends on the task. Reading the kth node wants the first. Removing it wants the second, because deletion needs the predecessor. Getting this wrong by one is the entire difficulty of the problem below.

The reliable way to settle it is a three-node list on paper. Guessing and adjusting until the samples pass usually produces something that fails on a boundary case instead.

Why it works

Combine it with the dummy head

Removing the kth from the end can mean removing the head itself, when k equals the length. Rather than branching for that, start the trailing pointer at a dummy node placed before the head.

Then the trailing pointer always has a predecessor to be, the removal is one uniform assignment, and the answer is dummy.next. Two techniques from this unit combining to erase a whole case is the intended lesson here.

Edge cases

What if the list is shorter than k?

The advance loop can run off the end. Whether that is an error, a no-op, or impossible depends on the problem's guarantees, and the guard above returns None for it.

Many versions promise that k is valid. Check for that promise; if it is there, say you are relying on it rather than silently omitting the check.

Find the off-by-one

This is meant to insert a new node immediately before the kth node from the end. On a three-node list with k equal to 1 the new node lands in the wrong place. Click the line that causes it.

This activity type is not wired up yet.

Remove Nth Node From End Of List

Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.

Loading the workspace…
← Previous