Saturday, January 30, 2016

Rotate an array in place

Rotate an array in place


Problem:
Rotate a one-dimensional array of n elements to the right by k steps.
For instance, with n=7 and k=3, the array {a, b, c, d, e, f, g} is rotated to {e, f, g, a, b, c, d}.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
   String reverse(String str, int i, int j)
{
    char[] arr = str.toCharArray();
    for(;i<j; i++, j--) {
        char temp = arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
    }
    return String.valueOf(arr);
}
 
/**
 * Rotate the string to right by k chars
 *
 * @param str
 * @param n
 * @param k
 */
String rotate(String str, int n, int k)
{
    //Reverse entire string
    str = reverse(str, 0, n-1);
    str = reverse(str, 0, k-1);
    str = reverse(str, k, n-1);
    return str;
}

No comments:

Post a Comment