> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Remove Nth Node From End of List

Leetcode Problem 19: Remove Nth Node From End of List

Problem Summary

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

Constraints:

  • The list has between 1 and 30 nodes.
  • Node values are integers in the range [0, 100].
  • n is a valid index (between 1 and the length of the list).

Techniques

  • Linked List
  • Two Pointers

Solution

import { ListNode } from "../list-node";

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
    let dummy = new ListNode(0, head);
    let slow: ListNode | null = dummy;
    let fast: ListNode | null = dummy;

    for (let i = 0; i <= n; i++) {
        fast = fast?.next ?? null;
    }

    while (fast !== null) {
        slow = slow!.next;
        fast = fast.next;
    }

    if (slow!.next !== null) {
        slow!.next = slow!.next.next;
    }

    return dummy.next;
}