Array Rotation Techniques in DSA C - Time & Space Complexity
We want to understand how the time taken to rotate an array changes as the array size grows.
How does the number of steps needed to rotate an array grow when the array gets bigger?
Analyze the time complexity of the following code snippet.
void rotateArray(int arr[], int n, int d) {
int temp[d];
for (int i = 0; i < d; i++) {
temp[i] = arr[i];
}
for (int i = d; i < n; i++) {
arr[i - d] = arr[i];
}
for (int i = 0; i < d; i++) {
arr[n - d + i] = temp[i];
}
}
This code rotates an array to the left by d positions using a temporary array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Three separate loops copying elements.
- How many times: First loop runs d times, second runs (n - d) times, third runs d times.
As the array size n grows, the total steps grow roughly in a straight line with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the size of the array.
Time Complexity: O(n)
This means the time to rotate grows in a straight line as the array gets bigger.
[X] Wrong: "Rotating an array always takes the same time no matter the size."
[OK] Correct: Actually, the bigger the array, the more elements you must move, so it takes more steps.
Understanding how array rotation scales helps you explain your code clearly and choose the best method during interviews.
"What if we used the reversal algorithm for rotation instead? How would the time complexity change?"
