Rotating an array in place
April 13, 2010 in Uncategorized
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}.
In my previous post we discussed about finding an element in a rotated array. You might ask, how do we rotate an array?
The straight forward way is to allocate a temporary array of size n, and then copy elements starting from index k to the new array, and copy it back to the old array. This is highly inefficient because:
- It needs extra space to store a temporary array (O(n) space).
- It involves back-and-forth copying, a total of 2*n copy operations.
So, the question is, can we do this more efficiently, preferably an in-place rotation method.
The answer is of course, yes. This is a trick so important that it becomes one of the frequently asked interview questions. An in-depth discussion is in Programming Pearls, one of the must-read book in Computer Science.
The trick is to do three reverse operation. One for the entire string, one from index 0 to k-1, and lastly index k to n-1. Magically, this will yield the correct rotated array, without any extra space! (Of course, you need a temporary variable for swapping).
void reverse_string(char* str, int left, int right) { char* p1 = str + left; char* p2 = str + right; while (p1 < p2) { char temp = *p1; *p1 = *p2; *p2 = temp; p1++; p2--; } } void rotate(char* str, int k) { int n = strlen(str); reverse_string(str, 0, n-1); reverse_string(str, 0, k-1); reverse_string(str, k, n-1); }