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:
On the original array, we perform a left rotation when n
is equal to . The modified array looks like this:
Similarly, when n
is equal to , we perform two right rotations one after the other. The modified array looks like this:
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 , ...