← Whiteboard questions

Remove Nth Node From End of List

Remove the nth node from the end of a linked list

DSA, Medium, Linked List

Which structure or algorithm, and what does it cost.

You get a linked list and a whole number n. Count from the end of the list, where the last node is number 1. Remove node number n and return the list that is left. A node has val and next. Your code gets the first node and n, and returns the first node of the result. The examples write the list as its values in order, only to keep them short. You do not know the length in advance. Read the list only once.

Examples

Input values = [4, 8, 15, 16, 23, 42], n = 2
Output [4, 8, 15, 16, 42]
Why the second node from the end holds 23, so 23 is removed.
Input values = [9], n = 1
Output []
Why the only node is also the last one, so the list becomes empty.
Input values = [5, 6, 7], n = 3
Output [6, 7]
Why the third node from the end is the first node, so the head changes.

Constraints

Your answer must contain

Target Aim for O(n) time in one pass and O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

To delete a node you need the node just before it. Think about how far that node is from the end of the list.

Hint 2 the approach

The distance from the end never changes while you walk. Two pointers a fixed number of steps apart reach that spot together.

Hint 3 the key step

Start both pointers on a dummy node in front of the list. Move one pointer n steps ahead. Then move both until the front one stops on the last node.

Walkthrough

Full walkthrough brute force to best

Brute force

Walk the list once to count its length, call it L. Walk again L - n steps to reach the node before the target, and unlink the target. This works in O(n) time and O(1) memory, but it reads the list twice and needs a special case when the head is removed.

Best method

Put a dummy node in front of the list. Start two pointers, lead and lag, on the dummy. Move lead forward n steps, so the gap between them is n nodes. Then move both one step at a time until lead is on the last node. The gap is still n, so lag is exactly on the node before the one to remove. Set the next link of lag past the target. The dummy means removing the head needs no special case, because lag can stop on the dummy. The answer is the node after the dummy. The list is read once.

Hand trace

Run on [4, 8, 15, 16, 23, 42] with n = 2. Both pointers start on the dummy. Move lead 2 steps: it is on 8. Now move both until lead is on 42. Lead goes 15, 16, 23, 42, and lag goes 4, 8, 15, 16. Lag is on 16, the node before 23. Link 16 to 42. The result is [4, 8, 15, 16, 42].

Code

class Node:
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt
def remove_nth_from_end(head, n):   # head is the first node
    dummy = Node(0, head)           # dummy: removing the first node needs no special case
    lead = lag = dummy
    for _ in range(n):              # open a gap of n nodes
        lead = lead.next
    while lead.next:                # move both until lead is on the last node
        lead, lag = lead.next, lag.next
    lag.next = lag.next.next        # lag is the node before the target
    return dummy.next               # the first node of the result

# Test helper, not part of the answer: builds a list of nodes from values and reads it back.
def build(values):
    head = None
    for v in reversed(values):
        head = Node(v, head)
    return head
def to_values(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out

Time and memory

O(n) time in a single pass, because lead visits each node once. O(1) extra memory: the dummy and two pointers.

Common mistakes

  • Starting both pointers on the head. Then you cannot reach the node before the head, so removing the head breaks. Start on a dummy node.
  • Moving lead one step too few or too many. Check with n = 1: lag must stop on the node before the last one.
  • Removing the node lag stands on. Lag stands on the node before the target, and its link must skip the next node.

Related problems

More Linked List problems
Remove Nth Node From End of List: walkthrough and solution