noodleProblems/
Remove Nth Node From End of List
#29

Remove Nth Node From End of List

AlgorithmmediumLinked ListTwo Pointers

Given the head of a singly linked list and an integer n, remove the n-th node counting from the **end** of the list and return the head of the resulting list.

n is 1-indexed from the end: n = 1 removes the last node, n = 2 removes the second-to-last, and so on. n is always a valid position, so 1 <= n <= length. If the list had a single node, removing it leaves the empty list.

Lists are shown in array notation for readability — [1, 2, 3, 4, 5] is the chain 1 -> 2 -> 3 -> 4 -> 5, and the empty list is [].

Example cases

  • remove 2nd from end
    in head = [1,2,3,4,5]12345nulln = 2
    out [1,2,3,5]1235null
    Counting from the end, the 2nd node is `4`; removing it leaves `1 -> 2 -> 3 -> 5`.
  • single node
    in head = [1]1nulln = 1
    out []null
    The only node is the 1st from the end; removing it leaves the empty list.
  • remove the head
    in head = [1,2]12nulln = 2
    out [2]2null
    With 2 nodes, the 2nd from the end is the head `1`.

Constraints

  • The number of nodes in the list is in the range [1, 30].
  • 0 <= Node.val <= 100
  • 1 <= n <= the number of nodes in the list.
Saved
head =
[1,2,3,4,5]
n =
2