LeetCode 189: Rotate Array

ArrayMathTwo Pointers

Problem Description

Explanation

To rotate an array to the right by k steps, we can use the following approach:

  1. Reverse the entire array.
  2. Reverse the first k elements.
  3. Reverse the remaining elements.

This approach allows us to achieve the rotation in-place with O(1) extra space.

Time complexity: O(n), where n is the number of elements in the array. Space complexity: O(1).

Solutions

class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }
    
    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}

Loading editor...