Rotate Array Right

Medium · rating 1300 · Arrays, Implementation

The first line contains n and k. The second line contains n integers. Print the array after rotating it right by k positions (elements shifted off the end wrap to the front), space-separated on one line.

Constraints: 1 ≤ n ≤ 105, 0 ≤ k ≤ 109

Editorial

Approach

Rotating by n lands back where you started, so first reduce k modulo n. Then the result is the last k elements followed by the rest: a[-k:] + a[:-k].

k %= n
if k:
    a = a[-k:] + a[:-k]
print(*a)

Watch out

Take k %= n before slicing — k can be far larger than n, and a k of 0 must leave the array untouched.

Complexity

Time: O(n). Space: O(n).

Related problems

Open Rotate Array Right in Code Arena →