How to Solve HackerRank’s Left Rotation Problem (JavaScript)

This blog post features and explains my solution to HackerRank’s Arrays Left Rotation Problem.

The problem states that we’ll be getting an array as an input (e.g. [1,2,3,4,5]) along with an integer (d). Then, we need to shift each of the array’s elements unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5] , then the array would become [3,4,5,1,2].

My favorite way to solve algorithms is by performing these steps:

  1. Draw it out; and do it manually as a human would
  2. Take those steps, and write it out, or pseudo code it into steps
  3. THEN begin translating that into code.

So, by taking these steps,

  1. Take the first element of the array…
  2. Put in the back
  3. Repeat this as many times as d says.

SPOILER ALERT — SOLUTION BELOW!

function rotLeft(a, d) {   while (d) {      a.push(a.shift());      d--;   }return a;}

I decided to write a blog post on this because I’ve seen a lot of solutions out there that seem (to me) unnecessarily complex. They create temporary variables, do for loops, calculate lengths…etc. But if we approach it like the best computer ever created (the human brain) and write it that way, it’s pretty simple:

while (d)

This is the code’s way of saying, “while this exists”. The this in this case, is the number we were given in d- in this case, 2. If you only want to execute something a particular number of times, you need to decrement or subtract something from d. Otherwise, you’ll get into an infinite loop. That’s what this line does.

d--

This means that the code inside the while loop will execute only two times, because after each execution, 1 will be subtracted from d. After two iterations, d will be 0. Because 0 in considered a falsy value in javascript, the loop breaks.

Inside the loop, we do the code’s version of what our human brain intuitively does: take that value I’m looking at, and put it at the end.

a.push(a.shift());

Because order of operations, we do what’s inside the parenthesis first. shift() takes out the first element of an array, and returns it. Now, all we have to do is put that thing at the end of the array. That’s what push() does.

Thanks for reading!

And remember: grit > talent.

Always learning.