1586. Batches From the Tail
A warehouse packs crates from the loading dock at the end of a singly linked list, so batches of k are counted from the tail rather than from the head. Let the list head have length n. The first n % k nodes stay exactly as they are, and every following full group of k consecutive nodes is reversed in place. If n is smaller than k, nothing changes. Return the head of the resulting list, or null for an empty list. Count the length once, skip the untouched prefix and relink the rest: O(n) time and O(1) extra space.
Example 1
- Input:
- head = [1,2,3,4,5,6,7], k = 3
- Output:
- [1,4,3,2,7,6,5]
- Explanation:
The length is 7, so 7 % 3 = 1 node stays: 1, then [2,3,4] and [5,6,7] are reversed: 1, 4, 3, 2, 7, 6, 5.
Example 2
- Input:
- head = [1,2,3,4], k = 2
- Output:
- [2,1,4,3]
- Explanation:
The length divides evenly, so every pair is reversed: 2, 1, 4, 3.
Example 3
- Input:
- head = [1,2], k = 5
- Output:
- [1,2]
- Explanation:
The list is shorter than k, so every node is in the untouched prefix.
Constraints
0 ≤ length ≤ 105
1 ≤ k ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)