LeetCode: Rotate Array
This week I’m working on the LeetCode Reverse Array problem. This function will accept an array of numbers and an integer, the array will rotate to the right by the amount given by the integer. For example, if the array is [1,2,3,4,5,6,7] and the given integer is 3, the final 3 elements in the array will flip to the front, so the solution would be [5,6,7,1,2,3,4].
This challenge has been giving me trouble for months, I was initially able to find a solution that solved all test cases except for one which timed out, and I decided to put it on the backburner since I the solution I had was nearly good enough, since it was able to find a correct answer, but that final test case just took too long to solve. I wanted to loop through the nums array and while the passed-in integer was greater than 0, remove the last element in the array and place it onto the front of the array.
I believe that the reason why the final test case was timing out is due to what’s happening in the unshift method. When unshift is called, it needs to update the index of each element along with its place, so in a large array it can be an extremely costly method. I had to find a different way to find a solution, even with how close this function is to being complete and passing.
One method that I know I can use to both add and remove elements from an array is the .splice() function. Splice is destructive, meaning it alters the input array that it’s called on. With line 6, I created a new variable that uses splice, with both arguments being variations of k, the passed-in integer. The first argument determines the start of the splice, when that number is made negative the method counts from the end of the array instead of the front. The second number is the amount of elements that will be removed from the array. Using the same array example from earlier in this solution, nums.splice(-3, 3) will be [5,6,7], the final 3 numbers in the array.
After setting that variable, I want to use it to add those numbers to the beginning of the array. You can use splice to add elements by setting the added value as the third argument of splice. Since I want to add the value of the rotate variable to the end of the splice, I want to start at 0, remove 0 elements, and use array destructuring to spread apart the rotate variable’s array to add those to the beginning, since if I don’t destructure the variable the solution will be a nested array, and return a wrong answer. This final splice will be the solution to get a completed problem!