Remove Nth Node From End of List
Given the headn
Example 1
Input: head = [1, 2, 3, 4, 5], n = 2
Output: [1, 2, 3, 5]
Explanation: Node with value 4 (2nd from end) is removed.
Output: [1, 2, 3, 5]
Explanation: Node with value 4 (2nd from end) is removed.
Example 2
Input: head = [1], n = 1
Output: []
Output: []
Example 3
Input: head = [1, 2], n = 1
Output: [1]
Output: [1]
Solution Approach - Two Pointer (Single Pass)
We use two pointers separated by a gap of n
- Create a
node pointing todummy . Set bothhead andfast toslow .dummy - Advance
exactlyfast steps ahead ofn + 1 . This creates a gap of n nodes.slow - Move both
andfast one step at a time untilslow reaches null.fast - Now
points to the node just before the target. Setslow to remove it.slow.next = slow.next.next - Return
.dummy.next
Java
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class RemoveNthNodeFromEndOfList {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
// Advance fast by n+1 steps
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
// Move both until fast reaches the end
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
// Remove the nth node from end
slow.next = slow.next.next;
return dummy.next;
}
}
Complexity Analysis:
Time complexity: O(L) where L is the length of the list. We make a single pass through the list.
Space complexity: O(1) as only two pointers are used.