Skip to content
Algorithm.js
📚 단일 패턴

189. Rotate Array

배열을 k번 오른쪽으로 회전시키는 문제를 여러가지 솔루션으로 해결하기

Oct 1, 2025 — hash

문제 설명

1st Solution: Time O(n * k)

/**
Do not return anything, modify nums in-place instead.
*/
function rotate(nums: number[], k: number): void {
while (k > 0) {
nums.unshift(nums.pop());
k -= 1;
}
};

2nd Solution : Time O(n) Space O(n)

/**
Do not return anything, modify nums in-place instead.
*/
function rotate(nums: number[], k: number): void {
const N = nums.length;
const rotated = Array(N).fill(0);
for (let i = 0; i < N; i += 1) {
rotated[(i + k) % N] = nums[i];
}
for (let i = 0; i < N; i += 1) {
nums[i] = rotated[i];
}
};

3rd Solution : Time O(n) Space O(n)

/**
Do not return anything, modify nums in-place instead.
*/
function rotate(nums: number[], k: number): void {
const N = nums.length;
const M = k % N;
const temp = [
...nums.slice(-M),
...nums.slice(0, -M)
]
for (let i = 0; i < N; i += 1) {
nums[i] = temp[i];
}
};

4th Solution : Time O(n) Space O(1)

/**
Do not return anything, modify nums in-place instead.
*/
function rotate(nums: number[], k: number): void {
const N = nums.length;
k = k % N;
const reverse = (array, left, right) => {
while (left < right) {
[ array[left], array[right] ] = [ array[right], array[left] ];
left += 1;
right -= 1;
}
}
reverse(nums, 0, N - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, N - 1);
};