# 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

Category >> Algorithms >> Interview >> Java
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
1. sebastian on 2015-3-13

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.

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;
}

3. ygw on 2015-3-29

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.

4. Stephen Boesch on 2015-4-9

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

5. NotActually An FormulaFan on 2015-4-14

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

6. Sweta Shah on 2015-5-26

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.

7. sermyro on 2015-6-2

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

order = order % arr.length;

8. Holden on 2015-6-5

yeah, it should be:
if(order > arr.length){
d = d%arr.length;
}

9. ramesh on 2015-6-19

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]);

}

}

}

10. Hans Once on 2015-9-8

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;
}

11. 刘文月 on 2015-9-12

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

12. Java Pro on 2015-9-19

nice java array program collection http://tinyurl.com/programarray

13. Jeffrey Forde on 2015-10-28

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; } } ```

14. ats2 on 2015-11-1

Bubble rotate exceeds time.

15. RF on 2015-11-6

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];
}
}

}

16. Sujan Deb on 2015-11-10

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;
}

17. Jeffrey Forde on 2015-11-16

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 🙂

18. RF on 2015-11-17

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.

19. Drew on 2015-12-6

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));

}
}

20. Ryan Shaw on 2015-12-16

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) ```

21. Ryan Shaw on 2015-12-16

It is to solve two corner cases:
1) order is greater than arr. length
2) order is negative

22. Dmitry Egorov on 2015-12-23

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.

23. Mykhailo Aniskin on 2015-12-26

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;
}

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; } } ```

25. Mahesh V.Shet on 2016-2-3

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);
}

26. sudha on 2016-2-4

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++;
}

27. sudha on 2016-2-4

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++;

}

28. José Yánez on 2016-2-15

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);
}

29. khushbu on 2016-3-2

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]);

}

}

}

30. Rakesh on 2016-3-18

Soln using javascript. with O(n) time and O(1) space

rotate = function(){

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

var b = []

var k=3; //

var flag = true;

for(var i=0;i<a.length;i++,k++){

if(ka.length-1){

flag = false;

k = 0

}

if(!flag){

b[k] = a[i]

//j++

}

}

console.log(b);

}

31. amd on 2016-4-1

But isn’t this a more concise solution:

def rotate(a, k):
k = k % len(a)
return a[-k:] + a[:-k]

32. Matias SM on 2016-4-2

I believe that in Solution 3, it should say

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

33. Gunjan Bansal on 2016-4-13

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]);
}
}

}

34. Mms Sow on 2016-4-14

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]…)

}

35. ryanlr on 2016-4-15

It’s changed. Thanks.

36. Robina Li on 2016-5-4

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 );
}

37. floydbites on 2016-5-5

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)); ```

38. StBean on 2016-5-5

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); ```

39. Sreekar on 2016-5-23

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

40. Ranjeet on 2016-5-28

System.arraycopy() is not O(1) time

41. Robina Li on 2016-5-29

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.

42. Anonymous on 2016-6-22

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 –;
}

43. rupalph on 2016-7-24

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;
}

44. Anon on 2016-7-30

can’t you just swap elements from index 0 and index k until k = array length?

45. Akash Chaturvedi on 2016-8-1

System.arraycopy can not be O(1) time. Please check the StackOverflow thread here:
http://stackoverflow.com/questions/7165594/time-complexity-of-system-arraycopy

46. Noe Alejandro Perez Domínguez on 2016-9-12

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} ```

47. bpgen on 2016-9-28

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);

48. bpgen on 2016-9-28

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);

49. bpgen on 2016-9-29

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);

50. bpgen on 2016-9-29

``` 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); ```

51. bpgen on 2016-9-29

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);

52. Jesse Drogin on 2016-10-20

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; } } ```

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;

}

54. Mario R. Rincón-Díaz on 2016-12-11

Holy guacamole, that last solution with reversing is pretty amazing.

55. Dayakar B on 2016-12-19

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]);
}

}

}
}

56. ilovecat on 2017-1-3

Genius! I love the third solution!

57. Dushyanth Vihari on 2017-1-24

Can some one expalin 3rd soultion why it should work? 😐

58. ANAND on 2017-3-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);
}
}

59. ANAND on 2017-3-14

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);
}

}

60. jay on 2017-4-8

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;

}

61. Olas on 2017-7-24

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] + "]"); } } ```