⌘K
Flycodx

Rotate Array by K

Rotate Array by K

EasyArrays19% accepted

Given an array of n integers and a non-negative integer k, rotate the array to the right by k positions. Rotating right by one step means the last element moves to the front. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer.

Input format — only if your code reads from stdin

Input format (stdin): - First line: two integers n (array size) and k (rotation steps) - Second line: n space-separated integers Output: the rotated array as space-separated integers. Note: if k ≥ n, the effective rotation is k % n steps.

Approach

Use k % n to normalize. The triple-reverse trick: reverse the whole array, then reverse first k elements, then reverse the rest — all in O(n) time and O(1) space.

Input

5 2 1 2 3 4 5

Output

4 5 1 2 3
  • •1 ≤ n ≤ 10^5, 0 ≤ k ≤ 10^9
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3