Remove Nth Node From End of List (LeetCode 19): Solution and Explanation
Given the head of a singly linked list and an integer n, remove the node that is n positions from the end and return the head of the updated list. The removed node might be the head itself, which the solution has to handle.
Watch it run step by step
Try your own input and write the code →Intuition
The obvious solution takes two passes. Walk the list once to count its length L, then walk again to the node at position L minus n, which is the one just before the target, and unlink the next node. That is already O(n) time and O(1) space, so the interesting part is doing it in one pass without knowing the length up front.
The trick is to measure distance from the end using a gap between two pointers. If a right pointer starts n nodes ahead of a left pointer and both then move together, then when right falls off the end of the list, left is exactly n nodes behind the end. Nothing needs to be counted, because the gap does the counting for you.
To delete a node in a singly linked list you need a pointer to the node before it. That is why left starts at a dummy node placed in front of the head while right starts at the head itself. The extra node of offset means left stops one step early, right before the target. The dummy also removes the special case of deleting the head: when n equals the list length, left never moves, and dummy.next simply skips the old head.
Approach: Two pointers with a fixed gap and a dummy node
- Create
dummywithnext = head. Setleft = dummyandright = head. - Move
rightforward n times so it is n nodes ahead ofhead. - Move
leftandrighttogether, one step each, untilrightbecomes None. - Now
left.nextis the node n positions from the end. Unlink it withleft.next = left.next.next. - Return
dummy.next, which is the original head unless the head itself was removed.
Step-by-step example
head = [1,2,3,4,5], n = 2
- Start with
leftat the dummy andrightat node 1. - Advance
righttwice: it moves to 2 and then to 3. - Move both together. First
leftgoes to 1 andrightto 4, thenleftto 2 andrightto 5, thenleftto 3 andrightto None. leftis node 3 andleft.nextis node 4, which is second from the end. Set3.nextto node 5.- Return
dummy.next, giving [1,2,3,5].
Code: Python, Java, C++
1class Solution:
2 def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
3 dummy = ListNode(0, head)
4 left = dummy
5 right = head
6
7 while n > 0 and right:
8 right = right.next
9 n -= 1
10
11 while right:
12 left = left.next
13 right = right.next
14
15 left.next = left.next.next
16 return dummy.next1class Solution {
2 public ListNode removeNthFromEnd(ListNode head, int n) {
3 ListNode dummy = new ListNode(0, head);
4 ListNode left = dummy;
5 ListNode right = head;
6
7 while (n > 0 && right != null) {
8 right = right.next;
9 n--;
10 }
11
12 while (right != null) {
13 left = left.next;
14 right = right.next;
15 }
16
17 left.next = left.next.next;
18 return dummy.next;
19 }
20}1class Solution {
2public:
3 ListNode* removeNthFromEnd(ListNode* head, int n) {
4 ListNode* dummy = new ListNode(0, head);
5 ListNode* left = dummy;
6 ListNode* right = head;
7
8 while (n > 0 && right) {
9 right = right->next;
10 n--;
11 }
12
13 while (right) {
14 left = left->next;
15 right = right->next;
16 }
17
18 left->next = left->next->next;
19 return dummy->next;
20 }
21};Time and space complexity
O(n)
Here n means the length of the list. The right pointer travels the list once from head to end, and left trails behind it, so the work is a single linear pass.
O(1)
Only the dummy node and two pointers are used, regardless of list length.
Other approaches
Count the length, then remove (time O(n), space O(1))
First pass counts the nodes. Second pass walks from a dummy node L minus n steps to reach the predecessor of the target and unlinks it. Same complexity, two passes instead of one, and arguably easier to explain.
Array of node references (time O(n), space O(n))
Store every node in an array, then index the predecessor directly at position L minus n minus 1, handling the head as a special case. Simple, but it costs linear extra memory.
Common mistakes
- Starting both pointers at the same node. Then
leftlands on the target itself rather than the node before it, and a singly linked list cannot delete a node from its own position. - Skipping the dummy node. When n equals the list length, the head must be removed, and without a dummy there is no predecessor to update.
- Advancing
rightn plus one times or n minus one times. The offset between the dummy start and the head start already accounts for the extra step. - Returning
headinstead ofdummy.next, which returns the deleted node when the head was the one removed.
Frequently asked questions
How do you remove the nth node from the end in one pass?
Put a dummy node before the head, start one pointer at the dummy and another n nodes ahead, then move them together until the leading pointer reaches the end. The trailing pointer then sits right before the node to delete.
Why do we need a dummy node?
Deleting a node means changing its predecessor's next, and the head has no predecessor. The dummy acts as one, so removing the head uses the same code as removing any other node.
Is the one-pass solution faster than the two-pass one?
Both are O(n). The one-pass version touches each node roughly once instead of up to twice, which matters little in practice, but it is the version interviewers usually ask for as a follow-up.