← DiffPush

Rotate array left&right by k places

Baseline Arrays · Easy O(n) · O(1)

Cyclic Duty Roster

An on-call roster is stored as an ordered list of engineers, and every k weeks the schedule is cycled so later engineers take the earliest shifts. Ops needs both directions available: one helper cycles the roster to the right, the other to the left. Both must rearrange the roster in place without a scratch copy.

Input: An array arr of n integer ids followed by a non-negative integer k, the number of positions to cycle.

Output: The array cycled k positions in the requested direction; a right rotation by k moves the last k entries to the front.

Constraints

Examples

Example 1

Input: {"nums":[1,2,3,4,5,6,7],"k":3,"direction":"right"}
Output: [5,6,7,1,2,3,4]
Cycling right three times lifts the tail block 5,6,7 to the front while the rest keeps its order.

Example 2

Input: {"nums":[-1,-100,3,99],"k":2,"direction":"right"}
Output: [3,99,-1,-100]
Two right shifts move the last pair to the front, and ordering inside each block is preserved.

Solve this in your browser →

Also on LeetCode ↗