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) = 5
k (int) = 2
Returns (int[]) [4,5,1,2,3]

Example 2

Input
nums (int[]) = [1,2,3]
size (int) = 3
k (int) = 1
Returns (int[]) [3,1,2]

Example 3

Input
nums (int[]) = [1,2]
size (int) = 2
k (int) = 2
Returns (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 result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.