
Remove Nth Node from the End of the Linked List (Blind 75)
Problem Overview We are given the head of a singly linked list. We are given a node index n from the end. The goal is to remove the nth node from the end of the list. Constraints We have to do this in a single pass. Leetcode - Linked List Cycle Brute Force Approach Intuition We use a vector to keep track of the nodes and their indices. Once the traversal is finished, we calculate the node index from the start. Once we get that index, we remove that node. Code class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { vector<ListNode*> arr; ListNode* curr = head; while (curr) { arr.push_back(curr); curr = curr->next; } int nodeFromStart = arr.size() - n; if (nodeFromStart == 0) return head->next; if (nodeFromStart < arr.size()) arr[nodeFromStart - 1]->next = arr[nodeFromStart]->next; return head; } }; Why This Fails It usegs extra space O(n). The problem requires a constant space solution. Time and Space Complexity Time: O(n) Space: O(n) Optimal Approach We maintain two pointers similar to Floyd’s Tortoise and Hare technique. ...


