Reverse a String
Problem
Reverse a string, or an array of characters in place with O(1) extra space.
Example 1
Input: "hello" Output: "olleh"
Test cases
Case 1
Input: "hello" Expected: "olleh"
Case 2
Input: "ab cd" Expected: "dc ba"
Case 3
Input: "a" Expected: "a"
Case 4
Input: "" Expected: ""
View solutionHide solution1 approach
1. Two pointers (in place on a char array)
Time O(n)Space O(n) for the array
Swap ends inward. JS strings are immutable, so operate on an array.
function reverseString(s) { const a = [...s]; let l = 0, r = a.length - 1; while (l < r) { [a[l], a[r]] = [a[r], a[l]]; l++; r--; } return a.join('');}