Remove Nth Node From End of List
Medium · Linked List
You are given the head of a singly linked list and an integer n. Remove the node that sits n positions from the end of the list and return the head of the resulting list. There is exactly one valid removal since n is guaranteed to be within range, so the goal is to find it without scanning the list twice.
Examples
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Why: Counting from the end, the 2nd node is 4, so it is dropped from the chain.
Input: head = [1], n = 1
Output: []
Why: The only node is removed, leaving an empty list.
Input: head = [1,2], n = 1
Output: [1]
Why: The last node, 2, is removed leaving just 1.
Constraints
1 <= number of nodes <= 10^4, -10^5 <= node value <= 10^5, 1 <= n <= number of nodes
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Remove Nth Node From End of List
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Remove Nth Node From End of List. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.