DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #189. Rotate Array

Solution with O(n) space complexity.

  • Time Complexity: O(n)

Single loop through the array (n iterations)
Each iteration does constant time operations (modulo, array assignment)

  • Space Complexity: O(n)

Creates an additional array rotatedArray of size nums.length
Extra space grows linearly with input size

class Solution {
    public void rotate(int[] nums, int k) {

          int[] rotatedArray = new int[nums.length];

        for (int i = 0; i < nums.length; i++) {
            rotatedArray[(i + k) % nums.length] = nums[i];
        }

        // copy the rotated array
        for (int i = 0; i < nums.length; i++) {
            nums[i] = rotatedArray[i];
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)