Algo-Sim › Linked Lists

Remove Nth Node From End of List

Medium · Linked Lists · step through it in Java, Python and C++ on your own input

Remove the nth node from the end in one pass: open a gap of n between two pointers, then slide both until fast hits the tail.

Problem

Given the head of a linked list and n, remove the nth node counted from the end (the last node is 1st) and return the head of the resulting list.

Constraints

Edge cases to test

Follow-up questions

Why use a dummy node?
Removing the head would otherwise need a special case; the dummy gives every node a predecessor.
Two passes or one?
Counting the length first is also O(n); the gap trick finds the node in one pass.

Solution

Java

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(0, head);
    ListNode fast = dummy, slow = dummy;
    for (int i = 0; i < n; i++) {
        fast = fast.next;
    }
    while (fast.next != null) {
        fast = fast.next;
        slow = slow.next;
    }
    slow.next = slow.next.next;
    return dummy.next;
}

Python

def remove_nth_from_end(head, n):
    dummy = ListNode(0, head)
    fast = slow = dummy
    for _ in range(n):
        fast = fast.next
    while fast.next:
        fast = fast.next
        slow = slow.next
    slow.next = slow.next.next
    return dummy.next

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *dummy = new ListNode(0, head);
        ListNode *fast = dummy, *slow = dummy;
        for (int i = 0; i < n; i++) {
            fast = fast->next;
        }
        while (fast->next != nullptr) {
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return dummy->next;
    }
};

More Linked Lists problems