Remove Nth Node From End of List [Medium]

22 Sep 2026 2 min read
0
Remove Nth Node From End of List requires removing the nth node from the end of a singly linked list.

Problem

Given the head of a linked list, remove the nth node from the end of the list and return its head. The list should be modified in-place using constant extra space.

Example(s)

Example 1

Input
head = [1,2,3,4,5]
n = 2
Output
[1,2,3,5]

Example 2

Input
head = [1]
n = 1
Output
[]

Solution

This problem uses Two Pointer technique. Use a fast and slow pointer with a dummy node before the head. Move the fast pointer n steps ahead, then move both pointers together until fast reaches the end.

At that point, slow.next is the node that needs to be removed. The dummy node also makes it easy to remove the head when the first node is the target.
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode slow = dummy;
        ListNode fast = dummy;

        // Move fast n steps ahead.
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }

        // Move both pointers until fast reaches the end.
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }

        // Remove the nth node from the end.
        slow.next = slow.next.next;

        return dummy.next;
    }
}

Complexity

The time complexity is O(n)O(1) because only a few pointers are used.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion