Leetcode Q189 (Medium): Rotate Array K times

Problem statements:




Problem Analysis:



Edge Cases:


Solutions:

Brute-Force Approach (Iterative Rotation):




Optimized Approach (The Three-Reversal Method)



Implemention - Java:

    /**
     * Rotates an array to the right by k steps.
     * The rotation is performed in-place.
     *
     * @param nums The array of integers to be rotated.
     * @param k The number of steps to rotate the array to the right.
     */
    public void rotate(int[] nums, int k) {
        int n = nums.length;
        if (n == 0) {
            return;
        }

        // Use the modulo operator to handle cases where k is greater than the array length.
        // This ensures k is always within the range [0, n-1].
        k %= n;

        // Step 1: Reverse the entire array.
        // For example, [1, 2, 3, 4, 5, 6, 7] becomes [7, 6, 5, 4, 3, 2, 1].
        reverse(nums, 0, n - 1);
        
        // Step 2: Reverse the first k elements.
        // For k=3, [7, 6, 5, 4, 3, 2, 1] becomes [5, 6, 7, 4, 3, 2, 1].
        reverse(nums, 0, k - 1);
        
        // Step 3: Reverse the remaining n-k elements.
        // [5, 6, 7, 4, 3, 2, 1] becomes [5, 6, 7, 1, 2, 3, 4].
        reverse(nums, k, n - 1);
    }


    /**
     * A helper method to reverse a portion of an array.
     *
     * @param nums The array.
     * @param start The starting index of the portion to reverse.
     * @param end The ending index of the portion to reverse.
     */
    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--;
        }
    }


Implementtion: Python

    class Solution:
      def rotate(self, nums: list[int], k: int) -> None:
          """
          Do not return anything, modify nums in-place instead.
          """
          n = len(nums)
          if n == 0:
              return

          k %= n

          def reverse(arr, start, end):
              while start < end:
                  arr[start], arr[end] = arr[end], arr[start]
                  start += 1
                  end -= 1

          # Step 1: Reverse the entire array
          reverse(nums, 0, n - 1)
          # Step 2: Reverse the first k elements
          reverse(nums, 0, k - 1)
          # Step 3: Reverse the remaining n-k elements
          reverse(nums, k, n - 1)

------ End ------