19. Remove Nth Node From End of List
Medium
|
Linked List
Two Pointers
|
Solved: Mar 15, 2026
View on LeetCode →
View on NeetCode →
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Problem Description
You are given the beginning of a linked list head, and an integer n.
Remove the nth node from the end of the list and return the beginning of the list.
Example 1:
Input: head = [1,2,3,4], n = 2
Output: [1,2,4]
Example 2:
Input: head = [5], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 2
Output: [2]
Constraints:
- The number of nodes in the list is
sz. 1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Approach
Use the “fast and slow pointer” approach with a dummy node.
- Create a
prevdummy node pointing toheadto handle cases where the head itself needs to be removed. - Initialize both
slowandfastpointers at theprevdummy node. - Advance the
fastpointer byn + 1steps. By doing this, the gap betweenslowandfastbecomesn + 1. - Move both
slowandfastpointers one step at a time untilfastreachesnull(the end of the list). At this point, theslowpointer will be exactly at the node before the target node to be deleted. - Skip the target node by updating
slow.nexttoslow.next.next. - Return
prev.nextas the new head of the list.
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode prev = new ListNode(0, head);
ListNode slow = prev;
ListNode fast = prev;
int t = n;
while(t>=0){
fast = fast.next;
t--;
}
while(fast != null){
slow = slow.next;
fast = fast.next;
}
slow.next= slow.next.next;
return prev.next;
}
}