19 - Hard - Remove Nth Node From End of List

Less than 1 minuteleetcodedata structurelinked listtypescript

19 - Hard - Remove Nth Node From End of List

LeetCodeopen in new window

  1. Find the (n + 1)-th node from the end of list:
  2. Create 2 pointers, p1 and p2;
  3. Move p2 forward by n + 1 steps;
  4. Move p1 and p2 simultaneously until p2 reaches the end of the list.
  5. At this point, p1 should point to the (n + 1)-th node from the end of the list. To delete the n-th node from the end of the list, point p1's next pointer to the one after p1.next.

TypeScript solution:

function removeNthFromEnd (head: ListNode | null, n: number): ListNode | null {
  if (head === null) {
    return null
  }

  let p1: ListNode | null = head
  let i = n
  while (p1 !== null && i > 0) {
    p1 = p1.next
    i--
  }

  if (p1 === null) {
    return head.next
  }

  let p2: ListNode | null = head
  while (p1 !== null && p2 !== null && p1.next !== null) {
    p1 = p1.next
    p2 = p2.next
  }

  if (p2 === null) {
    return head
  }

  const next = p2.next
  p2.next = next === null ? null : next.next

  return head
}
Last update:
Contributors: Shen Yuan