String Reversal
DSA · Arrays & Stringssyntax
Two pointers from ends, swap toward center.
Or use built-in reverse methods.example
// JavaScript
function reverseString(s) {
const chars = s.split('');
let l = 0, r = chars.length - 1;
while (l < r) {
[chars[l], chars[r]] = [chars[r], chars[l]];
l++; r--;
}
return chars.join('');
}
// Built-in: s.split('').reverse().join('')
# Python
def reverse_string(s):
chars = list(s)
l, r = 0, len(chars) - 1
while l < r:
chars[l], chars[r] = chars[r], chars[l]
l += 1; r -= 1
return ''.join(chars)
# Built-in: s[::-1]output
reverseString('interview') → 'weivretni'Note Time O(n), Space O(n) due to string immutability (both JS and Python strings are immutable). In-place reversal is possible on char arrays. Common follow-ups: reverse words in a sentence, reverse only vowels, check if palindrome.