Remove Nth Node from End
Medium
Linked ListTwo Pointers
Problem
Given the head of a singly linked list and an integer n, remove the nth node from the end and return the (possibly new) head.
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
- 1 ≤ length ≤ 30
- 1 ≤ n ≤ length
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def removeNthFromEnd(self, 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
Java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = 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;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Remove Nth Node from End interactively → ← All solutions