LeetCode-189: Rotate Array

Learn how to solve LeetCode 189 using an efficient in-place array manipulation approach. This solution explores array rotation with optimal time complexity using the reverse method.

189. Rotate Array

Solution

 1/**
 2 * @param {number[]} nums
 3 * @param {number} k
 4 * @return {void} Do not return anything, modify nums in-place instead.
 5 */
 6var rotate = function (nums, k) {
 7    let N = nums.length;
 8    let startElementIndex = N - k;
 9
10    // Step 1: Normalise k, in case k is larger than N
11    // console.log(`k (before)`, k);
12    k = k % N;
13    // console.log(`k (after)`, k);
14
15    // Step 2: Helper function to reverse part of the array
16    const reverse = (start, end) => {
17        while (start < end) {
18            [nums[start], nums[end]] = [nums[end], nums[start]]; // Swap
19            start++;
20            end--;
21        }
22    };
23
24    // Step 3: Reverse the entire array
25    reverse(0, N - 1);
26
27    // Step 4: Reverse the first k elements
28    reverse(0, k - 1);
29
30    // Step 5: Reverse the remaining N-k elements
31    reverse(k, N - 1);
32};
comments powered by Disqus

Table of contents