HackerRank – Left Rotation Solution in JavaScript – O(1) Space

Left Rotation is a coding challenge with easy difficulty in the HackerRank data structures category. In this blog post, we’ll discuss how we can solve it in JavaScript in O(n) time and O(1) space complexity.

Problem Statement

left rotation operation on an array of size n shifts each of the array’s elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result.

Read full details and access the challenge on Left Rotation | HackerRank

Solution

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

Time Complexity : O(n)

Space Complexity : O(1)

So, we have to shift the elements to the left. We can do that by simply moving the first element to the last index.

We can do that with arr.push(arr.shift()); arr.shift() removes the first element of an array and return it. The we just have to add it into the last index with arr.push().

Then, we repeat that with a for loop for d times.

Finally, we return the arr.

We’re iterating through the array once so we have O(n) time and since we used no extra array or extra space, we have O(1) space complexity.

Conclusion

That’s how you can solve the Left Rotation Challenge in HackerRank.

Overall, this is a simple challenge especially since JavaScript has such useful built-in functions. You just have to push the shifted element to the array and repeat it as many times as required.

If you have an approach different from mine, please do comment below!

Check out the rest of my blog for more helpful contents on Data Structures and Algorithms in JavaScript! We’ll also discuss more HackerRank solutions using JavaScript in this blog!

See you next post!

1 thought on “HackerRank – Left Rotation Solution in JavaScript – O(1) Space”

Leave a Comment