Write a function that reverses a string in Python.
The shortest way is slicing with a negative step: s[::-1]. You can also use "".join(reversed(s)). Both build a new string in O(n) time, since strings cannot be changed in place.
Explain it simply
Slicing has the form s[start:stop:step]. Leaving start and stop empty and using step -1 walks the string from the last character to the first.
Line by line
def reverse_string(s):
return s[::-1]
def reverse_with_join(s):
return "".join(reversed(s))
def reverse_manual(s):
result = []
for ch in s:
result.insert(0, ch) # slow: O(n) each time
return "".join(result)
print(reverse_string("placement")) # Output: tnemecalp
print(reverse_with_join("python")) # Output: nohtyp
print(reverse_string("a")) # Output: areversed(s) returns an iterator, so join is needed to get a string back. The manual version works but insert(0, ...) shifts every element each time, making it O(n squared).
Complexity
Time O(n), space O(n) for the new string (the manual insert version is O(n squared) time).
What to say in the interview
"I'd use s[::-1], which is idiomatic and fast. If the interviewer wants no slicing, I loop and build a list, then join it. I avoid repeated string concatenation or insert(0) because they are quadratic."
Common mistakes
- Trying
s.reverse(). Strings have no such method; it belongs to lists.