Two pointers from ends, swap toward center.Or use built-in reverse methods.
Example
// JavaScriptfunctionreverseString(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)-1while l < r:
chars[l], chars[r]= chars[r], chars[l]
l +=1; r -=1return''.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.
word ="pythonic"print(word[0:4])print(word[-4:])print(word[::2])print(word[::-1])
Output
pyth
onic
ptoi
cinohtyp
Note Slicing never raises IndexError, even if indices exceed the string length. Negative step reverses direction.
Frequently asked questions
How do you reverse string?
This task is covered in 2 stacks on this page: Interview Prep, Python. The "String Reversal" snippet in Interview Prep uses `Two pointers from ends, swap toward center.`.
Which code does the Interview Prep example use?
The "String Reversal" snippet uses `Two pointers from ends, swap toward center.`, from the Arrays & Strings section of the Interview Prep cheat sheet.
Which stacks cover "reverse string" on this page?
Interview Prep, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "String Reversal": 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.