Leetcode: Rotate Array (189)

Problem no. 189 (Rotate Array) using JavaScript.

Ayush Tibra
The Tech Bible
2 min readMar 1, 2024

--

Day 6:

Photo by Pankaj Patel on Unsplash

So, the problem I chose to start for the sixth day is the Array problem in the Leetcode Top Interview 150 series.

I will solve all the problems only in JavaScript, I know most people use C++, Java, or Python to solve DSA problems, but why not try something different?

Let’s start:
The problem states that:

leetcode problem

Code:

Solution:

function reverseArray(nums, l, r) {
while (l < r) {
let temp = nums[l];
nums[l] = nums[r - 1];
nums[r - 1] = temp;
l++;
r--;
}
return nums;
}

const RotateArray = (nums, k) => {
k = k % nums.length;
let l = 0;

// Reverse the whole array
nums = reverseArray(nums, l, nums.length);

// Reverse first k numbers of the updated nums array
nums = reverseArray(nums, l, k);

// Reverse the last nums.length - k numbers
nums = reverseArray(nums, k, nums.length);
}

So, I’ll explain the solution I shared above:-

  • We create a function named reverseArray, which will return the updated reversed array according to the variables we passed.
  • We first reverse the whole array.
  • Second, we reverse the first k element of the array as if you can see the example shared in the problem, we need output like this.
  • Lastly, we reversed the remaining element of the array.

This solution beats 75.48% of users with Javascript solution on this problem.

It’s a self-explanatory solution for all of you as I only used basic JavaScript functions. If anyone has doubts, please let me know in the comment section.

Please share your views in the comment section and yeah feedback is appreciated.
Hoping you would like and will share this for better reach.
Checkout my other articles on — https://medium.com/@aayushtibra1997
Thanks for reading :)

--

--