1587. Block Right Shift
A ticket line is stored as a singly linked list and is divided into consecutive blocks of k people; the last block may be shorter. Inside each block, the person at the back moves to the front of that block while everyone else keeps their order, which is a right shift by one position within the block. Blocks stay in their original order. Given head and k, return the head of the rearranged list (null for an empty list). Only relink existing nodes; do not copy values. The intended solution runs in O(n) time with O(1) extra space.
Example 1
- Input:
- head = [1,2,3,4,5,6], k = 3
- Output:
- [3,1,2,6,4,5]
- Explanation:
Blocks are [1,2,3] and [4,5,6]; the last node of each moves to its front: 3, 1, 2, 6, 4, 5.
Example 2
- Input:
- head = [1,2,3,4,5], k = 2
- Output:
- [2,1,4,3,5]
- Explanation:
Blocks are [1,2], [3,4], [5]; the result is 2, 1, 4, 3, 5.
Example 3
- Input:
- head = [8,9], k = 1
- Output:
- [8,9]
- Explanation:
Blocks of one node are unchanged.
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)