String Reversal Approaches in DSA C - Time & Space Complexity
We want to understand how the time needed to reverse a string changes as the string gets longer.
How does the number of steps grow when the string size grows?
Analyze the time complexity of the following code snippet.
void reverseString(char* str) {
int start = 0;
int end = strlen(str) - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
This code reverses a string in place by swapping characters from the start and end moving towards the center.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Swapping two characters inside a loop.
- How many times: About half the length of the string (n/2 times).
As the string gets longer, the number of swaps grows roughly in direct proportion to its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 swaps |
| 100 | 50 swaps |
| 1000 | 500 swaps |
Pattern observation: Doubling the string length roughly doubles the number of swaps.
Time Complexity: O(n)
This means the time to reverse the string grows linearly with the string length.
[X] Wrong: "Reversing a string takes constant time because we just swap characters."
[OK] Correct: Each character must be visited and swapped, so the time grows with the string size, not fixed.
Understanding how simple loops scale helps you explain your code clearly and shows you know how to reason about efficiency.
"What if we used recursion to reverse the string? How would the time complexity change?"
