Skills101
← All coding problems

Rotate Array

mediumArrays & Hashing+20 XPTime limit 2s

Rotate the array to the right by k steps: each step moves the last element to the front.

Input:

  • line 1: n k
  • line 2: n integers

Output: the rotated array on one line.

Constraints: 1 ≤ n ≤ 10⁵, 0 ≤ k ≤ 10⁹ (yes, k can be bigger than n), −10⁹ ≤ a[i] ≤ 10⁹.

Challenge: rotating one step at a time is far too slow for k = 10⁹. Try the reverse trick: reverse everything, then reverse the first k and the rest.

Sample input 1

7 3
1 2 3 4 5 6 7

Sample output 1

5 6 7 1 2 3 4

Sample input 2

4 2
-1 -100 3 99

Sample output 2

3 99 -1 -100

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.