PythonMediumArrays20 min
Rotate an array to the right
Wrap values past the final position back to the beginning. If the array is empty, return an empty result; k may exceed n. Interviewers use this problem to assess reduce k modulo n, then reverse the whole array and its two pieces.
Input
First line: n and k. Second line: n integers.
Output
Print the result values separated by single spaces; print an empty line for an empty result.
Constraints
0 <= n <= 100000; 0 <= k <= 10^18; -10^9 <= values <= 10^9.
Example
Input
5 2 1 2 3 4 5
Output
4 5 1 2 3
Example 2 input
4 4 1 1 -2 0
Output
1 1 -2 0
A full rotation is the identity.
Public test cases (2)
Input
5 2 1 2 3 4 5
Expected output
4 5 1 2 3
Input
3 10 -1 0 2
Expected output
2 -1 0
Hints (2)
- Identify the state needed to avoid repeated work.
- Reduce k modulo n, then reverse the whole array and its two pieces.
Target complexity: time O(n) · space O(1)
