The brute-force solution uses extra space to store the reversed array, leading to:
The optimal solution uses two pointers to reverse the array in-place with O(1) space complexity:
The “Reverse String” problem asks you to reverse a character array s
in-place. That means you must reverse the order of characters without using additional memory for another array.
For example:
["h", "e", "l", "l", "o"]
["o", "l", "l", "e", "h"]
Reversing a string in-place is a fundamental operation in computer science. It’s often used in more complex problems like string manipulation, palindrome checking, and memory-efficient algorithms. Mastering this builds confidence in using pointers and understanding array indexing.
A naive approach is to use a temporary array to store the reversed characters and then copy them back into the original array.
T
to store the characters in reverse order.s
to the beginning, appending each character to T
.T
back to s
to complete the reversal.While this works, it violates the in-place constraint by using extra memory and involves two separate passes through the array.
The optimal way to reverse a string in-place is by using the two-pointer technique. This method swaps characters from both ends of the array while moving inward, and it requires only constant extra space.
l = 0
(left side)r = s.length - 1
(right side)l < r
:
s[l]
and s[r]
.l
and decrement r
.s
.
Input: ["h", "e", "l", "l", "o"]
Iteration steps:
'h'
and 'o'
→ ["o", "e", "l", "l", "h"]
'e'
and 'l'
→ ["o", "l", "l", "e", "h"]
Final output: ["o", "l", "l", "e", "h"]
Time Complexity: O(n), where n is the number of characters. Each character is visited once.
Space Complexity: O(1), since the reversal is done in-place without using any additional data structures.
The “Reverse String” problem is a textbook example of applying the two-pointer technique to modify arrays efficiently. It’s simple, elegant, and a fundamental operation in both interview questions and real-world systems. Learning how to perform in-place reversal builds a solid foundation for more advanced string and array problems.