Rotate array in C: solved exercise
Rotate array in C: solved exercise
If you searched for a solved rotate array exercise in C, here is the three-reversal trick: rotate an array k positions left or right in O(n) time and O(1) extra space, with no auxiliary buffer needed.
The idea is that rotating an array is equivalent to reversing three sub-sequences: the block being shifted, the remainder, and then the entire array.
Problem statement
Given the array {1, 2, 3, 4, 5, 6, 7}:
- Rotate it 3 positions to the left →
{4, 5, 6, 7, 1, 2, 3}. - Rotate it 2 positions to the right →
{6, 7, 1, 2, 3, 4, 5}.
Use the three-reversal algorithm in both cases.
C solution
Expected output
Common mistakes
- Not reducing
kwithk %= n: ifk >= n, computingk - 1gives an out-of-bounds index. - Confusing left with right: rotating left by
kis equivalent to rotating right byn - k. - Using an auxiliary buffer of size
k: functionally correct but uses O(k) extra space; the three-reversal algorithm is O(1). - Getting the three ranges wrong: for a left rotation they must be
[0, k-1],[k, n-1], and[0, n-1], in that order.
Practical use
Array rotation is used in circular buffers, FIFO queue implementations with arrays, signal processing (sliding windows), and string problems such as detecting rotation anagrams.
Recommended next exercise
- Maximum subarray: Kadane in C: solved exercise
- Two pointers in C: solved exercise
- Transposed matrix in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why does the three-reversal algorithm work?
Rotating left by k transforms [A|B] into [B|A]. Reversing A gives [A'|B], then reversing B gives [A'|B'], and finally reversing the whole array gives [B|A]. The three in-place reversals achieve the rotation without any copies.
How do you handle k larger than n?
Use k %= n. Rotating by n positions is the same as not rotating. With the modulo, k = 9 on a 7-element array is equivalent to k = 2.
Can the same algorithm rotate a string?
Yes. A C string is an array of char, so reverse and rotate_left work identically by replacing int with char and passing strlen(s) as n.