Problem Title
Oracle Interview Question – Remove Nth Node From End of List
Problem Description
You are given the head of a singly linked list and an integer n
.
Your task is to remove the n-th node from the end of the list and return the modified list.
Input Examples
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]
Constraints
-
The number of nodes in the list is between 1 and 30.
-
Each node’s value is between 0 and 100.
-
n
is between 1 and the size of the list.
Objective
Solve the problem in one pass through the linked list.
Approach – Two Pointer Technique (Single Pass)
-
Create a dummy node that points to the head. This handles edge cases like deleting the first node.
-
Use two pointers,
fast
andslow
, both starting from the dummy node. -
Move the
fast
pointern + 1
steps forward. -
Move both
fast
andslow
one step at a time untilfast
reaches the end. -
Now,
slow
is just before the node that needs to be deleted. -
Change
slow->next
to skip the target node. -
Delete the target node to free memory.
-
Return
dummy->next
as the new head of the list.
C++ Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* fast = dummy;
ListNode* slow = dummy;
for (int i = 0; i <= n; i++) {
fast = fast->next;
}
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
ListNode* toDelete = slow->next;
slow->next = slow->next->next;
delete toDelete;
return dummy->next;
}
};
Key Concepts
-
Dummy nodes simplify edge case handling.
-
Two-pointer technique allows solving the problem in a single pass.
-
Proper memory management is important to avoid leaks.