Remove Nth Node from End of List - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

  • We use two pointers: ahead and behind, both starting at the head of the list.
  • Step 1: Create a gap of n nodes.
    To understand why, imagine removing the 1st node from the end β€” which is the last node in the list.
    To delete it, we need a pointer referring to the node before it, since in a singly linked list we can only remove a node by changing the next pointer of its preceding node.

    Therefore, if we maintain two pointers β€” ahead and behind β€” then ahead must start 1 node ahead of behind. That way, when ahead reaches the last node, behind will be exactly at the node before it β€” which is where we need to be in order to remove the last node.

    Generalizing this idea: If we want to remove the k-th node from the end, ahead should start out k nodes ahead of behind. Then, when ahead reaches the end, behind will be positioned immediately before the node we want to delete.

    🧩 Implementation: Move ahead forward n steps to create this gap. If after these moves ahead becomes null (which happens when n equals the list’s length), it means the node to remove is the head itself β€” handled as a special case by returning head.next.
  • Step 2: Handle the edge case where n equals the list’s length.
    After moving ahead n steps, if it becomes null β€” which happens when n equals the list’s length β€” it means the node to remove is the head itself.
    In that case, we simply return head.next, effectively skipping the first node and making the second node the new head.
  • Step 3: Move both pointers together.
    Move both ahead and behind one step at a time until ahead reaches the last node. At that moment, behind is positioned exactly one node before the node that needs to be deleted.
  • Step 4: Remove the target node.
    Skip over the target node by setting behind.next = behind.next.next, effectively removing the N-th node from the end of the list.
  • Step 5: Return the updated list.
    The modified list starts at head, or head.next if the first node was removed.

Time Complexity

O(L) β€” where L is the list’s length. Each node is visited at most once by the ahead pointer and at most once by the behind pointer.

Space Complexity

O(1) β€” only a few pointer variables are used.

Visucodize editorial solution titled JS Solution for LeetCode's Remove Nth Node from End of List coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/remove-nth-node-from-end-of-list.