19. Remove Nth Node From End of List
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Linked List
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven a singly-linked list and an integer n, delete the node that is exactly n positions from the tail and return the (possibly new) head of the modified list.
Approach
- Use a two-pointer (fast/slow) technique with a sentinel dummy node prepended so that head-removal needs no special case.
- Advance
fastexactlyn+1steps ahead ofslow; then move both together untilfastfalls off the end (becomesnullptr) — at that pointslowsits at the predecessor of the target. - Splice out the target with
slow->next = slow->next->nextand returndummy.next. - One pass through the list suffices, making this strictly O(n) time with O(1) extra space.
#include <cstddef>
using namespace std;
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) {
// Dummy node absorbs the edge case where the head itself is removed.
ListNode dummy(0, head);
ListNode* fast = &dummy;
ListNode* slow = &dummy;
// Advance fast by n+1 steps so the gap between slow and fast is n nodes.
for (int i = 0; i <= n; ++i)
fast = fast->next;
// Move both pointers until fast falls off the end.
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
// slow->next is the node to remove; skip over it.
ListNode* to_delete = slow->next;
slow->next = slow->next->next;
delete to_delete;
return dummy.next;
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
/**
* 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(0, head);
ListNode* tmp=head;
int total=0;
while(tmp){
++total;
tmp=tmp->next;
}
tmp=&dummy;
int target=total-n;
for(int i=0; i<target; i++) // prev node of target
tmp=tmp->next;
if(tmp->next){
ListNode* to_delete=tmp->next;
tmp->next=tmp->next->next;
delete to_delete;
}
return dummy.next;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.