Remove Kth Node From End
Remove Kth Node From End
Category
Linked Lists
Difficulty
Medium
Problem Statement
Given the head of a singly linked list and a positive integer k, remove the kth node from the end of the list. The removal should be done in place. Note that the head of the list could be the node that needs to be removed.
Intuition
Using two pointers separated by a gap of k nodes, when the leading pointer reaches the end of the list, the trailing pointer will be right before the node to remove. This allows us to find and remove the target node in a single pass without first calculating the length of the list.
Approach
- Initialize two pointers,
firstandsecond, both at the head. - Advance
firstbyksteps so that it isknodes ahead ofsecond. - If
firstis now null, the node to remove is the head itself. Update the head's value and next pointer. - Otherwise, advance both
firstandsecondone step at a time untilfirst.nextis null. - Now
secondis the node right before the target. Setsecond.next = second.next.next.
Pseudocode
function removeKthNodeFromEnd(head, k):
first = head
second = head
// Advance first by k steps
for i from 0 to k - 1:
first = first.next
// If first is null, remove the head
if first is null:
head.value = head.next.value
head.next = head.next.next
return
// Advance both until first reaches the last node
while first.next is not null:
first = first.next
second = second.next
// Remove the node after second
second.next = second.next.next
Time & Space Complexity
- Time: O(n) where n is the length of the list. We traverse the list once.
- Space: O(1) — only two pointers are used.
Key Insights
- The two-pointer gap technique converts a "distance from end" problem into a "distance from another pointer" problem.
- Removing the head node is a special case that requires careful handling since we cannot modify what
headpoints to from outside the function. Instead, we copy the next node's value and skip it. - The gap of exactly
kensures that whenfirstreaches the end,secondis positioned correctly for removal.
Edge Cases
- Removing the head node (k equals the length of the list).
- Removing the last node (k = 1).
- Single-node list where k = 1: the list becomes empty, but handling depends on the problem's API.
kis guaranteed to be valid (1 <= k <= length of list), so no bounds checking is needed.