Intermediate Level
Implement the rotateArrayRightK method that returns the array after rotating it k positions to the right.
The input contains an integer array nums, its length size, and an integer k. Your task is to rotate the array to the right by k positions and return the rotated array.
In a right rotation, elements from the end move to the beginning. For example, rotating [1,2,3,4,5] right by 2 gives [4,5,1,2,3].
Example 1
Input
nums (int[]) =
[1,2,3,4,5]size (int) =
5k (int) =
2Returns (int[])
[4,5,1,2,3]Example 2
Input
nums (int[]) =
[1,2,3]size (int) =
3k (int) =
1Returns (int[])
[3,1,2]Example 3
Input
nums (int[]) =
[1,2]size (int) =
2k (int) =
2Returns (int[])
[1,2]First reduce k using k % size, because rotating by the array length brings the array back to the same order.
One simple way is to split the array into two parts: the last k elements and the remaining first part. Place the last part first, followed by the first part.
If k becomes 0, return the array unchanged.
Pseudocode:
function rotateArrayRightK(nums, size, k):
if size == 0:
return nums
k = k % size
if k == 0:
return nums
result = empty array
for i from size - k to size - 1:
add nums[i] to result
for i from 0 to size - k - 1:
add nums[i] to result
return resultReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run