7. Rotate Array

Difficulty: medium · Array, Math, Two Pointers

Problem

Given an integer array `nums`, rotate it to the **right** by `k` steps, and print the result. One step moves the last element to the front.

Input

The first line holds `n` and `k`. The second holds `n` integers.

Output

Print the rotated array, space separated.

Example 1

Input:
7 3
1 2 3 4 5 6 7
Output:
5 6 7 1 2 3 4

Explanation: The last 3 elements move to the front.

Example 2

Input:
4 2
-1 -100 3 99
Output:
3 99 -1 -100

Explanation: The last 2 elements move to the front.

Example 3

Input:
1 5
42
Output:
42

Explanation: Rotating 1 elements by 5 steps brings every element back to where it started.

Example 4

Input:
5 0
1 2 3 4 5
Output:
1 2 3 4 5

Explanation: Rotating 5 elements by 0 steps brings every element back to where it started.

Example 5

Input:
3 3
1 2 3
Output:
1 2 3

Explanation: Rotating 3 elements by 3 steps brings every element back to where it started.

Example 6

Input:
3 4
1 2 3
Output:
3 1 2

Explanation: The last 1 element move to the front (4 steps is the same as 1, since the array has 3 elements).

Example 7

Input:
6 1
10 20 30 40 50 60
Output:
60 10 20 30 40 50

Explanation: The last 1 element move to the front.

Example 8

Input:
2 1
8 9
Output:
9 8

Explanation: The last 1 element move to the front.

Example 9

Input:
6 7
-860913 706787 586564 -39425 565921 609542
Output:
609542 -860913 706787 586564 -39425 565921

Explanation: The last 1 element move to the front (7 steps is the same as 1, since the array has 6 elements).

Example 10

Input:
6 4
790937 375211 -462713 151613 -451717 -329263
Output:
-462713 151613 -451717 -329263 790937 375211

Explanation: The last 4 elements move to the front.

Constraints

- 1 <= n <= 10^5 - 0 <= k <= 10^9 - -2^31 <= nums[i] <= 2^31 - 1

Solutions are judged against 10 sample and 5 hidden tests. Sign in to solve it · All problems