Approach
- Initialize two pointers:
lat the start of the arrayrat the end of the array
- While
l < r, swaps[l]ands[r]. - Move both pointers inward (
l++,r--) and continue. - Stop when pointers meet or cross; at that point the array is fully reversed.
Implementation
export function reverseString(s: string[]): void {
function swap(arr: string[], idx1: number, idx2: number): void {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
}
let l = 0;
let r = s.length - 1;
while (l < r) {
swap(s, l, r);
l++;
r--;
}
}Complexity
- Time O(n): Each element is visited at most once as pointers move toward the center.
- Space O(1): Reversal is done in-place with constant extra memory.