Skip to content
Ayotl

← All challenges

Interview challenge · easy · string, two-pointers

Reverse a String

The challenge

Reverse a string without a built-in helper such as Python's [::-1] or reversed().

Example

"hello"    ->  "olleh"
"ayotl"    ->  "ltoya"
"racecar"  ->  "racecar"   (a palindrome stays the same)

Idea: two pointers, one at each end. Swap the two characters and move both pointers one step toward the middle until they meet. Every character is touched once: time O(n). In C the string is reversed in place with O(1) extra space. Python strings are immutable, so the Python version swaps inside a list of characters and joins it at the end.

The solution

# Reverse a String - ayotl.dev
def reverse(s):
    a = list(s)  # str is immutable
    i, j = 0, len(a) - 1
    # swap the ends, walk to the middle
    while i < j:
        a[i], a[j] = a[j], a[i]
        i, j = i + 1, j - 1
    return "".join(a)


for w in ["hello", "ayotl", "racecar"]:
    print(reverse(w))

$ python3 reverse_a_string.py

olleh

ltoya

racecar

The video

Watch on YouTube →