15% off all plans & roadmaps Use code

See plans

Remove Nth Node From End of List

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 sz nodes.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Constraints that matter

  • 1 <= n <= sz means 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.
  • n can equal sz, 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 <= 30 lets 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Create a dummy node that points to head, and set p to the dummy.
  2. While p is not null, walk a second pointer q from p.next to the end and count the nodes you pass.
  3. If the count equals n, then p.next is the target. Set p.next = p.next.next and stop.
  4. Otherwise move p one node forward and repeat the count.
  5. 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

TimeO(L^2)
SpaceO(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

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

  1. Walk the list from head and count the nodes into length.
  2. Create a dummy node that points to head, and set p to the dummy.
  3. Move p forward length - n times. It now sits on the predecessor of the target.
  4. Set p.next = p.next.next to unlink the target.
  5. 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

TimeO(L)
SpaceO(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
Fixed Separation (Nth Node from End) pattern infographic for Remove Nth Node From End of List

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

  1. Create a dummy node that points to head. Set slow and fast to the dummy.
  2. Move fast forward n + 1 times. The gap between slow and fast is now n + 1 nodes.
  3. While fast is not null, move slow and fast one node forward each.
  4. When the loop ends, slow is the predecessor of the target. Set slow.next = slow.next.next.
  5. 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.

StepActionslowfast
0startDD
1gap move 1D1
2gap move 2D2
3gap move 3D3
4slide14
5slide25
6slide3null

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

TimeO(L)
SpaceO(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

Common mistakes

  • Skipping the dummy node and starting slow at head. When n equals the list length, the head is the target and has no predecessor, so slow.next = slow.next.next removes the wrong node. Start both pointers at a dummy node and return dummy.next.
  • Moving fast only n steps, as in for i in range(n). Then slow ends on the target instead of its predecessor, and you cannot unlink it in a singly linked list. Move fast n + 1 steps from the dummy.
  • Returning head instead of dummy.next. When the head is removed, head still points at the deleted node and the answer is wrong. Always return dummy.next.
  • Looping with while fast.next: after a gap of n + 1. The loop stops one step early, so slow lands on the target and not its predecessor. Use while fast: with the n + 1 gap, or while fast.next: with a gap of n.
  • Computing the walk length as length - n - 1 while starting from a dummy node. The dummy already adds one step, so you stop one node too early. From the dummy you walk exactly length - n steps.
  • Dereferencing slow.next.next when the list has been shortened by an earlier edit, or deleting before the loop finishes. Do the unlink once, after slow is 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 returns dummy.next, which is null.
  • head = [1,2], n = 2: the target is the head. The gap phase moves fast three times and ends at null, slow stays on the dummy, and the result is [2].
  • head = [1,2], n = 1: the target is the tail. slow ends on node 1, and its next becomes null, giving [1].
  • head = [1,2,3,4,5], n = 5: n equals 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 past null.

Follow-ups interviewers ask

Can you do it in one pass over the list?
Yes, and that is the third approach. Keep fast n + 1 nodes ahead of slow, both starting at a dummy node. When fast reaches null, slow is 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 null while building the gap. Check for fast == null inside the gap loop and return head unchanged, since no node qualifies. The constraints here guarantee n <= 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

Practise it