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.

Fig. 1: Solution for rotate([1, 2, 3, 4, 5], 2).

Let’s try another one: rotate([0, 1, 2], 4). This solution should be

[2, 0, 1]

and figure 2 shows it is indeed.

Fig. 2: Solution for rotate([0, 1, 2], 4).

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






Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What is Flutter? Here is everything you should know.

How to Mine on Alien Worlds

AVA Gecko Node on Raspberry OS 64-bit

Exposing information of Salesforce with AppSync (GraphQL)

Creating and Using Static Libraries in the C Programming Language

A Simple Way to Create Kubernetes Clusters Locally Using kind

A Blockchain transaction ledger implementation

LEGACY — HackTheBox WriteUp

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Darrick Pang

Darrick Pang

More from Medium

Otherside: Everything to Know About the New Bored Apes Project

CS 373 Spring 2022: William Gunawan(Week of 25 Apr. — 01 May.)

Dlithe 4th week Experience