Learner Level

Implement the rightRotateArrayByOne method that returns the array after rotating all elements one position to the right.

The input contains an integer array nums and its length size. Your task is to rotate the array one position to the right and return the updated array.

In a right rotation, the last element moves to the front and every other element shifts one position toward the end. For example, [1,2,3,4] becomes [4,1,2,3].

Example 1

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

Example 2

Input
nums (int[]) = [9]
size (int) = 1
Returns (int[]) [9]

Example 3

Input
nums (int[]) = [5,6]
size (int) = 2
Returns (int[]) [6,5]

Handle arrays of size 0 or 1 directly because rotation will not change them.

For larger arrays, store the last element, shift all earlier values one position right, then place the stored last element at index 0.

Pseudocode:

function rightRotateArrayByOne(nums, size):
    if size <= 1:
        return nums
    last = nums[size - 1]
    for i from size - 1 down to 1:
        nums[i] = nums[i - 1]
    nums[0] = last
    return nums
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.