Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get the head of a linked list and a number n. Remove the node that is n-th from the end (n = 1 is the last node) and return the head of the changed list.
n is always valid: the list has between 1 and 30 nodes, and 1 ≤ n ≤ length. That means n can equal the length, which means deleting the head.
Example: 1 → 2 → 3 → 4 → 5, n = 2 → 1 → 2 → 3 → 5. The 2nd node from the end is 4.
Start with brute force
Two passes. First, walk the whole list to count its length L. The node to delete is then L − n steps from the front (0-indexed), so walk L − n − 1 steps to reach the node before it and unlink it. If L − n is 0, you're deleting the head, so return head.next instead.
That's already O(n) time and O(1) space, so it's a perfectly good answer. Interviewers usually follow with "can you do it in one pass?" The one-pass version also teaches a trick you'll reuse.
Building the intuition
The trouble is "from the end". When you're walking a singly linked list, you have no idea how close the end is until you fall off it.
So use a second pointer as a measuring stick. Picture two people walking down a corridor holding a rope of fixed length between them. When the person in front touches the far wall, the person behind is exactly one rope-length from the wall.
In pointer terms: if fast is exactly n nodes ahead of slow, then when fast is on the last node, slow is n nodes before the last node. That's the node just before the one we want to delete. And "just before" is exactly what deleting needs, because to unlink a node you change the next of the node in front of it.
One problem left: if the target is the head, there's no node in front of it. So make one. A dummy node placed before head means every real node, including the head, has a node before it. Start both pointers on the dummy.
The optimal approach
- Create
dummywithdummy.next = head. Setslow = fast = dummy. - Move
fastforwardntimes. Now there are exactlynsteps between them. - While
fast.nextisn'tnull, move both one step. When this stops,fastis on the last node. slow.nextis the target. Unlink it:slow.next = slow.next.next.- Return
dummy.next.
The subtle detail is why return dummy.next and not head. If the target was the head, step 4 makes dummy.next point at the second node. head still points at the deleted node. dummy.next is always the true first node.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head) # sits before head, so removing the head is not a special case
slow = fast = dummy
# open a gap of exactly n nodes between slow and fast
for _ in range(n):
fast = fast.next
# slide both until fast is on the last node; slow is then just BEFORE the target
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next # unlink the nth node from the end
return dummy.next # not head: head itself may have been removedclass Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy(0, head); // sits before head, so removing the head is not a special case
ListNode* slow = &dummy;
ListNode* fast = &dummy;
// open a gap of exactly n nodes between slow and fast
for (int i = 0; i < n; i++) {
fast = fast->next;
}
// slide both until fast is on the last node; slow is then just BEFORE the target
while (fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next; // unlink the nth node from the end
return dummy.next; // not head: head itself may have been removed
}
};class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head); // sits before head, so removing the head is not a special case
ListNode slow = dummy;
ListNode fast = dummy;
// open a gap of exactly n nodes between slow and fast
for (int i = 0; i < n; i++) {
fast = fast.next;
}
// slide both until fast is on the last node; slow is then just BEFORE the target
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next; // unlink the nth node from the end
return dummy.next; // not head: head itself may have been removed
}
}/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
const dummy = new ListNode(0, head); // sits before head, so removing the head is not a special case
let slow = dummy;
let fast = dummy;
// open a gap of exactly n nodes between slow and fast
for (let i = 0; i < n; i++) {
fast = fast.next;
}
// slide both until fast is on the last node; slow is then just BEFORE the target
while (fast.next !== null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next; // unlink the nth node from the end
return dummy.next; // not head: head itself may have been removed
};Dry run
1 → 2 → 3 → 4 → 5, n = 2. D is the dummy, so the list is D → 1 → 2 → 3 → 4 → 5.
| Step | slow | fast | Note |
|---|---|---|---|
| start | D | D | |
| gap 1 | D | 1 | |
| gap 2 | D | 2 | gap is now n = 2 |
| slide | 1 | 3 | |
| slide | 2 | 4 | |
| slide | 3 | 5 | fast.next is null, stop |
slow is on 3, so slow.next is 4, the target. Set 3.next = 5. List state: D → 1 → 2 → 3 → 5. Return dummy.next, which is 1.
Now n = 5 on the same list: fast takes 5 steps to reach 5, which is already the last node, so the slide loop never runs. slow is still on D, and D.next = 2 deletes the head. Return dummy.next = 2. No special case needed.
Complexity
- Time: O(n).
fastwalks the list once;slowfollows behind it. - Space: O(1). One dummy node and two pointers.
Edge cases and traps
- Deleting the head (
n= length). Without a dummy you need a special case. With one,slowstays on the dummy and it just works. - A one-node list,
n = 1.slowstays on the dummy,dummy.nextbecomesnull, and you returnnull: an empty list. - Off by one in the gap. If both pointers start on
headinstead of the dummy,slowends on the target instead of before it. DrawD → 1 → 2and check whereslowstops before you code it. - Looping
while fastinstead ofwhile fast.next.fastgoes one step too far, soslowlands on the target, not before it. - Returning
head. Wrong when the head was deleted. Returndummy.next.
Say it in the interview
"I'll do it in one pass with two pointers. I put a dummy node in front of head so deleting the head isn't a special case, and start both pointers there. I move
fastn steps ahead, then move both together untilfastis on the last node. Since the gap stays n,slowis now just before the node to remove, so I setslow.nexttoslow.next.nextand returndummy.next. That's O(n) time and O(1) space."
Follow-ups interviewers ask
- "Is one pass actually faster than two?" Not in big-O; both are O(n). The one-pass version touches each node with
fastonce andslowtrails behind, so total pointer moves are similar. What it shows is the fixed-gap technique. - "Find the middle of the list in one pass." A different speed instead of a fixed gap: move
fasttwo steps for every one step ofslow. Whenfasthits the end,slowis in the middle. - "What if
nmight be larger than the length?" Check fornullwhile opening the gap. Iffastruns off the list before takingnsteps, return the list unchanged.
Practise the same idea
This is Day 47 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free