String Reversal Approaches in DSA Python - Time & Space Complexity
We want to understand how the time needed to reverse a string changes as the string gets longer.
How does the work grow when the input string size increases?
Analyze the time complexity of the following code snippet.
def reverse_string(s: str) -> str:
result = []
for char in s:
result.insert(0, char)
return ''.join(result)
This code reverses a string by inserting each character at the start of a list, then joining the list into a string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each character in the string and inserting it at the start of the list.
- How many times: Once for each character in the string (n times).
Each insertion at the start shifts existing elements, so work grows faster than just the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 (sum of 1 to 10) |
| 100 | About 5,050 |
| 1000 | About 500,500 |
Pattern observation: Operations grow roughly with the square of the input size.
Time Complexity: O(n2)
This means the time needed grows roughly with the square of the string length because each insert shifts elements.
[X] Wrong: "Inserting at the start of a list is a quick, constant-time operation like appending at the end."
[OK] Correct: Inserting at the start requires moving all existing elements one step, so it takes longer as the list grows.
Understanding how different ways to reverse a string affect time helps you choose the best method in real problems.
"What if we used a list to collect characters by appending at the end and then reversed the list once at the end? How would the time complexity change?"
Practice
s in Python?Solution
Step 1: Understand string slicing
The slicing syntaxs[::-1]creates a new string with characters in reverse order.Step 2: Check other methods
s.reverse()ands.append()are list methods, not valid for strings.reversed(s)returns an iterator, not a string, so it needs conversion.Final Answer:
Using slicing: s[::-1] -> Option BQuick Check:
String slicing with negative step reverses string [OK]
- Trying to use list methods on strings
- Forgetting to convert reversed() iterator to string
- Using append() on strings
text = 'hello' and prints it?Solution
Step 1: Analyze each option
text.reverse()is invalid for strings.text[::-2]reverses with step 2, skipping characters.text.append()is invalid for strings.Step 2: Confirm correct syntax
reversed(text)returns an iterator of characters reversed.''.join()converts it back to string. This prints 'olleh'.Final Answer:
print(''.join(reversed(text))) -> Option DQuick Check:
reversed() + join() prints reversed string [OK]
- Using reverse() method on strings
- Using slicing with wrong step
- Trying to append to strings
def reverse_string(s):
result = ''
for char in s:
result = char + result
return result
print(reverse_string('abc'))Solution
Step 1: Trace the loop for s='abc'
Initially, result = ''. Iteration 1: char='a', result='a' + '' = 'a'. Iteration 2: char='b', result='b' + 'a' = 'ba'. Iteration 3: char='c', result='c' + 'ba' = 'cba'.Step 2: Return the reversed string
The function returns 'cba', which is the reverse of 'abc'.Final Answer:
'cba' -> Option AQuick Check:
Prepending chars reverses string [OK]
- Appending char instead of prepending
- Returning original string
- Confusing order of concatenation
def reverse_str(s):
s.reverse()
return s
print(reverse_str('hello'))Solution
Step 1: Check method usage on string
Thereverse()method exists for lists, not strings. Calling it on a string causes AttributeError.Step 2: Understand the error cause
Since strings are immutable, they do not support reverse(). The code will raise an error at runtime.Final Answer:
Strings do not have reverse() method -> Option CQuick Check:
reverse() is list method, not string method [OK]
- Trying to use reverse() on strings
- Expecting reverse() to modify string in place
- Ignoring immutability of strings
s = 'hello world' while keeping other characters in place. Which approach below correctly achieves this?Solution
Step 1: Understand the problem
We want to reverse only vowels, keeping consonants and spaces fixed in their places.Step 2: Analyze each option
Reverse entire string usings[::-1]reverses whole string, changing all characters. Usereversed(s)and join all characters reverses all characters, not just vowels. Replace vowels with '*' and then reverse string replaces vowels with '*', losing original vowels. Extract vowels, reverse them, then replace vowels in original positions extracts vowels, reverses them, then puts them back in original vowel positions, preserving other characters.Final Answer:
Extract vowels, reverse them, then replace vowels in original positions -> Option AQuick Check:
Reverse vowels only by extracting and replacing [OK]
- Reversing entire string instead of vowels only
- Replacing vowels with placeholders without restoring
- Ignoring character positions
Ready to prove it?
Pass the test and this pattern moves unknown
