Remove Nth Node From End of List
medium
linked-list
two-pointers
Given the head of a linked list, remove the n-th node from the end of the list and return its head.
Input / output
- Input:
head: ListNode(JSON test fixture is a plain array of node values),n: int - Output:
ListNode— the head of the list after removal (serialized the same way)
Constraints
- The number of nodes in the list is between 1 and 30.
0 <= node value <= 1001 <= n <= number of nodes(n is always valid, so the removed node always exists)
Follow-up
Can you do this in a single pass, without first counting the length of the list?
Examples
Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2 (removing the only node)
Input: head = [1], n = 1
Output: []
Example 3 (removing the last node)
Input: head = [1,2], n = 1
Output: [1]
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.