LeetCode 19: Remove Nth Node From End of List Solution
Master LeetCode problem 19 (Remove Nth Node From End of List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
19. Remove Nth Node From End of List
Problem Explanation
Explanation
To remove the nth node from the end of a linked list, we can use a two-pointer approach. We initialize two pointers, fast
and slow
, both pointing to the head of the linked list. We move the fast
pointer to the nth node from the beginning. Then, we move both pointers simultaneously until the fast
pointer reaches the end of the list. At this point, the slow
pointer will be pointing to the node just before the node to be removed. We update the slow
pointer to skip the nth node from the end, effectively removing it from the list.
Solution Code
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 19 (Remove Nth Node From End of List)?
This page provides optimized solutions for LeetCode problem 19 (Remove Nth Node From End of List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 19 (Remove Nth Node From End of List)?
The time complexity for LeetCode 19 (Remove Nth Node From End of List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 19 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 19 in Java, C++, or Python.