The βRemove Nth Node From End of Listβ problem asks you to remove the n
th node from the end of a singly linked list, and return the modified listβs head.
Example:
1 β 2 β 3 β 4 β 5
, n = 21 β 2 β 3 β 5
4
; after removing it, the list becomes 1 β 2 β 3 β 5
.This is a classic linked list problem that highlights the use of the two-pointer (fast and slow) technique. It also teaches how to modify list structure without explicitly counting all elements β a useful skill in memory-constrained and real-time environments.
The idea is to maintain a fixed gap of n
between two pointers so that when the fast pointer reaches the end, the slow pointer is at the node just before the one to be removed. Using a dummy node simplifies edge cases like removing the head.
dummy
node that points to the head of the list.ahead
and behind
, both pointing to dummy
.ahead
n + 1
steps forward to create a gap of n
between ahead
and behind
.ahead
is not null
:
behind
points to the node just before the one we want to remove.behind.next = behind.next.next
.dummy.next
as the new head of the list.
Input: 1 β 2 β 3 β 4 β 5
, n = 2
Steps:
1 β 2 β 3 β 5
Time Complexity: O(n), where n
is the number of nodes in the list. Each node is visited at most once.
Space Complexity: O(1), since only pointers and no additional memory are used.
The βRemove Nth Node From End of Listβ problem elegantly demonstrates how to use the two-pointer technique to solve linked list problems in one pass. It also emphasizes how dummy nodes help handle edge cases cleanly. Mastering this pattern will help you solve a wide range of similar problems efficiently.