1570. Kth Link From the Back
A parcel conveyor is stored as a singly linked list, and an inspector wants the parcel that sits k places before the end of the belt. Given head and an integer k, return the k-th node counted from the back, where k = 1 is the last node and k = length is the head. Return the node itself, the reference to the node that is already in the list and not a copy, so the answer is the suffix that starts at that node. The value of k is always valid. Do it without measuring the length first: advance a lead pointer k nodes, then move the lead and a trail pointer together until the lead falls off the list, and return the trail. The list has 1 to 1000 nodes. Aim for O(n) time and O(1) extra space.
Example 1
- Input:
- head = [1,2,3,4,5], k = 2
- Output:
- 3
- Explanation:
The 2nd node from the back is 4.
Example 2
- Input:
- head = [10,20,30], k = 3
- Output:
- 0
- Explanation:
k equals the length, so the head is returned.
Example 3
- Input:
- head = [5], k = 1
- Output:
- 0
- Explanation:
A single node is its own last node.
Constraints
1 ≤ length ≤ 1000
1 ≤ k ≤ length
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)