Algorithms

HackerRank Left Rotation Arrays Challenge

Return the updated array to be printed as a single line of space-separated integers.

Adam

Adam


The details for the problem detailed in this post can be found at https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem

The following solution is written in Javascript.

Problem

A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become . Note that the lowest index item moves to the highest index in a rotation. This is called a circular array.

Given an array a of n integers and a number, d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.

Function Description

Complete the function rotLeft in the editor below.

rotLeft has the following parameter(s):

  • int a[n]: the array to rotate
  • int d: the number of rotations

Returns

  • int a'[n]: the rotated array

Input Format

The first line contains two space-separated integers n and d, the size of a and the number of left rotations. The second line contains n space-separated integers, each an a[i].

Constraints


    1 <= n <= 10^5
    1 <= d <= 1n
    1 <= a[i] <= 10^6
  

Sample Input


    5 4
    1 2 3 4 5
  

Sample Output


    5 1 2 3 4
  

Explanation

When we perform d = 4 left rotations, the array undergoes the following sequence of changes:


        [1,2,3,4,5,] -> [2,3,4,5,1] -> [3,4,5,1,2,] -> [4,5,1,2,3] -> [5,1,2,3,4]
    

Solution


    function rotLeft(a, d) {
        const dif = a.length - d;

        if (d < a.length) {
            return a.slice(-dif).concat(a.slice(0, d))
        } else {
            return a.slice(-(d % a.length)).concat(a.slice(0, dif))
        }
    }

Refactored Solution

Although the solution above works with all test cases there is some code repetition, both return statements are essentially the same with slightly different parameters for each slice method. In my first attempt I was getting the last x amount of indexes and then concatenating the first range of indexes. By using a range in both instances I was able to replace the if statment with a ternary statement.


    function rotLeft(a, d) {
        const len = d < a.length ? d : d % a.length;
        return a.slice(len, a.length).concat(a.slice(0, len))
    }