DEV Community

Cover image for Rotate Array - Leetcode 189 - TypeScript
Yaz
Yaz

Posted on • Edited on

Rotate Array - Leetcode 189 - TypeScript

Here's the Leetcode 189 solution using TypeScript.

Watch on Youtube

Leetcode 189 - Rotate Array:

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

Approach

The goal is to rotate an array nums to the right by k steps. You can use a cyclic rotation by repeatedly popping the last element and unshifting it to the beginning of the array in a loop.

The for loop runs for k iterations, and in each iteration, the pop method removes the last element from the array, and unshift adds it to the beginning. This process is repeated k times and it will rotate the array to the right.

View on Excalidraw

View on Excalidraw

Code Implementation

function rotate(nums: number[], k: number): void {
  for (let i = 0; i < k; i++) nums.unshift(nums.pop()!)
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity

Time complexity is O(k * n), where n is the length of the input array nums. In each iteration of the loop, both pop and unshift operations take O(n) time as they involve shifting elements. Therefore, the total time complexity is O(k * n).

Space Complexity

Space complexity is O(1) or constant. The algorithm performs the rotation in-place, it modifies the input array directly without using additional memory that grows with the size of the input array.

Top comments (0)