Tags

  • AWS (7)
  • Apigee (3)
  • ArchLinux (5)
  • Array (6)
  • Backtracking (6)
  • BinarySearch (6)
  • C++ (19)
  • CI&CD (3)
  • Calculus (2)
  • DesignPattern (43)
  • DisasterRecovery (1)
  • Docker (8)
  • DynamicProgramming (20)
  • FileSystem (11)
  • Frontend (2)
  • FunctionalProgramming (1)
  • GCP (1)
  • Gentoo (6)
  • Git (16)
  • Golang (1)
  • Graph (10)
  • GraphQL (1)
  • Hardware (1)
  • Hash (1)
  • Kafka (1)
  • LinkedList (13)
  • Linux (27)
  • Lodash (2)
  • MacOS (3)
  • Makefile (1)
  • Map (5)
  • MathHistory (1)
  • MySQL (21)
  • Neovim (11)
  • Network (67)
  • Nginx (6)
  • Node.js (33)
  • OpenGL (6)
  • PriorityQueue (1)
  • ProgrammingLanguage (9)
  • Python (10)
  • RealAnalysis (20)
  • Recursion (3)
  • Redis (1)
  • RegularExpression (1)
  • Ruby (19)
  • SQLite (1)
  • Sentry (3)
  • Set (4)
  • Shell (4)
  • SoftwareEngineering (12)
  • Sorting (2)
  • Stack (4)
  • String (2)
  • SystemDesign (13)
  • Terraform (2)
  • Tree (24)
  • Trie (2)
  • TwoPointers (16)
  • TypeScript (3)
  • Ubuntu (4)
  • Home

    [LeetCode 19] Remove Nth Node from End of List

    Published Nov 30, 2021 [  LinkedList  ]

    Problem

    Given the head of a linked list, remove the nth node from the end of the list and return its head.

    Example 1:

    Input: head = [1,2,3,4,5], n = 2
    Output: [1,2,3,5]
    

    Example 2:

    Input: head = [1], n = 1
    Output: []
    

    Example 3:

    Input: head = [1,2], n = 1
    Output: [1]
    

    Constraints:

    - The number of nodes in the list is sz.
    - 1 <= sz <= 30
    - 0 <= Node.val <= 100
    - 1 <= n <= sz
    

    Thoughts

    • With a dummy node, we can make the distance between left & right pointer to be n + 1
    • We move right pointer to the end of list, left pointer will be before the node we want to delete.

    Typescript

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     val: number
     *     next: ListNode | null
     *     constructor(val?: number, next?: ListNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.next = (next===undefined ? null : next)
     *     }
     * }
     */
    
    function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
        // create a dummy node pointing to head
        const dummy = new ListNode(0, head)
        
        let left = dummy;
        let right = head;
        
        // make sure the diff between left & right is n + 1
        while(n > 0 && right) {
            right = right.next;
            n--;
        }
        
        // move both right & left to next until right is null
        // then we have left before the nth node from the end
        while(right) {
            left = left.next
            right = right.next
        }
        
        // deletion
        left.next = left.next.next
        
        
        return dummy.next
        
    };
    

    Reference