← DiffPush

Rotate LL k times

DiffPush Tier Linked List · Hard Promblems of LL O(n) · O(1)

Shunting the Print Queue to the Back of the Line

A print farm's job queue is a single chain, and every shift change the last k jobs are moved — in their existing order — to the front, so long-waiting jobs print first. A counter records the queue length while the tail is temporarily looped back to the head, which turns the chain into a ring: the shift then becomes a single cut at the right spot of that ring rather than k separate moves. Jobs past the cut become the new front, and the ring is cut open again.

Input: An array head of n node values and an integer k, the number of right rotations (possibly larger than n).

Output: The values of the list after rotating right by k places.

Constraints

Examples

Example 1

Input: {"head":[1,2,3,4,5],"k":2}
Output: [4,5,1,2,3]
The last two jobs (4, 5) move to the front in order; the cut on the ring lands after node 3.

Example 2

Input: {"head":[0,1,2],"k":4}
Output: [2,0,1]
Four rotations on a length-3 queue collapse to one effective rotation via modulo.

Solve this in your browser →

Also on LeetCode ↗