You are given an array of characters which represents a string s. Write a function which reverses a string.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["n","e","e","t"]
Output: ["t","e","e","n"]Example 2:
Input: s = ["r","a","c","e","c","a","r"]
Output: ["r","a","c","e","c","a","r"]Constraints:
1 <= s.length < 100,000s[i] is a printable ascii character.The simplest approach is to build the reversed string in a separate array. We iterate through the original array from the end to the beginning, collecting characters in a new temporary array. Then we copy the reversed characters back to the original array. This works because reading backward gives us characters in reverse order.
tmp to store characters.i.tmp.tmp back to the original array s.We can reverse a string recursively by thinking of it as swapping the outermost characters, then reversing the inner substring. If we have pointers at both ends (l and r), we first recurse to handle the inner portion, then swap the current pair on the way back up. This naturally reverses the array through the call stack.
reverse(l, r) where l is the left index and r is the right index.l >= r, return (nothing to swap).reverse(l + 1, r - 1).s[l] and s[r].reverse(0, len(s) - 1).A stack follows Last-In-First-Out (LIFO) order, which is perfect for reversing. If we push all characters onto a stack, then pop them off one by one, we get the characters in reverse order. This exploits the stack's natural behavior to achieve the reversal.
stack.s onto the stack.i, popping from the stack and writing each character back to s.Most programming languages provide a built-in method to reverse arrays or lists. These functions are typically optimized and handle the reversal in place efficiently. While this approach is the simplest to write, it hides the underlying algorithm.
The most efficient approach uses two pointers starting at opposite ends of the array. We swap the characters at these pointers, then move them toward each other. When the pointers meet or cross, every character has been swapped exactly once, and the array is reversed. This achieves O(1) space since we only swap in place.
l at index 0 and r at the last index.l < r:s[l] and s[r].l and decrement r.s is now reversed in place.When using two pointers, the loop should terminate when l >= r, not when l > r. Using l != r works for odd-length strings but is less intuitive. The condition l < r correctly handles both even and odd length arrays.
The problem requires modifying the input array in-place. A common mistake is creating a new reversed array or string and returning it, which violates the in-place requirement and uses unnecessary extra space.