Reverse String
Difficulty: Easy Source: NeetCode
Problem
Write a function that reverses an array of characters in-place. You must do this by modifying the input array with
O(1)extra memory.Example 1: Input:
s = ['h','e','l','l','o']Output:['o','l','l','e','h']Example 2: Input:
s = ['H','a','n','n','a','h']Output:['h','a','n','n','a','H']Constraints:
1 <= s.length <= 10^5s[i]is a printable ASCII character
Prerequisites
Before attempting this problem, you should be comfortable with:
- Arrays — index-based access and in-place modification
- Two Pointers — using two indices that move toward each other from opposite ends
1. Brute Force
Intuition
Create a reversed copy of the array and write it back into the original. Python’s slicing makes this a one-liner, but it uses O(n) extra space — which violates the problem’s constraint. It’s still useful as a baseline to understand what we’re trying to achieve.
Algorithm
- Create a reversed copy of
susing slicing:s[::-1]. - Write each element of the reversed copy back into
s.
Solution
def reverseString(s):
reversed_copy = s[::-1]
for i in range(len(s)):
s[i] = reversed_copy[i]
s = ['h', 'e', 'l', 'l', 'o']
reverseString(s)
print(s) # ['o', 'l', 'l', 'e', 'h']
s = ['H', 'a', 'n', 'n', 'a', 'h']
reverseString(s)
print(s) # ['h', 'a', 'n', 'n', 'a', 'H']
s = ['a']
reverseString(s)
print(s) # ['a']
Complexity
- Time:
O(n) - Space:
O(n)
2. Two Pointers
Intuition
Place one pointer at the start and another at the end of the array. Swap the characters they point to, then move both pointers inward. Keep going until the pointers meet in the middle. Each swap fixes two characters at once, so we only need n/2 swaps total — and we never need any extra storage.
Algorithm
- Initialize
left = 0andright = len(s) - 1. - While
left < right:- Swap
s[left]ands[right]. - Increment
left, decrementright.
- Swap
Solution
def reverseString(s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
s = ['h', 'e', 'l', 'l', 'o']
reverseString(s)
print(s) # ['o', 'l', 'l', 'e', 'h']
s = ['H', 'a', 'n', 'n', 'a', 'h']
reverseString(s)
print(s) # ['h', 'a', 'n', 'n', 'a', 'H']
s = ['a', 'b']
reverseString(s)
print(s) # ['b', 'a']
Complexity
- Time:
O(n) - Space:
O(1)
Common Pitfalls
Using s = s[::-1] and thinking it modifies in-place. Reassigning s inside the function only rebinds the local variable — the original list the caller passed in is unchanged. You must mutate the list itself, either with index assignments or slice assignment s[:] = s[::-1].
Stopping too early with left <= right. When the array has an odd number of elements, left == right at the middle element. Swapping an element with itself is harmless, but using < is cleaner and equally correct.