189. Rotate Array - Medium

Given an integer array nums, rotate the array to the right by k steps, where k is a non-negative.

Example:
Input: nums = [1,2,3,4,5,6,7], k = 3

Output: [5,6,7,1,2,3,4]

Explanation:
rotate 1 steps to the right:

[7,1,2,3,4,5,6]

rotate 2 steps to the right:

[6,7,1,2,3,4,5]

rotate 3 steps to the right:

[5,6,7,1,2,3,4]

Constraints:

  • 1 <= nums.length <= 10**5
  • -2**31 <= nums[i] <= 2**31 - 1
  • 0 <= k <= 10**5
My solution:
var rotate = function(nums, k) {
    while(k > 0) {
        nums.unshift(nums.pop());
        k--;
    }
}

It passes most test cases except it exceeds the time limit for the second to last test case so its not very fast. I am happy with it and I think an interviewer would be satisfied.

Here is a simple one liner solution that uses js built in method splice.

var rotate = function(nums, k) {
    return nums.unshift(...nums.splice(-k % nums.length));
}

The splice method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. I'd give my rating a 6/10 because I'm new to splice and not sure I'd fully remember how to use it.

Comments

Popular posts from this blog

28. Find the Index of the First Occurence in a String - Easy

121. Best Time to Buy and Sell Stock - Easy

58. Length of Last Word - Easy