
Rotate an Array
Today, I will be talking about rotations. On LeetCode, there is a question that given some array
var head = [1, 2, 3, 4, 5]
and rotate it a number of
var k = 2
times, the final rotation will be
[4, 5, 1, 2, 3].
So how shall we approach this problem? We do know that we want to rotate it by removing the last number and inserting it into the front, and keep doing it until we have rotated it k times. The first thing I would do is splice the head array between the array length-k to k
var arr = head.splice(head.length - k, k)
because this will remove the last elements of the array and be inserted into a new array. We then define a new array to be
var newarr = head.
However, the head array is not the original, but after the splice. If the original head array were
head = [1, 2, 3, 4, 5],
then after the splice, it is
head = [1, 2, 3].
Our array is
arr = [5, 4]
and we want to insert these numbers into the front so we simply use a for loop and start at the end and insert into the head array using unshift(). The for loop is
for(var x = arr.length - 1; x >= 0; x--){newarr.unshift(arr[x])}return newarr
The full code is then
function rotate(head, k){ var arr = head.splice(head.length - k, k) var newarr = [] newarr = head for(var x = arr.length - 1; x >= 0; x--){ newarr.unshift(arr[x]) } return newarr}
Let’s give it a whirl. Given rotate([1, 2, 3, 4, 5], 2), the answer should be
[4, 5, 1, 2, 3],
and from figure 1, it is.

Let’s try another one: rotate([0, 1, 2], 4). This solution should be
[2, 0, 1]
and figure 2 shows it is indeed.

We can see the code works. If you know of another way to solve it, please tell me and we can discuss it.
References