Write a function that reverses a string. The input is given as an array of characters s. You must do this in-place with O(1) extra memory — you cannot create a new array.
s = ["h","e","l","l","o"]["o","l","l","e","h"]s = ["H","a","n","n","a","h"]["h","a","n","n","a","H"]l = 0 (left pointer), r = n−1 (right pointer)l < r: the two pointers haven't crossed yets[l] ↔ s[r] using a temporary variablel++, r--l ≥ r, all elements are in their final positionClassic in-place reversal with two pointers. Each swap permanently places two characters in their final positions. After ⌊n/2⌋ swaps, every element is in its correct reversed position. The middle element (odd-length arrays) needs no swap. No extra memory is used beyond a single tmp variable.
Copying the characters into a new array backwards uses O(n) extra space. The problem asks you to work in place.
Put one pointer at each end. Swap the two characters, then move both pointers inward. Stop when they meet.
In-place reversal is two pointers swapping toward the middle. The same move appears inside many harder problems.
Run the animation above on your own input, or watch the 0:58 video explanation of Reverse String with a dry run and Java code.