Reverse string

2 snippets across 2 stacks — Interview Prep, Python

Also written as string reversal

DSAInterview Prep

String Reversal

DSA · Arrays & Strings
syntax
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.

PYPython

String Slicing

PY · Strings
syntax
string[start:stop:step]
example
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.