DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 19. Remove Nth Node From End of List

You're given a singly linked list. Your task is to remove the nth node from the end and return the updated head of the list.


šŸ’” Approach

To solve this efficiently in one pass, we use the two-pointer technique:

  1. Dummy Node:

    • Add a dummy node pointing to the head. This simplifies edge cases like removing the first node.
  2. Two Pointers:

    • Initialize two pointers: left at the dummy node and right at the head.
    • Move right ahead by n steps. This ensures the gap between left and right is n nodes.
    • Now, move both left and right one step at a time until right reaches the end of the list.
  3. Remove the Node:

    • At this point, left.next points to the node that needs to be removed.
    • Update left.next = left.next.next to skip the nth node.
  4. Return:

    • Return dummy.next which is the new head of the modified list.

Diagrams

Image description

Image description

Image description

Image description

āœ… Code (JavaScript)

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function (head, n) {
    let dummy = new ListNode(0, head); // Step 1: Dummy node
    let left = dummy;
    let right = head;

    // Step 2: Move right n steps ahead
    while (n > 0 && right) {
        right = right.next;
        n--;
    }

    // Step 3: Move both pointers until right reaches the end
    while (right) {
        left = left.next;
        right = right.next;
    }

    // Step 4: Remove the nth node
    left.next = left.next.next;

    return dummy.next;
};
Enter fullscreen mode Exit fullscreen mode

ā±ļø Time & Space Complexity

  • Time Complexity: O(L)

    • L is the number of nodes in the list.
    • We make a single pass through the list using the two-pointer technique.
  • Space Complexity: O(1)

    • No extra space is used apart from a few pointers.

Top comments (0)