Reverse a string without built-in functions
Filed under Microsoft
Free read 3 of 3Convert the string to a list of characters since strings are immutable.
The question
Reverse a string without using built-in functions like reverse() or slicing.
Constraints
- Do not use string slicing [::-1]
- Do not use built-in reverse functions
- Handle empty strings
Examples
- Input
- hello
- Output
- olleh
- Why
- Characters are swapped from ends towards the center.
Approach
Convert the string to a list of characters since strings are immutable.
Use two pointers, one at the start and one at the end of the list.
Swap elements at pointers and move pointers towards the center until they meet.
Solution
O(n) time, O(n) space
def solve(s):
chars = list(s)
left, right = 0, len(chars) - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return "".join(chars)
Tips
- What they are testing: Test with single-character strings and even/odd length strings.
- Common mistake: Trying to modify the string in-place in languages like Python where strings are immutable.
Related Microsoft questions
Collected from public candidate posts and coding forums. Updated Nov 2026.