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 input string size increases?
Analyze the time complexity of the following code snippet.
void reverseString(std::string &s) {
int left = 0, right = s.length() - 1;
while (left < right) {
std::swap(s[left], s[right]);
left++;
right--;
}
}
This code reverses a string 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 in the string.
- 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 (swaps) |
|---|---|
| 10 | 5 |
| 100 | 50 |
| 1000 | 500 |
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 quadratic time because of swapping characters inside a loop."
[OK] Correct: Each swap is a constant time operation, and the loop runs only about n/2 times, so total time grows linearly, not quadratically.
Understanding this simple linear time reversal helps build intuition for more complex string and array manipulations in interviews.
"What if we used recursion to reverse the string instead of a loop? How would the time complexity change?"
Practice
std::reverse function do when applied to a string in C++?Solution
Step 1: Understand std::reverse behavior
Thestd::reversefunction reverses the order of elements in a range, here characters in a string.Step 2: Apply to string
When applied to a string, it changes the string so the last character becomes first, and so on.Final Answer:
It reverses the order of characters in the string. -> Option AQuick Check:
std::reverse reverses string characters [OK]
- Thinking std::reverse sorts characters
- Confusing reversal with uppercase conversion
- Assuming it removes characters
s using std::reverse in C++?Solution
Step 1: Identify correct std::reverse usage
Thestd::reversefunction requires two iterators: start and end of the range.Step 2: Match syntax with string iterators
For strings,s.begin()ands.end()provide correct iterators.Final Answer:
std::reverse(s.begin(), s.end()); -> Option AQuick Check:
std::reverse needs begin and end iterators [OK]
- Using incorrect iterator names like start() or finish()
- Calling reverse without std:: prefix
- Passing string and indices directly
std::string s = "hello";
for (int i = 0; i < s.length() / 2; ++i) {
std::swap(s[i], s[s.length() - 1 - i]);
}
std::cout << s;Solution
Step 1: Understand the swapping loop
The loop swaps characters from start and end moving towards the center, effectively reversing the string.Step 2: Trace the swaps on "hello"
Swap s[0] and s[4]: 'h' and 'o' -> "oellh"; Swap s[1] and s[3]: 'e' and 'l' -> "olleh".Final Answer:
olleh -> Option CQuick Check:
Swapping pairs reverses string [OK]
- Not swapping correctly causing partial reversal
- Loop running too many or too few times
- Confusing indices causing wrong output
s.for (int i = 0; i <= s.length() / 2; ++i) {
std::swap(s[i], s[s.length() - i]);
}Solution
Step 1: Check the swap indices
The code usess[s.length() - i]. Fori=0, this accessess[s.length()], out of bounds.Step 2: Correct reversal index
To reverse, swaps[i]withs.length() - 1 - i.Final Answer:
The second index should be s.length() - 1 - i instead of s.length() - i to avoid out-of-range access. -> Option BQuick Check:
Missing -1 in second index causes out-of-range [OK]
- Off-by-one error: s.length() - i instead of s.length() - 1 - i
- Incorrect index calculation for swap
- Assuming std::swap can't swap chars
s, which approach below correctly reverses the string without using extra space and handles empty strings safely?Solution
Step 1: Analyze each approach
Use a for loop swapping characters from start to end with conditioni < s.length() / 2. swaps characters in place up to half length, safe for empty strings. Usestd::reverse(s.begin(), s.end() - 1);to reverse all but last character. misses last character. Create a new string and append characters from end to start. uses extra space. Use a while loop swapping characters untili > s.length(). has wrong loop condition.Step 2: Confirm correctness and safety
Use a for loop swapping characters from start to end with conditioni < s.length() / 2. reverses string in place without extra space and works for empty strings as loop won't run.Final Answer:
Use a for loop swapping characters from start to end with condition i < s.length() / 2. -> Option DQuick Check:
In-place swap up to half length reverses string safely [OK]
- Using incorrect end iterator causing partial reversal
- Creating new string uses extra space
- Wrong loop conditions causing infinite loops
Ready to prove it?
Pass the test and this pattern moves unknown
