Remove the th node from the end of a singly linked list and return the updated list.
Problem
You are given the head of a singly linked list and an integer . Remove the th node from the end of the list, then return the head of the modified list.
The list should be changed in-place by adjusting pointers; you do not need to create a new list.
Notes
- The list has at least one node.
- is always valid and refers to an existing node from the end.
- The first node is the head of the list, and the last node is the end of the list.
Input Format
- The first input is the head of a singly linked list.
- The second input is an integer .
For backend practice records, the list may be represented in array form when describing examples.
Output Format
- Return the head of the linked list after removing the th node from the end.
Constraints
- The list contains at least 1 node.
- length of the list.
- Time complexity should be linear in the number of nodes.
- Extra space should be constant, excluding the input list storage.
Example 1
Input
head = [1,2,3,4,5], n = 2
Output
[1,2,3,5]
Explanation
The 2nd node from the end is 4, so it is removed.
Example 2
Input
head = [1], n = 1
Output
[]
Explanation
Removing the only node leaves an empty list.
Show 1 more example
Example 3
Input
head = [1,2], n = 2
Output
[2]
Explanation
The node to remove is the head, so the new head becomes 2.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.