1585. Alternate Batch Reversal
A conveyor belt carries parcels in a singly linked list and is processed in batches of k consecutive parcels. Cut head into consecutive groups of k nodes, the last group possibly shorter. Reverse the 1st, 3rd, 5th, ... group and leave the 2nd, 4th, ... group exactly as it is, then join the groups in their original order. A short final group is reversed if it falls on a reversing turn and left alone otherwise. Return the head of the rebuilt list, which is null for an empty list. Relink nodes without allocating new ones: O(n) time, O(1) extra space.
Example 1
- Input:
- head = [1,2,3,4,5,6], k = 2
- Output:
- [2,1,3,4,6,5]
- Explanation:
Groups are [1,2], [3,4], [5,6]; groups 1 and 3 are reversed: 2, 1, 3, 4, 6, 5.
Example 2
- Input:
- head = [1,2,3,4,5], k = 3
- Output:
- [3,2,1,4,5]
- Explanation:
The first group [1,2,3] is reversed and the short second group [4,5] is not: 3, 2, 1, 4, 5.
Example 3
- Input:
- head = [7,8,9], k = 5
- Output:
- [9,8,7]
- Explanation:
The single short group is the first group, so it is reversed: 9, 8, 7.
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)