Maria

Posted on

# Array Left Rotation | HackerRank practice

It's that sweet time in every developers career when you have to prepare for job interviews!

To practice for upcoming interviews I decided to make my way though the problem solving challenges on HackerRank and share my solution here for further discussion.

The first exercise in this series is Array Left Rotation, which I solved in JavaScript.

In this problem you get the length of an array(n), the number of left shifts(d), and an array(a). The goal is to performs d rotations on the array, moving one element from the beginning to the end of the array.

For example: if you have the array `[1, 2, 3, 4, 5]` and d is 2 then the algorithm should output `3 4 5 1 2`.

## Brute force approach

This was my first solution to the problem: loop though the array d times and each time move the first element to the end of the array.

Remember: a is the array and d is the number of shifts to the left

``````for(let i=0; i<d; i++){
let elem = a.shift()
a.push(elem)
}

console.log(a.join(' '))

``````

## The slice solution

If you look at the constrains listed in the HackerRank instructions you'll notice that d is always smaller than n, the array's length. This means we can use slice() to slice off the first d elements of the array and then concatenate it to the end of the array.

``````let toShift = a.slice(0, d)
let remaining = a.slice(d, n)

console.log(remaining.concat(toShift).join(' '))
``````

These are my 2 solutions!

Please feel free to comment and add other solutions to this problem!

Also if you want you can follow me here or on Twitter :)