Bird
0
0
DSA Cprogramming~5 mins

String Reversal Approaches in DSA C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String Reversal Approaches
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the string gets longer, the number of swaps grows roughly in direct proportion to its length.

Input Size (n)Approx. Operations
105 swaps
10050 swaps
1000500 swaps

Pattern observation: Doubling the string length roughly doubles the number of swaps.

Final Time Complexity

Time Complexity: O(n)

This means the time to reverse the string grows linearly with the string length.

Common Mistake

[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.

Interview Connect

Understanding how simple loops scale helps you explain your code clearly and shows you know how to reason about efficiency.

Self-Check

"What if we used recursion to reverse the string? How would the time complexity change?"