19. Remove Nth Node From End of List

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.

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.