Skip to content
BytePatterns

Rotate Right By K

MediumArrays#in-place#reversal~25m

Problem

Shift every element of a list k positions to the right, so values pushed off the end reappear at the front. The rearrangement must happen inside the same list rather than in a freshly allocated one. The shift amount k is zero or positive and may be larger than the list itself.

Examples

Input:  nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
Why:    the last three values wrap around to the front
Input:  nums = [1, 2], k = 5
Output: [2, 1]
Why:    five shifts over two slots is the same as one shift
Input:  nums = [], k = 3
Output: []
Why:    edge case, an empty list has nothing to wrap

Hints

0 / 3

Stuck on the idea rather than the code? Rotate an Array covers it.