Arrays: Left Rotation (JavaScript)

Tanuka Das
3 min readSep 18, 2020

HackerRank’s Arrays Left Rotation

Question: 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].

Example 1:

Input: n = 7, d = 2
arr[] = {1, 2, 3, 4, 5, 6, 7}
Output: 3 4 5 6 7 1 2
Explanation: Rotation of the above
array by 2 will make the output array .

Example 2:

Input: n = 6, d = 12
arr[] = {1, 2, 3, 4, 5, 6}
Output: 1 2 3 4 5 6

My approach:

The rotLeft function takes in two parameters, array (a), and the number of rotations (d). The first approach involves two loops. Start by creating a new array where we can store the integers from the original array. The first loop will start from the index of the rotation number to the length of the array. Next, store each integer in the new array and increment both the integers in the new array and the rotation index in the original array. So, our new array will look like this [3, 4, 5, 6, 7]. Now, set the rotation index to 0 and start the second loop from the rotation index to the rotation number.

If you’re confused between the rotation number and rotation index, you’re not alone. The rotation number, d = 2, that means we’ve to rotate the first two numbers from the array. Now, when we set the rotation left index to d, it points to index 2 which is 3 in this array. As a result, in the 1st loop, we iterated from index 2 to the end of the array. After setting the left rotation index to 0, in the second loop, we will iterate from the rotation left index, which starts at 0, to the number of the rotation, d. It should look this[3, 4, 5, 6, 7, 1, 2] . Next, add each of the indexes in the new array. Finally, return the new array.

function rotLeft(a, d) {   let size = a.length;   let newArr = [];   let rotateLeftIdx = d;   let i = 0;   while(rotateLeftIdx < size){       newArr[i] = a[rotateLeftIdx]       i++       rotateLeftIdx++   }    //set rotateLeftIdx back to 0   rotateLeftIdx = 0;   while(rotateLeftIdx < d){       newArr[i] = a[rotateLeftIdx]       i++       rotateLeftIdx++    }    return newArr}

Time Complexity: O(n), n is the length of the array.

Space Complexity: O(n), linear time because we required extra space to store the integers.

Solution: https://github.com/tanuka16/JavaScript/blob/master/rotateLeft.js

--

--

Tanuka Das

Software Developer, technical writer, bookworm, constant learner.