Is JavaScript's .shift() Method a Performance Boost?

Annie Liao - Jun 13 '20 - - Dev Community

It's one thing to understand the concept of time/space complexity. It's another to apply the knowledge when solving algorithm puzzles. After reading the well-illustrated, beginner-friendly Grokking Algorithm, I thought I was fully prepared to tackle algorithm challenges using the big O notation.

I was wrong. This is what I often encounter during my HackerRank practices:
hackerrank timeout screenshot

It is still challenging for me to come up with scalable solutions on the first try. Naturally, I would look up alternative solutions and try to emulate the solver's thought process.

Oftentimes my initial reaction would be "Wow, that's brilliant. Why didn't I think of that?"

But in this particular code challenge, I found a solution that looks similar to mine and is able to pass all test cases.

And that led me to learning runtime complexity of JavaScript array methods.

So, here's the challenge. It's a simple left rotation of an array:



Given an array (arr) and number of left rotations (d), 
returns the updated array.


Enter fullscreen mode Exit fullscreen mode

For example:



rotateLeft([1, 2, 3, 4, 5], 4)
// elements in the array rotate 4 times:
// [2, 3, 4, 5, 1] -> [3, 4, 5, 1, 2] -> [4, 5, 1, 2, 3] -> [5, 1, 2, 3, 4] 
// returns [5, 1, 2, 3, 4]


Enter fullscreen mode Exit fullscreen mode

Here's my initial solution, which passed 8 of the 10 test cases:



function rotateLeft(arr, d) {
    for (let i = 0; i < d; i++) {
    // 1. create a copy of arr starting at index 1, save to a variable (tempArr)
    // 2. push arr[0] to tempArr
    // 3. Now, tempArr has the updated order, so we reassign arr to tempArr
        let tempArr = arr.slice(1)
        tempArr.push(arr[0])
        arr = tempArr
    }
    return arr
}


Enter fullscreen mode Exit fullscreen mode

And here's the solution I found that passed all test cases:



function rotateLeft(arr, d) {
    let tempArr = arr.slice()
    for (let i = 0; i < d; i++) {
        let firstItem = tempArr.shift()
        tempArr.push(firstItem)
    }
    return tempArr
}


Enter fullscreen mode Exit fullscreen mode

In my solution, I created a new array via .slice() method in each iteration, while the other solution code only did it once outside the for loop.

I also found an explanation on Stack Overflow that compares runtime complexity of some array methods.

An engineer friend further explained that adding arrays together is an O(n + m) complexity: Arrays are fixed in size under the surface, so when you add them together, you are actually creating a new array big enough to hold them. And doing it for each iteration results in an O(n + m)^2 complexity.

Despite the two resources above, I am still baffled by the reason behind using .shift() that leads to an optimized solution.

Would anyone like to take a stab at explaining it?

. . . . . . . . . . . . . . . . . . . . . . . . . . .