Leetcode 189 – Rotate Array | Three Approaches

Problem Description:

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

Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105
Problem Link : Rotate Array – LeetCode

Solution(s):

Approach 1: Using temporary array
  • Create a separate array named tempArr[] of size k.
  • First copy last k elements from original array to tempArr.
  • Now move first n-k elements from original array to last of original array.
  • Then copy all elements from tempArr to original array.
Java Code:
public void rotate(int[] nums, int k) {
    k = k % nums.length;
    //Create a temporary array of size K
    int[] tempArr = new int[k];
    
    //Copy last K elemets from original array to tempArr
    for (int i = 0; i < k; i++) {
        tempArr[i] = nums[nums.length-k+i];
    }
    
    //Move first n-k elements of original array to the end of it.
    for (int i = nums.length-1; i >= k; i--) {
        nums[i] = nums[i-k];
    }
    
    //Copy all the elements of tempArr to orignal array
    for (int i = 0; i < k; i++) {
        nums[i] = tempArr[i];
    }
  }
}
Complexity:
  • Time-Complexity : O(n)
  • Space Complexity : O(K)
Approach 2 : In-Place
  • the array is first reversed in its entirety.
  • then the first “k” elements are reversed, and
  • finally the remaining elements are reversed.
Java Code :
public void rotate(int[] nums, int k) {
        k = k % nums.length;

        reverseArr(nums, 0, nums.length-1);
        reverseArr(nums, 0, k-1);
        reverseArr(nums, k, nums.length-1);
}
    
static void reverseArr(int[] nums, int start, int end) {
        while(start <= end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        } 
 }
Complexity:
  • Time-Complexity: O(n)
  • Space Complexity: O(1)

Leave a comment