Skip to main content

189 Rotate Array

Description:

Given an integer array nums, rotate the elements to the right by k positions, where k is a non-negative integer.
Rotating to the right means that each element moves to an index that is k steps ahead, wrapping around to the beginning if necessary.


Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Step 1: [7,1,2,3,4,5,6]
Step 2: [6,7,1,2,3,4,5]
Step 3: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
Step 1: [99,-1,-100,3]
Step 2: [3,99,-1,-100]

Constraints:

1 <= nums.length <= 10^5
-2^31 <= nums[i] <= 2^31 - 1
0 <= k <= 10^5

JavaScript

var rotate = function(nums, k) {
let n = nums.length
let step = k % n
reverse(nums, 0, n - 1)
reverse(nums, 0, step - 1)
reverse(nums, step, n - 1)
};

const reverse = (arr, begin, end) => {
while(begin < end) {
let t = arr[begin]
arr[begin] = arr[end]
arr[end] = t
begin++
end--
}
}

TypeScript

function rotate(nums: number[], k: number): void {
let n = nums.length
let step = k % n
reverse(nums, 0, n - 1)
reverse(nums, 0, step - 1)
reverse(nums, step, n - 1)
};

function reverse(nums: number[], begin: number, end: number) : void {
while(begin < end) {
let t = nums[begin]
nums[begin] = nums[end]
nums[end] = t
begin++
end--
}
}