Rotate an Array by N Elements
Explore how to rotate an array by a given number of elements in either direction, modifying the original array efficiently. Understand two approaches: one uses in-place reversals for constant space complexity, and the other uses a temporary array for clarity. By the end, you'll grasp how to normalize rotation values and implement these solutions with linear time complexity.
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
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 , ...