Skip to content
Advertisement

Array Left Rotation in Javascript will log to console but not return

I’m working on the array left rotation on Hackerrank. The solution that I have will console.log the array containing the correct result, but will not work using return. Here’s the detail from their site – “Print a single line of n space-separated integers denoting the final state of the array after performing d left rotations.” I’ve read that the issue might be with asynchronous functions running in node.js, but I’m not sure how to work around that.

// sample input - 1 2 3 4 5
// sample output - 5 1 2 3 4

function rotLeft(a, d) {
  var arr = [];

    for (var i = 1; i <= a; i++){
      arr.push(i)
    };
    for (var j = 1; j <= d; j++){
    	arr.shift(arr.push(j))
    }
    console.log(arr.toString()); // <-- this will print the desired output.
    return arr.toString(); // <-- no return from this.
}


rotLeft(5, 4)

Advertisement

Answer

I have also been trying to solve this problem. There are some issues in your current solution. See you have to create an array and store the array passed from parameters in it. What you have done is just creating a new array and adding the sequence of numbers of elements that should be in it e.g a.length=5 you are doing arr.push 1 2 3 4 5. But the question wants an array of user’s choice. Second thing is that you should return an array not the string.

So this is the solution of this problem:

function rotLeft(a, d) {
    var arr = [];
    for (var i = 0; i < a.length; i++) {
        arr.push(a[i]);
    };
    for (var j = 1; j <= d; j++) {
        arr.shift(arr.push(arr[0]));
    }
    return arr;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement