Rotation of Array

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

Example 1:

Input: [1,2,3,4,5,6,7] and 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]

1. Using Temporary Array:

We use a temporary array in which we place every element of the input array at its correct position.The ith element of the input array should be placed in the (i + k)%(input_array.length) th position of the temporary array.

/**
 * Rotation by temp array
 * @param nums
 * @param k
 */
public static void rotate_2(int[] nums, int k) {
  int[] a = new int[nums.length];
  for (int i = 0; i < nums.length; i++) {
    a[(i + k) % nums.length] = nums[i];
  }
  // Copy the temp array to the original array
  for (int i = 0; i < nums.length; i++) {
    nums[i] = a[i];
  }
}

The Time Complexity is O(n) and Space Complexity is also O(n).

2. By Reversing the Array:

In this approach, we firstly reverse all the elements of the array. Then, reversing the first k elements followed by reversing the rest n−k elements gives us the required result.

Original List  : 1 2 3 4 5 6 7
After reversing all numbers : 7 6 5 4 3 2 1
After reversing first k numbers : 5 6 7 4 3 2 1
After revering last n-k numbers : 5 6 7 1 2 3 4 
/**
 * In place rotation
 * @param nums
 * @param k
 */
public static void rotate_1(int[] nums, int k) {
  int len = nums.length;
  // If given k in greater than array length
  k = k % len;
  reverse(nums, 0, nums.length - 1);
  reverse(nums, 0, k - 1);
  reverse(nums, k, nums.length - 1);
}

private static void reverse(int[] arr, int start, int end) {
  while (start < end) {
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    start++;
    end--;
  }
}

Complexity Analysis

  • Time complexity: O(n). n elements are reversed a total of three times.
  • Space complexity: O(1). No extra space is used.
Arrays Algorithm