LeetCode - Blind 75 - Remove Nth Node From End of List

The Problem Given the head of a linked list, remove the nth node from the end of the list and return its head. Examples Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Input: head = [1], n = 1 Output: [] 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 Brute Force Solution func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { var nodes: [ListNode] = [] var curr = head while curr != nil { nodes.append(curr!) curr = curr!.next } let removeIndex = nodes.count - n if removeIndex == 0 { return head?.next } nodes[removeIndex - 1].next = nodes[removeIndex].next return head } Explanation One way to solve this problem is to use extra memory by iterating over all elements in head and storing them in an array. The brute force solution allows us to know the index of each element and delete the node. ...

December 25, 2024 · 3 min · Dmytro Chumakov