Rotate Array by K
Rotate Array by K
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
Output
- •
1 ≤ n ≤ 10^5, 0 ≤ k ≤ 10^9
More Arrays problems
Browse all coding problems →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