15% off all plans & roadmaps Use code
See plansRemove Nth Node From End of List
- LeetCode 19
- Medium
- Two Pointers
- Fixed Separation (Nth Node from End)
Updated
TL;DR: Delete the nth node counted from the tail of a singly linked list. Keep two pointers a fixed gap apart so that when the front pointer falls off the end, the back pointer sits right before the node to remove.
Problem
You are given the head of a singly linked list. Remove the nth node counted from the end of the list and return the head of the resulting list.
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 list has
sznodes. 1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Constraints that matter
1 <= n <= szmeans the target node always exists, so you never need to handle n larger than the list. You do not need a bounds check before moving the front pointer.ncan equalsz, which means the head itself can be the node to delete. You need a way to delete the head without a special case, and a dummy node gives you that.sz <= 30lets even an O(L^2) approach pass here. Interviewers still expect the O(L) one-pass answer, so treat the small limit as a hint about the grader, not the target.- The list is singly linked, so you cannot walk backward from the end. That is why the problem asks you to measure position from the tail with pointer tricks.
Hints
Hint 1
This is a two pointers problem with a fixed separation.
Hint 2
Check every possible predecessor and ask whether exactly n nodes follow it.
Solution
Intuition
This is a two pointers problem with a fixed separation. The list only lets you walk forward, so you cannot start at the tail and count back n nodes. The question is how to know where the tail is while you are still near the head.
Picture two runners on a track who keep a fixed gap of n + 1 steps between them. When the front runner reaches the end of the track, the back runner stands on the node before the one to remove.
The answer is to carry a ruler with you. Put one pointer fast ahead of another pointer slow by a constant number of nodes. Both move one step at a time. When fast reaches the end, slow is exactly that many nodes from the end, because the distance between them never changed.
To delete a node in a singly linked list, you must stand on the node before it and rewrite its next. So you want slow to stop on the predecessor of the target. That means the gap between the pointers must be n + 1 nodes when fast is null, not n.
One more detail removes every special case. If the target is the head, it has no predecessor. Add a dummy node in front of the head, start both pointers there, and the head gets a predecessor like any other node. Returning dummy.next then gives the right head in all cases, including an empty result.
Worked example
Input: head = [1, 2, 3, 4, 5], n = 2 Output: [1, 2, 3, 5] Explanation: Counting from the tail, node 5 is first and node 4 is second. Removing node 4 links node 3 straight to node 5, which leaves 1, 2, 3, 5.
Approach 1: Brute force: count the tail for every node
Check every possible predecessor and ask whether exactly n nodes follow it. The predecessor of the target is the node whose next chain contains n nodes. Walk from a dummy node, and at each position count the nodes after it by walking to the end.
This is the most literal reading of the problem. It needs no length variable and no clever trick, only a nested scan.
Steps
- Create a dummy node that points to
head, and setpto the dummy. - While
pis notnull, walk a second pointerqfromp.nextto the end and count the nodes you pass. - If the count equals
n, thenp.nextis the target. Setp.next = p.next.nextand stop. - Otherwise move
pone node forward and repeat the count. - Return
dummy.next.
Dry run
Use [1,2,3,4,5] with n = 2. The dummy node is D.
p = D: nodes after it are 1,2,3,4,5, so the count is 5. Not 2.p = 1: nodes after it are 2,3,4,5, so the count is 4. Not 2.p = 2: nodes after it are 3,4,5, so the count is 3. Not 2.p = 3: nodes after it are 4,5, so the count is 2. Match.
Set 3.next = 5. The list is [1,2,3,5]. The inner scans walked 5 + 4 + 3 + 2 = 14 nodes in total.
Complexity
| Time | O(L^2) |
|---|---|
| Space | O(1) |
Let L be the number of nodes. The outer loop runs up to L + 1 times, and each iteration runs an inner scan of up to L nodes, so the work is bounded by L * L. In the worst case, n = L, the match happens at the dummy after one scan, but n = 1 forces roughly L^2 / 2 steps. You only keep a few pointers and a counter, so the space is O(1).
PythonTested in our runner
from typing import Optional
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
p = dummy
while p:
# count how many nodes follow p
count = 0
q = p.next
while q:
count += 1
q = q.next
if count == n:
p.next = p.next.next
break
p = p.next
return dummy.next
JavaTested in our runner
import java.util.*;
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode p = dummy;
while (p != null) {
// count how many nodes follow p
int count = 0;
ListNode q = p.next;
while (q != null) {
count++;
q = q.next;
}
if (count == n) {
p.next = p.next.next;
break;
}
p = p.next;
}
return dummy.next;
}
}
C++Tested in our runner
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy(0, head);
ListNode* p = &dummy;
while (p != nullptr) {
// count how many nodes follow p
int count = 0;
ListNode* q = p->next;
while (q != nullptr) {
count++;
q = q->next;
}
if (count == n) {
p->next = p->next->next;
break;
}
p = p->next;
}
return dummy.next;
}
};
JavaScriptTested in our runner
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
const dummy = new ListNode(0, head);
let p = dummy;
while (p !== null) {
// count how many nodes follow p
let count = 0;
let q = p.next;
while (q !== null) {
count++;
q = q.next;
}
if (count === n) {
p.next = p.next.next;
break;
}
p = p.next;
}
return dummy.next;
};
GoTested in our runner
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummy := &ListNode{Val: 0, Next: head}
p := dummy
for p != nil {
// count how many nodes follow p
count := 0
for q := p.Next; q != nil; q = q.Next {
count++
}
if count == n {
p.Next = p.Next.Next
break
}
p = p.Next
}
return dummy.Next
}
C#Tested in our runner
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode p = dummy;
while (p != null) {
// count how many nodes follow p
int count = 0;
ListNode q = p.next;
while (q != null) {
count++;
q = q.next;
}
if (count == n) {
p.next = p.next.next;
break;
}
p = p.next;
}
return dummy.next;
}
}
Approach 2: Two passes: measure the length first
What's slow: the brute force re-counts the same tail again and again. The count after node 3 is the count after node 2 minus one, yet you walk it from scratch each time.
The insight that fixes it: the length L of the list is the only number you need. The target sits at index L - n counting from 0, so its predecessor is L - n steps from the dummy node. Measure L once, then walk L - n steps once.
Steps
- Walk the list from
headand count the nodes intolength. - Create a dummy node that points to
head, and setpto the dummy. - Move
pforwardlength - ntimes. It now sits on the predecessor of the target. - Set
p.next = p.next.nextto unlink the target. - Return
dummy.next.
Dry run
Use [1,2,3,4,5] with n = 2.
First pass: counting gives length = 5.
Second pass: length - n = 3, so move p three times from the dummy. The path is D, then 1, then 2, then 3. Now p is on node 3.
Set 3.next = 5. The result is [1,2,3,5]. The total work was 5 steps to count and 3 steps to walk, which is 8 steps against 14 for the brute force.
Complexity
| Time | O(L) |
|---|---|
| Space | O(1) |
Let L be the number of nodes. The counting pass visits each node once, which is L steps. The second pass takes L - n steps, which is at most L. The total is at most 2L, so the time is O(L). You store only a counter and a few pointers, so the space is O(1).
PythonTested in our runner
from typing import Optional
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
# first pass: count the nodes
length = 0
node = head
while node:
length += 1
node = node.next
# second pass: stop on the predecessor of the target
dummy = ListNode(0, head)
p = dummy
for _ in range(length - n):
p = p.next
p.next = p.next.next
return dummy.next
JavaTested in our runner
import java.util.*;
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// first pass: count the nodes
int length = 0;
ListNode node = head;
while (node != null) {
length++;
node = node.next;
}
// second pass: stop on the predecessor of the target
ListNode dummy = new ListNode(0, head);
ListNode p = dummy;
for (int i = 0; i < length - n; i++) {
p = p.next;
}
p.next = p.next.next;
return dummy.next;
}
}
C++Tested in our runner
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// first pass: count the nodes
int length = 0;
for (ListNode* node = head; node != nullptr; node = node->next) {
length++;
}
// second pass: stop on the predecessor of the target
ListNode dummy(0, head);
ListNode* p = &dummy;
for (int i = 0; i < length - n; i++) {
p = p->next;
}
p->next = p->next->next;
return dummy.next;
}
};
JavaScriptTested in our runner
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
// first pass: count the nodes
let length = 0;
for (let node = head; node !== null; node = node.next) {
length++;
}
// second pass: stop on the predecessor of the target
const dummy = new ListNode(0, head);
let p = dummy;
for (let i = 0; i < length - n; i++) {
p = p.next;
}
p.next = p.next.next;
return dummy.next;
};
GoTested in our runner
func removeNthFromEnd(head *ListNode, n int) *ListNode {
// first pass: count the nodes
length := 0
for node := head; node != nil; node = node.Next {
length++
}
// second pass: stop on the predecessor of the target
dummy := &ListNode{Val: 0, Next: head}
p := dummy
for i := 0; i < length-n; i++ {
p = p.Next
}
p.Next = p.Next.Next
return dummy.Next
}
C#Tested in our runner
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// first pass: count the nodes
int length = 0;
for (ListNode node = head; node != null; node = node.next) {
length++;
}
// second pass: stop on the predecessor of the target
ListNode dummy = new ListNode(0, head);
ListNode p = dummy;
for (int i = 0; i < length - n; i++) {
p = p.next;
}
p.next = p.next.next;
return dummy.next;
}
}

Solution pattern
Fixed Separation (Nth Node from End)
Part of Two Pointers
Approach 3: One pass with two pointersOptimalFixed Separation (Nth Node from End)
What's slow: the two-pass method reads the list twice. The first pass exists only to learn L, and the follow-up asks you to avoid that.
The insight that fixes it: keep two pointers a fixed n + 1 nodes apart. When fast falls off the end, slow is n + 1 nodes behind it, which is the predecessor of the target. You never need L, because the gap measures the distance to the tail for you.
Start both pointers on a dummy node. Move fast forward n + 1 times to build the gap. Then move both together until fast is null.
Steps
- Create a dummy node that points to
head. Setslowandfastto the dummy. - Move
fastforwardn + 1times. The gap betweenslowandfastis now n + 1 nodes. - While
fastis notnull, moveslowandfastone node forward each. - When the loop ends,
slowis the predecessor of the target. Setslow.next = slow.next.next. - Return
dummy.next.
Dry run
Use [1,2,3,4,5] with n = 2, so the gap is n + 1 = 3. The dummy node is D.
| Step | Action | slow | fast |
|---|---|---|---|
| 0 | start | D | D |
| 1 | gap move 1 | D | 1 |
| 2 | gap move 2 | D | 2 |
| 3 | gap move 3 | D | 3 |
| 4 | slide | 1 | 4 |
| 5 | slide | 2 | 5 |
| 6 | slide | 3 | null |
fast is null, so the loop stops with slow on node 3. Its next is node 4, the second node from the end. Set 3.next = 5. Return dummy.next, which is the list [1,2,3,5].
Complexity
| Time | O(L) |
|---|---|
| Space | O(1) |
Let L be the number of nodes. The fast pointer moves from the dummy to null, which is L + 1 steps in total, split between the gap phase and the slide phase. The slow pointer moves only during the slide phase, so it takes L - n steps. The list is read once, so the time is O(L), and memory holds only the dummy node and two pointers, so the space is O(1).
PythonTested in our runner
from typing import Optional
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
slow = dummy
fast = dummy
# build a gap of n + 1 nodes between slow and fast
for _ in range(n + 1):
fast = fast.next
# slide both until fast falls off the end
while fast:
slow = slow.next
fast = fast.next
# slow is the predecessor of the target
slow.next = slow.next.next
return dummy.next
JavaTested in our runner
import java.util.*;
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode slow = dummy;
ListNode fast = dummy;
// build a gap of n + 1 nodes between slow and fast
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
// slide both until fast falls off the end
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
// slow is the predecessor of the target
slow.next = slow.next.next;
return dummy.next;
}
}
C++Tested in our runner
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy(0, head);
ListNode* slow = &dummy;
ListNode* fast = &dummy;
// build a gap of n + 1 nodes between slow and fast
for (int i = 0; i <= n; i++) {
fast = fast->next;
}
// slide both until fast falls off the end
while (fast != nullptr) {
slow = slow->next;
fast = fast->next;
}
// slow is the predecessor of the target
slow->next = slow->next->next;
return dummy.next;
}
};
JavaScriptTested in our runner
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
const dummy = new ListNode(0, head);
let slow = dummy;
let fast = dummy;
// build a gap of n + 1 nodes between slow and fast
for (let i = 0; i <= n; i++) {
fast = fast.next;
}
// slide both until fast falls off the end
while (fast !== null) {
slow = slow.next;
fast = fast.next;
}
// slow is the predecessor of the target
slow.next = slow.next.next;
return dummy.next;
};
GoTested in our runner
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummy := &ListNode{Val: 0, Next: head}
slow := dummy
fast := dummy
// build a gap of n + 1 nodes between slow and fast
for i := 0; i <= n; i++ {
fast = fast.Next
}
// slide both until fast falls off the end
for fast != nil {
slow = slow.Next
fast = fast.Next
}
// slow is the predecessor of the target
slow.Next = slow.Next.Next
return dummy.Next
}
C#Tested in our runner
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode slow = dummy;
ListNode fast = dummy;
// build a gap of n + 1 nodes between slow and fast
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
// slide both until fast falls off the end
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
// slow is the predecessor of the target
slow.next = slow.next.next;
return dummy.next;
}
}
Common mistakes
- Skipping the dummy node and starting
slowathead. Whennequals the list length, the head is the target and has no predecessor, soslow.next = slow.next.nextremoves the wrong node. Start both pointers at a dummy node and returndummy.next. - Moving
fastonlynsteps, as infor i in range(n). Thenslowends on the target instead of its predecessor, and you cannot unlink it in a singly linked list. Movefastn + 1steps from the dummy. - Returning
headinstead ofdummy.next. When the head is removed,headstill points at the deleted node and the answer is wrong. Always returndummy.next. - Looping with
while fast.next:after a gap of n + 1. The loop stops one step early, soslowlands on the target and not its predecessor. Usewhile fast:with the n + 1 gap, orwhile fast.next:with a gap of n. - Computing the walk length as
length - n - 1while starting from a dummy node. The dummy already adds one step, so you stop one node too early. From the dummy you walk exactlylength - nsteps. - Dereferencing
slow.next.nextwhen the list has been shortened by an earlier edit, or deleting before the loop finishes. Do the unlink once, afterslowis in its final place.
Edge cases
head = [1], n = 1: the only node is removed and the answer is an empty list. The dummy approach returnsdummy.next, which isnull.head = [1,2], n = 2: the target is the head. The gap phase movesfastthree times and ends atnull,slowstays on the dummy, and the result is[2].head = [1,2], n = 1: the target is the tail.slowends on node 1, and itsnextbecomesnull, giving[1].head = [1,2,3,4,5], n = 5:nequals the length, so the head goes. The result is[2,3,4,5].- Duplicate values such as
[7,7,7], n = 2: you remove by position, not by value, so the answer is[7,7]and the middle node is the one unlinked. - Maximum size, 30 nodes with
n = 1: the tail is removed. All three approaches finish instantly, and the one-pass code never reads pastnull.
Follow-ups interviewers ask
- Can you do it in one pass over the list?
- Yes, and that is the third approach. Keep
fastn + 1 nodes ahead ofslow, both starting at a dummy node. Whenfastreachesnull,slowis on the predecessor of the target. The list is read once and the extra space is O(1). - Can you solve it with recursion?
- Yes. Recurse to the end, and as the calls return, count back from the tail. When the counter reaches n, the current call's parent unlinks the node. It is one pass in time, but the call stack uses O(L) space, so it is worse than the two-pointer version on memory.
- What if n can be larger than the list length?
- Then the fast pointer would hit
nullwhile building the gap. Check forfast == nullinside the gap loop and returnheadunchanged, since no node qualifies. The constraints here guaranteen <= sz, but production code should guard it.
Remove Nth Node From End of List FAQ
What is the time complexity of Remove Nth Node From End of List?
The best solution runs in O(L) time, where L is the number of nodes. The fast pointer makes L + 1 moves and the slow pointer makes L - n moves, so the list is read once. The brute force that recounts the tail for each node takes O(L^2).
Why use two pointers for Remove Nth Node From End of List?
A singly linked list cannot be walked backward, so you cannot measure from the tail directly. Two pointers with a fixed gap let you measure from the tail while moving forward. When the front pointer reaches null, the back pointer is a known distance from the end.
Why do you need a dummy node in LeetCode 19?
The head can be the node to delete, and the head has no predecessor. A dummy node placed before it gives every real node a predecessor. It also makes the empty-list result fall out naturally, because dummy.next is null.
Can Remove Nth Node From End of List be solved in O(1) extra space?
Yes. Both the two-pass count and the one-pass two-pointer solutions use only a dummy node, two pointers and maybe a counter. Recursion is the only common approach that needs O(L) extra space, because of the call stack.
Why does the gap have to be n + 1 and not n?
With a gap of n, slow lands on the target when fast is null. To unlink a node you must change the next of the node before it. A gap of n + 1 puts slow one node earlier, exactly on that predecessor.
Is the one-pass solution really faster than two passes?
Both are O(L). The one-pass solution makes about L + 1 moves with fast plus L - n with slow, so the pointer work is similar to the two-pass total. The gain is that the list is read once, which matters when reading nodes is costly, as with a stream or a slow store.
Asked at
See which companies ask this — Pro
Related problems
- Delete the Middle Node of a Linked List · same technique: Fixed Separation (Nth Node from End)
- Middle of the Linked List · same technique: Fixed Separation (Nth Node from End)
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers
- Reverse Integer · same pattern: Two Pointers
- Two Sum II - Input Array Is Sorted · same pattern: Two Pointers