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

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]
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:
Follow up:

Contents

In this approach, we will use a temporary array and copy last k elements of nums array into this temporary array first, then copy remaining elements from nums array, i.e. from 0th index to n-kth index into the temporary array. Finally replace nums array with the temporary array.

Implementation steps:
import java.util.Arrays; public class RotateArray { static void rotateUsingTempArray(int[] nums, int k) { k %= nums.length; // If k is greater than array length, we just need to rotate mod number of times. //Say if array is [1,2] and k=3, if we rotate 1st time-> [2,1], 2nd time -> [1,2] // 3rd time -> [2,1], this is equivalent to rotate 1st time. int[] temp = new int[nums.length]; int index=0; for(int i=nums.length-k; i<nums.length; i++) { temp[index++] = nums[i]; } for(int i=0;i<nums.length-k;i++) { temp[index++] = nums[i]; } for(int i=0;i< nums.length;i++) { nums[i] = temp[i]; } } public static void main(String[] args) { int[] nums = new int[]{1,2,3,4,5,6,7}; rotateUsingTempArray(nums, 3); System.out.println(Arrays.toString(nums)); nums = new int[]{1,2}; rotateUsingTempArray(nums, 3); System.out.println(Arrays.toString(nums)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of nums array.
Space complexity: O(n) for the temporary array.

In this approach, we will first reverse the input array nums, then reverse first k elements, then reverse remaining elements.

Example:
import java.util.Arrays; public class RotateArray { static void rotateUsingReverseAndReArrangeApproach(int[] nums, int k) { if(k ==0) { return; } k %= nums.length; reverse(nums, 0, nums.length-1); reverse(nums, 0, k-1); reverse(nums, k, nums.length-1); } static void reverse(int[] nums, int from, int to) { while(from<=to) { int temp = nums[from]; nums[from] = nums[to]; nums[to] = temp; from++; to--; } } public static void main(String[] args) { int[] nums = new int[]{1,2,3,4,5,6,7}; rotateUsingReverseAndReArrangeApproach(nums, 3); System.out.println(Arrays.toString(nums)); nums = new int[]{1,2}; rotateUsingReverseAndReArrangeApproach(nums, 3); System.out.println(Arrays.toString(nums)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of nums array.
Space complexity: O(1).

Above implementations source code can be found at GitHub link for Java code