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>
  • Radhe Krishna

    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;

    }

  • Jesse Drogin

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

  • bpgen

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

  • bpgen

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

  • bpgen

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

  • bpgen

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

  • bpgen

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

  • Noe Alejandro Perez Domínguez

    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}

  • Akash Chaturvedi

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

  • Anon

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

  • rupalph

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

  • Anonymous

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

  • Robina Li

    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.

  • Ranjeet

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

  • Sreekar

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

  • StBean

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

  • floydbites

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

  • Robina Li

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

  • ryanlr

    It’s changed. Thanks.

  • Mms Sow

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

    }

  • Gunjan Bansal

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

    }

  • Matias SM

    I believe that in Solution 3, it should say

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

    Instead of * Rotate …

  • amd

    But isn’t this a more concise solution:

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

  • Rakesh

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

    }

  • khushbu

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

    }

    }

    }

  • José Yánez

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

  • sudha

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

    }

  • sudha

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

  • Mahesh V.Shet

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

  • Nayana Adassuriya

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

  • Mykhailo Aniskin

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

  • Dmitry Egorov

    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.

  • Ryan Shaw

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

  • Ryan Shaw

    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)

  • Drew

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

    }
    }

  • RF

    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.

  • Jeffrey Forde

    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 🙂

  • Sujan Deb

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

  • RF

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

    }

  • ats2

    Bubble rotate exceeds time.

  • Jeffrey Forde

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

  • Java Pro

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

  • 刘文月

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

  • Hans Once

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

  • ramesh

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

    }

    }

    }

  • Holden

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

  • sermyro

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

    order = order % arr.length;

  • Sweta Shah

    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.

  • NotActually An FormulaFan

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

  • Stephen Boesch

    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

  • ygw

    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.

  • Djallal Serradji

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

  • sebastian

    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.