Rotate Array in Java

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different ways do you know to solve this problem?

Solution 1 – Intermediate Array

In a straightforward way, we can create a new array and then copy elements to the new array. Then change the original array by using System.arraycopy().

public void rotate(int[] nums, int k) {
    if(k > nums.length) 
        k=k%nums.length;
 
    int[] result = new int[nums.length];
 
    for(int i=0; i < k; i++){
        result[i] = nums[nums.length-k+i];
    }
 
    int j=0;
    for(int i=k; i<nums.length; i++){
        result[i] = nums[j];
        j++;
    }
 
    System.arraycopy( result, 0, nums, 0, nums.length );
}

Space is O(n) and time is O(n). You can check out the difference between System.arraycopy() and Arrays.copyOf().

Solution 2 – Bubble Rotate

Can we do this in O(1) space?

This solution is like a bubble sort.

public static void rotate(int[] arr, int order) {
	if (arr == null || order < 0) {
	    throw new IllegalArgumentException("Illegal argument!");
	}
 
	for (int i = 0; i < order; i++) {
		for (int j = arr.length - 1; j > 0; j--) {
			int temp = arr[j];
			arr[j] = arr[j - 1];
			arr[j - 1] = temp;
		}
	}
}

However, the time is O(n*k).

Here is an example (length=7, order=3):

i=0
0 1 2 3 4 5 6 
0 1 2 3 4 6 5
...
6 0 1 2 3 4 5
i=1
6 0 1 2 3 5 4 
...
5 6 0 1 2 3 4 
i=2
5 6 0 1 2 4 3 
...
4 5 6 0 1 2 3  

Solution 3 – Reversal

Can we do this in O(1) space and in O(n) time? The following solution does.

Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:

1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Reverse first part: 4,3,2,1,5,6
3. Reverse second part: 4,3,2,1,6,5
4. Reverse the whole array: 5,6,1,2,3,4
public static void rotate(int[] arr, int order) {	
	if (arr == null || arr.length==0 || order < 0) {
		throw new IllegalArgumentException("Illegal argument!");
	}
 
	if(order > arr.length){
		order = order %arr.length;
	}
 
	//length of first part
	int a = arr.length - order; 
 
	reverse(arr, 0, a-1);
	reverse(arr, a, arr.length-1);
	reverse(arr, 0, arr.length-1);
 
}
 
public static void reverse(int[] arr, int left, int right){
	if(arr == null || arr.length == 1) 
		return;
 
	while(left < right){
		int temp = arr[left];
		arr[left] = arr[right];
		arr[right] = temp;
		left++;
		right--;
	}	
}

References:
1. Programming Pearls

71 thoughts on “Rotate Array in Java”

  1. PYTHON 3 – resolution -> sequence slicing and concatenation

    n = 20
    k = 10

    stend_1 = (n-k) + 1 # difference. obs: +1 to add the last position

    matrix_stop = [] #empty object --> fixed sequence

    matrix_move = [] #empty object --> moving sequence

    for i in range (1,stend_1): # sequence from 1 to 'stend_1 -> Difference'.

    matrix_stop.append(i) # adding value of position i to object

    print(f'{matrix_stop} matrix stop n')

    while n > k: # recursive loop

    if n >= stend_1: # only values ​​greater than 'stend_1'

    matrix_move.append(n) # adding value of position "n" to object

    matrix_move.sort() #sorting list

    n -= 1 #decrementation '-1' -> returns to 'while' validation

    print(f'{matrix_move} matrix move n')

    print(f'{matrix_move+matrix_stop} concatenate list')

  2. public static void RotateArrayAndPrint(int[] n, int rotate)
    {
    for (int i = 1; i n.Length ? n.Length – (i + rotate) : (i + rotate);
    arrIndex = arrIndex < 0 ? arrIndex * -1 : arrIndex;
    var output = n[arrIndex-1];
    Console.Write(output + " ");
    }
    }

  3. Please check this solution in javascript:

    What I did:
    I copied the array exactly in front of the given array and did a small mathematics to return the rotated array.


    // Rotating Array
    const main = (array, rotatingTimes) =>
    !array || rotatingTimes > array.length
    ? []
    : [...array, ...array]
    .slice(array.length - rotatingTimes, array.length + rotatingTimes + 1);

    console.log(main([1, 2, 3, 4, 5, 6, 7], 3));

  4. In python3:

    def rotateByK(A,k):
    — n = len(A)
    — if k>n:
    — — k = n%k
    — for i in range(k):
    — — A.insert(0,A.pop())
    — return A

  5. Using single for loop –

    import java.util.Arrays;
    public class RotateArray {
    public static int[] rotate(int arr[] , int k) {
    int arr1[] = new int[arr.length];
    boolean flag = false;
    int j =0;
    for(int i= arr.length-k;i<arr.length ; i++) {
    if(i==arr.length-1 && !flag) {
    arr1[j++] = arr[i];
    i = 0;
    flag = true;

    }

    if(i == arr.length-k-1 && flag) {
    arr1[j++] = arr[i];
    break;

    }
    arr1[j++] = arr[i];
    }
    return arr1;
    }
    public static void main(String[] args) {
    int []rotated = rotate(new int[]{1,2,3,4,5,6,7},4);
    System.out.println(Arrays.toString(rotated));
    }

    }

  6. Not using temporary array, O(n) time, modulo operator is used only once
    `
    public static int[] rotate(int[] array, int steps){
    int length = array.length;
    steps = steps % length;
    if (steps == 0) {
    return array;
    }
    int m = 0;
    int replacingWith = array[0];
    for (int n=0, k=steps; n= length)? length:0;
    int l = (k==m)? ++m: k;
    int replaced = array[l];
    array[k] = replacingWith;
    replacingWith = replaced;
    k=l;
    }
    return array;
    }
    `

  7. Here is my simple, efficient Java Solution. O(n) time complexity.

    public static void rotate(int[] arr, int order) {
    int[] results = new int[arr.length];
    int n = arr.length;

    for (int i = order + 1, b = 0; i < n; b++, i++) {
    results[b] = arr[i];
    if (i == n - 1) {
    for (int j = 0; j <= order; j++) {
    results[b + 1] = arr[j];
    b++;
    }
    }
    }
    System.out.println(Arrays.toString(results));
    }

  8. // Optimal algorithm: each element goes directly to it’s final position (no additional swaps).
    // Complexity: O(n) time, O(1) space
    public static void RotateArrayCyclicSwap(int[] arr, int k) {
    int n = arr.length, p = k + 1;

    if(!(0 < p && p < n)) return;

    for(int j = 0; j < GreatestCommonDivisor(n, p); j++) {
    for(int i = j + n – p % n; i != j; i = (i + n – p) % n) {
    swap(arr, j, i);
    }
    }
    }

    public static int GreatestCommonDivisor(int a, int b) {
    int t;
    if(a < b) {
    t = a; a = b; b = t;
    }

    while(b != 0) {
    t = b;
    b = a % b;
    a = t;
    }

    return a;
    }

    public static void swap(int[] arr, int i, int j) {
    if(i != j) {
    arr[i] ^= arr[j];
    arr[j] ^= arr[i];
    arr[i] ^= arr[j];
    }
    }

  9. Heres my solution with O(1) space and O(n) time

    public class myClass{

    public static void main(String [] args ){
    int[] arr = {1,2,3,4,5};
    printArray(arr);
    rotateArr (arr, 3);

    }

    public static void rotateArr(int [] arr, int order){

    // assuming array has at least 1 value
    int prev_v = arr[0];
    int prev_i = 0;
    int next_v ;
    int next_i ;

    // get new spot for each arr value
    int offset = order % arr.length;

    for (int i = 0 ; i < arr.length; i++){

    //save overwritten value at offset
    next_v = arr[( prev_i + order) % arr.length ];
    next_i =( prev_i + order) % arr.length;

    // store current index value in the right rotated location
    arr[ (prev_i + order) % arr.length ] = prev_v;

    // reset previous index so we do not rotate any index more than once
    prev_v = next_v;
    prev_i = next_i;

    }

    printArray(arr);

    }

    public static void printArray(int [] arr){
    System.out.print("[");
    int i = 0;
    for (; i <= arr.length-2; i++){
    System.out.print(arr[i] + ",");
    }
    System.out.println(arr[i] + "]");

    }
    }

  10. I think the simplest way is recursion:

    public class ReverseArray {

    public static void main(String[] args) {
    Integer[] array = new Integer[]{1,2,3,4,5,6,7};
    List list = new ArrayList(Arrays.asList(array));
    reverseInKStep(list, 3);
    }

    public static void reverseInKStep(List list, int k) {
    if(k<0)
    return;
    k = k-1;
    list.add(list.get(0));
    list.remove(0);
    reverseInKStep(list, k);
    }
    }

  11. public static int[] arrayLeftRotation(int[] a, int n, int k) {
    int b[] = new int[a.length];
    int j =0;
    for( int i=0; i <n ; i++){
    if( i+k < n)
    b[i] = a[i+k];
    else
    b[i] = a[j++];

    }
    return b;

    }

  12. public static void main(String[] args) {
    int ar[]={1,2,3,4,5,6,7};
    int k=3;
    int n =ar.length;
    for(int i=n-k;i0){
    ar[j]=ar[j-1];
    j–;
    }
    ar[j]=temp;
    }
    for(int e: ar){
    System.out.println(e);
    }

    }

  13. public static void main(String[] args) {
    int ar[]={1,2,3,4,5,6,7};
    int n =ar.length-1;
    for(int i=0;i<=n/2;i++){
    int temp=ar[i];
    ar[i]=ar[n-i];
    ar[n-i] = temp;
    }
    for(int e: ar){
    System.out.println(e);
    }
    }

  14. public class ArrayRotate {
    public static void main(String[] args) {
    int[] a = {1,2,3,4,5,6,7};
    rotateArray(a,36);

    }

    private static void rotateArray(int[] a, int timesToRotate) {

    if(a != null && a.length > 0){
    int[] target = new int[a.length];
    int length = a.length;
    for (int i = 0; i < target.length; i++) {
    //System.out.println(timesToRotate%a.length);
    target[(timesToRotate++%a.length)] = a[i];
    }

    for (int i = 0; i < target.length; i++) {
    System.out.println(target[i]);
    }

    }

    }
    }

  15. private static Integer[] rotateNumberArrayByIndex(Integer[] inputArr, int lastKElementsLength) {

    System.out.println(“inputArr : “+Arrays.toString(inputArr));

    System.out.println(“lastKElementsLength : “+lastKElementsLength);

    Integer tmpArr[] = null;

    if (lastKElementsLength > 0 && inputArr != null) {

    int lengthOfInputArr = inputArr.length;

    if (lengthOfInputArr > 0) {

    int reverseStartIndex = (lengthOfInputArr – lastKElementsLength);

    if (reverseStartIndex > 0) {

    tmpArr = new Integer[lengthOfInputArr];

    int rotatedArrStartIndex = 0;

    int rotatedArrLastIndex = lastKElementsLength;

    for (int inputArrIndex = 0; inputArrIndex < lengthOfInputArr; inputArrIndex++) {

    if(inputArrIndex < reverseStartIndex) {

    tmpArr[rotatedArrLastIndex++] = inputArr[inputArrIndex];

    } else {

    tmpArr[rotatedArrStartIndex++] = inputArr[inputArrIndex];

    }

    }

    } else {

    System.out.println("Provide postive number");

    tmpArr = inputArr;

    }

    } else {

    System.out.println("Input array length is null");

    tmpArr = inputArr;

    }

    } else {

    System.out.println("Input array is null");

    tmpArr = inputArr;

    }

    inputArr = null;

    System.out.println("tmpArr : "+Arrays.toString(tmpArr));

    return tmpArr;

    }

  16. here’s an O(n) time, O(1) space where you rotate forward k spots. If you return to the current starting point, increment the starting point by 1 and repeat. Keep track of the number of moves, when number of moves equals n you are done.


    static void Rotate(int[] arr, int k)
    {
    int n = arr.Length;
    k = k % n;
    int count = 0;
    int start = k;

    while (count < n)
    {
    int index = start;
    int prev = arr[(start - k + n) % n];
    do
    {
    int temp = arr[index];
    arr[index] = prev;
    prev = temp;
    index = (index + k) % n;
    count++;
    }
    while (index != start && count < n);

    start = (start + 1) % n;
    }
    }

  17. int[] arr = {1,2,3,4,5,6,7};
    int firstIndex = 0;
    int k = 3;
    int[] newArr = new int[arr.length];
    for (int i = 0; i <arr.length ; i++) {
    newArr[i]=arr[(++firstIndex + k)%arr.length];
    }
    Arrays.stream(newArr).forEach(System.out::println);

  18. int[] arr = {1,2,3,4,5,6,7};
    int firstIndex = 0;
    int k = 3;

    int[] newArr = new int[arr.length];
    for (int i = 0; i <arr.length ; i++) {
    newArr[i]=arr[(++firstIndex + k)%arr.length];
    }
    Arrays.stream(newArr).forEach(System.out::println);

  19. int[] arr = {1,2,3,4,5,6,7};
    int firstIndex = 0;
    int k = 3;

    int[] newArr = new int[arr.length];
    for (int i = 0; i <arr.length ; i++) {
    newArr[i]=arr[(++firstIndex + k)%arr.length];
    }
    Arrays.stream(newArr).forEach(System.out::println);

  20. int[] arr = {1,2,3,4,5,6,7};
    int firstIndex = 0;
    int k = 3;

    int[] newArr = new int[arr.length];
    for (int i = 0; i <arr.length ; i++) {
    newArr[i]=arr[(++firstIndex + k)%arr.length];
    }
    Arrays.stream(newArr).forEach(System.out::println);

  21. int[] arr = {1,2,3,4,5,6,7};
    int firstIndex = 0;
    int k = 3;

    int[] newArr = new int[arr.length];
    for (int i = 0; i <arr.length ; i++) {
    newArr[i]=arr[(++firstIndex + k)%arr.length];
    }
    Arrays.stream(newArr).forEach(System.out::println);

  22. A possible one liner solution in Scala


    def rotateArray(xs: List[Int], k: Int): List[Int] =
    xs.splitAt(xs.length - k) match {case (x, y) => List(y, x).flatten}

  23. O(n) and O(1) space solution:

    public int[] roatateArray(int[] a,int k)
    {
    int last = a[0];
    int start = k;
    for(int j=0;j<k;j++) {
    for(int i=start;i<a.length;i+=k)
    {
    int tmp=a[i];
    a[i]=last;
    last=tmp;
    }
    start–;
    if (start<=0) break;
    }
    a[0]=last;
    return a;
    }

  24. String str =”ABCDEFGHI”;
    char[] arr = str.toCharArray();
    int start = 0;
    int end = arr.length-1;
    while(start<end){
    char temp = arr[start];
    arr[start] = arr[end];
    arr[end]= temp;
    start++;
    end –;
    }

  25. Yes, you are right. It is not O(N). 😀
    Bases on test results, it is indeed better than O(N) in timing. Though need the library source code to ensure.

  26. Simple and elegant than any other above solutions. It is more natural solution to this problem actually.

  27. JavaScript function which will rotate after the kth index of an array:


    var input2 = [1,2,3,4,5,6,7];

    function rotatArray2(k, data){
    return data.splice(k + 1, data.length).concat(data.splice(0, k + 1));
    };
    var res2 = rotatArray2(3, input2);

  28. good ole JavaScript

    function rotatArray(n, k, data){
    var res = data.splice(n + 1, k).concat(data.splice(0, n + 1));
    return res;
    };
    console.log(rotatArray(3, 7, data));

  29. Actually, this rotate can be resolve by shift and copy:
    1. shift fist (length – k) to right by k;
    2 copy last k to position 0.

    public void rotate(int[] arr, int k) {
    if(k > arr.length)
    k=k%arr.length;

    int[] tmp = new int[arr.length];

    System.arraycopy( arr, arr.length – k, tmp, 0, k );
    System.arraycopy( arr, 0, tmp, k , arr.length – k );
    System.arraycopy( tmp, 0, arr, 0, arr.length );
    }

  30. Golang solution for rotate

    package main

    import “fmt”

    func main() {
    fmt.Println(rotate([]int{1,2,3,4,5,6,7}, 4))
    }

    func rotate(data []int, k int) []int{

    return append(data[k:], data[0:k]…)

    }

  31. public class Rotatearray {

    /**
    * @param args
    * @throws IOException
    */
    public static void main(String[] args) throws IOException {
    int a[]={1,2,3,4,5,6};
    int temp1[],temp2[];
    temp1=new int[10];
    temp2=new int[10];

    int i=2;

    for (int j=0;j2;j–)
    {
    temp2[j]=a[k];
    k–;
    System.out.println(temp2[j]);
    }
    for (int j=5;j>2;j–)
    {
    System.out.print(temp2[j]);
    }
    for (int j=2;j>=0;j–)
    {
    System.out.print(temp1[j]);
    }
    }

    }

  32. I believe that in Solution 3, it should say

    2. Reverse first …
    3. Reverse second …
    4. Reverse the whole …

    Instead of * Rotate …

  33. hi , rotating a array element by k step can be done by this way —

    public static void rotateByKStep(int[] arr , int pass){

    int size =arr.length;

    if(pass==7||pass==0){

    for(int a : arr){

    System.out.print(a);

    }

    return;

    }
    else if(pass>size){

    pass=pass%size;

    }

    int index , currentIndex;

    index=pass;

    for(int i=0;i<size;i++){

    currentIndex=(index++)%(size);

    System.out.print(arr[currentIndex]);

    }

    }

    }

  34. Why didn’t any one come up with this?

    This is one is O(n) space and O(n/2) execution..

    public static void Run()
    {
    int[] x = new int[] { 9, 2, 2, 5, 1, -4 };
    int start = 0;
    int end = x.Length – 1;

    while (end – start >= 1)
    {
    ArraySwapping.Swap(x, end, start);
    end–;
    start++;
    }

    Printing.PrintArray(x);
    Console.Read();
    }

  35. int n =array.length; int k=3;int j=0;

    j = k;

    for(int i=0;i<n-k;i++)

    {

    newres[j] = array[i];

    j++;

    }

    j=0;

    for(int i=n-k;i<n;i++)

    {

    newres[j] = array[i];

    j++;

    }

  36. int[] result = {0,1,2,3,4,5,6,8,9,10};
    int[] newres = new int[result.length];
    int n =result.length; int k=3;int j=0;
    j = k;
    for(int i=0;i<n-k;i++)
    {
    newres[j] = result[i];
    j++;
    }
    j=0;
    for(int i=n-k;i<n;i++)
    {
    newres[j] = result[i];
    j++;
    }

  37. If the order is zero, the third solution rotates the array twice, once in the reverse direction and again in forward direction. Can be avoided if we put a check in rotate method for order size zero check:

    public static void rotate(int[] arr, int order) {
    order = order % arr.length;
    if (arr == null || order < 0) {
    throw new IllegalArgumentException("Illegal argument!");
    }

    if (order == 0) {
    return;
    }

    //length of first part
    int a = arr.length – order;

    reverse(arr, 0, a-1);
    reverse(arr, a, arr.length-1);
    reverse(arr, 0, arr.length-1);
    }

  38. C++ soloution


    void rotate_array(int* number_array,int size, int rotate_index)
    {
    int temp = 0;
    for(int i=0 ; i< rotate_index; i++)
    {
    temp = number_array[i];
    number_array[i] = number_array[size-rotate_index+i];
    number_array[size-rotate_index+i] = temp;
    }
    }

  39. Haven’t tested:

    private static void RotateArray(int[] arr, int n)
    {
    if (arr == null || arr.Length == 0 || (arr.Length + n) % arr.Length == 0) return;

    var count = arr.Length – 1;
    var index = 0;
    var item = arr[index];

    while (count > 0)
    {
    index = (arr.Length + index + n) % arr.Length;
    var item1 = arr[index];
    arr[index] = item;
    item = item1;
    count–;
    }

    arr[0] = item;
    }

  40. Actually, the original won’t work not only when the length is evenly divisible by the shift amount, but also when their greatest common divisor is not 1. E.g. length is 9 and shift is 6. But the new solution solves this problem too.

  41. Python solution:


    def reverse_array(arr, begin, end):
    """Reverse arr in range [begin, end]"""
    if begin = len(arr): return
    if end = len(arr): return
    while begin < end:
    tmp = arr[begin]
    arr[begin] = arr[end]
    arr[end] = tmp
    begin += 1
    end -= 1

    def rotate(arr, k):
    n = len(arr)
    reverse_array(arr, 0, (n - k - 1) % n)
    reverse_array(arr, (n - k - 1) % n + 1, n - 1)
    reverse_array(arr, 0, n - 1)

  42. public class Rotate {
    public static void main(String[] args) {
    if(args.length != 1) {
    System.out.println(“USAGE: java rotate “);
    System.exit(1);
    }

    int offset = Integer.parseInt(args[0]);
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int[] rotated = new int[numbers.length];

    System.out.println(“Original Array: ” + Arrays.toString(numbers));

    int index;
    for(int n=0; n < numbers.length; n++) {
    index = (n + offset) % numbers.length;
    rotated[index] = numbers[n];
    }

    System.out.println("Rotated Array: " + Arrays.toString(rotated));

    }
    }

  43. Hmmm…you are correct. I think I might have attributed my bug to you. I started with your algorithm, fixed the evenly-divisible bug, but then it didn’t work with larger shift values. That was my bug. Then I added that initial modulus in to solve some cases, but it didn’t fix it all. I then figured out the final solution, which I guess made that line obsolete.

  44. Good catch on the even division case! I believe the previous solution did work with a shift greater than the length when the displaced_position was set. (With the exception of the case you pointed out of course). In fact I removed the shift reset in your code and all of my tests pass – including that case.
    Btw – Just realized my snake casing. Been in Ruby a lot lately 🙂

  45. How do you like this

    static int[] rotate(int arr[], int k) {
    int result[] = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
    result[(i + k) % arr.length] = arr[i];
    }
    return result;
    }

  46. Your solution fails an important case. When the array length is evenly divisible by the shift amount, you either end up with nothing shifted (if length/shift is even), or only every n-th letter shifted (where n = shift, and length/shift is odd). Example, try rotating a 6 value array by 3 positions.

    Also, you should account for the case where shift >= length, either by throwing an exception or by using a modulus.

    Here a solution that accounts for both:

    public static void rotateRightIP(int[] arr, int shift) {

    if (arr == null || shift < 0 ) {
    throw new IllegalArgumentException("Illegal Argument");
    }

    shift = shift % arr.length;

    int start_position = 0;
    int current_position = start_position;
    int current_value = arr[current_position];

    for(int i = 0; i < arr.length; i++) {
    int displaced_position = (current_position + shift) % arr.length;
    int displaced_value = arr[displaced_position];
    arr[displaced_position] = current_value;
    current_position = displaced_position;
    current_value = displaced_value;

    if (current_position == start_position) {
    start_position = (current_position + 1) % arr.length;
    current_position = start_position;
    current_value = arr[current_position];
    }
    }

    }

  47. Another solution O(1) space, O(n) time. This algorithm moves each value to it’s position after it has been displaced by the one before it, starting with the value at position 0.


    public static void rotateRightIP(int[] arr, int shift) {
    if (arr == null || shift < 0) {
    throw new IllegalArgumentException("Illegal Argument");
    }

    int current_position = 0;
    int current_value = arr[current_position];

    for(int i = 0; i < arr.length; i++) {
    int displaced_position = (current_position + shift) % arr.length;
    int displaced_value = arr[displaced_position];
    arr[displaced_position] = current_value;
    current_position = displaced_position;
    current_value = displaced_value;
    }
    }

  48. Hello ,In Solution 2 ,Could you tell me the purpose of the “order = order % arr.length;”? I am a newbie.

  49. public int[] reverseHalf(int[] numbers) {

    int[] temp = new int[numbers.size()];
    int j =0;

    // loop just once
    for (int i = numbers.size()/2; i < numbers.size(); i++) {
    temp[j]=numbers.get(i);
    temp[i]=numbers.get(j);
    j++;
    }
    return temp;
    }

  50. public class ArrayRotation {

    public static void main(String[] args) {

    int[] i = { 1, 2, 3, 4 };

    int[] l = new int[4];

    int k = 2;

    while (k > 0) {

    for (int j = i.length – 1; j >= 0; j–) {

    l[j] = i[i.length – j-1];

    }

    k–;

    }

    for (int o = 0; o < l.length; o++) {

    System.out.println(l[o]);

    }

    }

    }

  51. In solution 3 – Reversal:
    case when arr.length ==0
    divided by zero

    order = order % arr.length;

  52. One more solution similar to first one:

    public static void rotateArray(int[] arr, int k) {

    final int[] newArr = new int[arr.length];

    final int remNumLength = arr.length – k;

    System.arraycopy(arr, remNumLength, newArr, 0, k);
    System.arraycopy(arr, 0, newArr, k, remNumLength);
    System.arraycopy(newArr, 0, arr, 0, arr.length);

    System.out.println(Arrays.toString(arr));
    }

    This is O(n) for both time and space complexity.

  53. why is this faster than switching arr[i] and arr[length-i] for i =0; i < length / 2; i++

  54. The elements in the second part are not being rotated. Also: your bounds “k-n to k-n+1 are incorrect. should be n-k and n-k+1

  55. O(n) time O(1) space solution:

    1. Divid the array to 3 parts: 1 to k, k+1 to k-n, k-n+1 to n (for k n/2)

    2. Swap part 1 and part 3

    3, first k elements are in their final place.

    4. Last n-k elements need rotation by k — which is recursive with less elements repeating step 1-3.

    5. Ending condition: only one or two elements need rotation.

  56. Another O(n) space O(n) solution:

    public int[] rotate(int[] nums, int k) {

    int[] result = new int[nums.length];

    for (int i = 0; i < nums.length; i++) {
    result[(i + k) % nums.length] = nums[i];
    }

    return result;
    }

  57. hi, in the second solution you need to subtract 1 value “condition of the for” like that
    for (int i = 0; i < order -1 ; i++) {
    Because your doing 1 itaration more than you need.

Leave a Comment