...

/

Rotate an Array by N Elements

Rotate an Array by N Elements

Given an integer array, rotate it by 'n' elements.

Statement

We’re given an array of integers, nums. Rotate the array by n elements, where n is an integer:

  • For positive values of n, perform a right rotation.
  • For negative values of n, perform a left rotation.

Make sure we make changes to the original array.

Example

Let’s look at the original array below:

g array 0 1 2 3 4 5 6 7 8 9 1 10 20 0 59 86 32 11 9 40

On the original array, we perform a left rotation when n is equal to 1-1. The modified array looks like this:

g array 0 1 2 3 4 5 6 7 8 9 10 20 0 59 86 32 11 9 40 1

Similarly, when n is equal to 22, we perform two right rotations one after the other. The modified array looks like this:

g array 0 1 2 3 4 5 6 7 8 9 9 40 1 10 20 0 59 86 32 11

Sample input

nums = [1, 10, 20, 0, 59, 86, 32, 11, 9, 40]
n = 2

Expected output

[9, 40, 1, 10, 20, 0, 59, 86, 32, 11]

Try it yourself

#include <iostream>
#include <vector>
using namespace std;
void RotateArray(vector<int>& nums, int n) {
//TODO: Write - Your - Code
}

Solution 1

Here’s how the solution works:

  • Normalize the rotations, so they do not exceed the length of the array. For example, for an array of length 1010, ...