Remove Nth Node from End
Problem Statement:β
Given theΒ headΒ of a linked list, remove theΒ nthΒ node from the end of the list and return its head.
Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
-
Example:
β Solution: Two Pointer Technique (Fast & Slow Pointers)β
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL) return NULL;
ListNode *slow = head, *fast = head;
// Move the fast pointer n steps ahead
while(n--) {
fast = fast->next;
}
// If fast is NULL, the node to be deleted is the head itself
if(fast == NULL) return head->next;
// Move both pointers until fast reaches the end
while(fast->next != NULL) {
slow = slow->next;
fast = fast->next;
}
// Delete the nth node from the end
slow->next = slow->next->next;
return head;
}
};
π How It Worksβ
- This method uses two pointers (
fastandslow) to identify the node to delete in a single traversal. fastis movednsteps ahead first.- If
fastbecomesNULL, it means we have to remove the head node (i.e.,nequals the length of the list). - Otherwise, we move both pointers forward together until
fast->next == NULL. At this point:slowis just before the node we need to remove.
- We update
slow->nextto skip the node.
π§© Key Formula / Recurrenceβ
Thereβs no recurrence here β just a key pointer logic:
When fast reaches the end, slow is at (length - n)-th node (i.e., just before the target node).
β±οΈ Time & Space Complexityβ
| Metric | Complexity |
|---|---|
| β±οΈ Time | O(L), where L is the length of the linked list |
| πͺ Space | O(1), constant space |
β οΈ Edge Casesβ
head == NULLβ returnNULLn == length of listβ remove the head node- Only one node in the list β result should be
NULLafter deletion - Deleting the last node (
n == 1) is handled smoothly
π‘ Other Approachesβ
| Approach | Time | Space |
|---|---|---|
| Two-pass (count length first) | O(L) | O(1) |
| Stack-based (store pointers) | O(L) | O(L) |
| Recursive postorder deletion | O(L) | O(L) due to call stack |
π Related Problemsβ
- LC 19. Remove Nth Node From End of List
- LC 876. Middle of the Linked List
- LC 206. Reverse Linked List
- LC 2. Add Two Numbers
π¬