Remove Nth Node From End of List solution explained
To remove the nth node from the end of a linked list in one pass, start two pointers at a sentinel node placed before the head, move the front pointer n + 1 steps ahead, then move both together until the front one falls off the end. The back pointer then sits just before the node to delete, so one pointer change removes it in O(n) time and O(1) extra memory.
By Evin JohnPublished 6 min read
The task in plain words
You get the head of a singly linked list and a whole number n. Count positions from the tail: the last node is first from the end, the one before it is second, and so on. Unlink the node at position n from the end and return the head of the shortened list. Usually you may assume n is at least 1 and no larger than the list length.
| List | n | Result | Why |
|---|---|---|---|
| 4 → 8 → 15 → 16 → 23 | 2 | 4 → 8 → 15 → 23 | 16 is second from the end |
| 4 → 8 → 15 → 16 → 23 | 5 | 8 → 15 → 16 → 23 | n equals the length, so the head goes |
| 7 | 1 | empty list | The only node is removed |
| 1 → 2 | 1 | 1 | The tail is removed and 1 becomes the new tail |
Before coding, ask whether n is always valid. If it might be zero or larger than the list, decide with the interviewer whether to return the list unchanged or raise an error.
Why interviewers like it
The problem is short, but it checks three linked-list habits at once: pointer movement without losing nodes, the off-by-one between the node you delete and the node before it, and clean handling of a deleted head. The usual follow-up is to do it in a single pass, which leads to the two-pointer gap idea. That idea returns later in cycle detection, middle-of-list and palindrome-list questions.
Follow-ups you may hear
- Return the value instead of deleting it. Same walk, but stop the front pointer only n steps ahead and return the back pointer's value.
- Find the middle node. Use a slow pointer moving one step and a fast pointer moving two.
- Delete the nth node from the end of a doubly linked list. Same search; the unlink step also fixes the next node's back pointer.
- What if n can exceed the length? Detect the front pointer reaching the end early and stop before dereferencing nothing.
First answer: count, then walk
Walk the list once to count its length L. The target sits at index L minus n when counting from zero at the head. If that index is zero, return the second node. Otherwise walk to index L minus n minus 1 and skip over the next node. Two passes, O(n) time and O(1) memory. That is already optimal in big-O terms, so say so; the one-pass version is about elegance and about showing you know the gap technique.
def remove_nth_by_counting(head, n):
length, node = 0, head
while node:
length += 1
node = node.next
target = length - n # index from the front
if target == 0:
return head.next
node = head
for _ in range(target - 1): # stop just before the target
node = node.next
node.next = node.next.next
return headOne pass with a gap between two pointers
Put a sentinel node in front of the head. Start both pointers on it. Move the lead pointer n + 1 times. Now exactly n nodes sit strictly between the trail pointer and the lead pointer. Advance both together until lead becomes empty. At that moment the n nodes after trail are the last n nodes of the list, so trail.next is the one to drop. Because trail started on the sentinel, deleting the original head is no special case at all.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def remove_nth_from_end(head, n):
sentinel = Node(0, head)
lead = trail = sentinel
for _ in range(n + 1): # leave n nodes between trail and lead
lead = lead.next
while lead:
lead = lead.next
trail = trail.next
trail.next = trail.next.next # trail is just before the node to drop
return sentinel.nextclass ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function removeNthFromEnd(head, n) {
const sentinel = new ListNode(0, head);
let lead = sentinel;
let trail = sentinel;
for (let i = 0; i <= n; i++) lead = lead.next;
while (lead !== null) {
lead = lead.next;
trail = trail.next;
}
trail.next = trail.next.next;
return sentinel.next;
}Trace the first example with n = 2. After three moves, lead is on 15 and trail on the sentinel. Moving both three more times takes lead off the end and leaves trail on 15, so 16 is skipped. Return sentinel.next, not head, because the head may have been the node removed.
Complexity
| Approach | Time | Extra memory | Passes |
|---|---|---|---|
| Count, then walk | O(n) | O(1) | Two |
| Copy nodes into an array, then unlink by index | O(n) | O(n) | One, plus the array |
| Two pointers with a gap | O(n) | O(1) | One |
Cases to test
- n equal to the list length, which deletes the head.
- n equal to 1, which deletes the tail.
- A single-node list, which becomes empty.
- A two-node list with each value of n.
- A long list with n in the middle, to confirm the gap math rather than lucky edges.
Slips that cost time
- Moving lead only n steps when both start on the sentinel. Trail then lands on the target itself, which you cannot unlink in a singly linked list.
- Starting both pointers at the head without a sentinel and then crashing when the head must go.
- Returning head at the end even though it was just deleted.
- In languages with manual memory, forgetting to free the removed node, or freeing it before reading its next pointer.
How to explain it out loud
Fictional example
- Candidate
- Counting first and walking second works and is linear, so I could stop there. For a single pass, I keep two pointers a fixed distance apart.
- Candidate
- Both start on a dummy node before the head. I move the front one n plus one steps, so when it runs off the end, the back one is right before the node to delete. One pointer change removes it.
- Candidate
- The dummy means removing the head needs no special branch, and I return dummy.next. Time is linear and memory is constant.
Where to go next
Add Two Numbers uses the same sentinel trick to build a new list. Reverse Nodes in k-Group is the harder pointer workout. Two pointers at different speeds, rather than a fixed gap, are the heart of Find the Duplicate Number.
Practicing with Natively
Linked-list bugs hide in the off-by-one, so it helps to talk through a trace. Natively, a desktop app for Mac and Windows, can read this kind of problem from a screenshot while you practice and outline the gap approach plus the cases to try, which you can compare with your own trace. If you practice out loud, its transcript of the session shows whether you explained why the lead pointer moves n + 1 steps. Read about the AI interview assistant.
Questions people ask
How do you remove the nth node from the end in one pass?
Put a sentinel before the head, start two pointers on it, move the first n + 1 steps ahead, then move both until the first falls off the end. The second pointer is now just before the node to remove.
Why use a dummy node in Remove Nth Node From End of List?
Because the node removed may be the head. Starting from a node placed before the head means the same unlink step works in every case, and you return dummy.next.
What is the time complexity of removing the nth node from the end?
O(n) time and O(1) extra memory, for both the two-pass counting version and the one-pass two-pointer version.
Is the two-pass solution acceptable?
Yes, it has the same big-O cost. Interviewers often ask for one pass as a follow-up to see whether you know the gap technique.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
