AlgoInsight

DSA problem

Remove Nth Node From End of List

MediumLinked ListPattern: Linked Listtop75FreeAmazonMicrosoftMetaGoogleApple

Given the head of a linked list, remove the n-th node from the end of the list and return its head.

The difficulty here is that a singly linked list can only be traversed forward, yet the target is described relative to the end. A straightforward two-pass solution first counts the total length L, then walks L - n nodes from the front to reach the node before the one to delete. This is correct and simple, but it scans the list twice.

The single-pass solution maintains a fixed n-node gap between two pointers. Advance a fast pointer n steps ahead first. Then move fast and a slow pointer together until fast reaches the last node; at that moment slow is exactly the predecessor of the node to remove, because the gap between them equals n.

To handle the case where the head itself must be removed, start both pointers from a dummy node placed before the head. The dummy guarantees slow always has a valid predecessor to rewire, so the deletion is a uniform O(1) pointer splice. The entire algorithm runs in one O(L) pass with O(1) extra space.

Examples

Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Explanation: The 2nd node from the end is the node with value 4. Removing it gives [1,2,3,5].
Example 2
Input: head = [1], n = 1
Output: []
Explanation: The only node is the 1st from the end; removing it leaves an empty list.
Example 3
Input: head = [1,2], n = 2
Output: [2]
Explanation: The 2nd node from the end is the head (value 1); removing it leaves [2]. The dummy node makes this head deletion uniform.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listtwo-pointersfast-slow-pointers

Browse all DSA problems