Mastery Points
0

Array Rotation in dsa

Context & Logic

Rotating an array involves shifting its elements by 'k' steps to the right or left. An optimal approach uses array reversals.

Example

function rotate(nums, k) {
    k %= nums.length;
    const reverse = (l, r) => {
        while (l < r) [nums[l++], nums[r--]] = [nums[r], nums[l]];
    }
    reverse(0, nums.length - 1);
    reverse(0, k - 1);
    reverse(k, nums.length - 1);
}

Step-by-Step Logic

1

Normalize k (k = k % length).

2

Reverse the entire array.

3

Reverse the first 'k' elements.

4

Reverse the remaining 'n-k' elements.

Complexity Metrics

Time Efficiency

O(n)

Memory Footprint

O(1)