LeetCode 344 · Two pointers

Reverse String, explained with a picture

Two friends swapping letter cards.

Two pointers
▶ Watch it step by step

The problem

Reverse a list of characters in place.

Input:  "hello"
Output: "olleh"

Picture it

Picture two friends holding the end letter cards. They swap cards, step one card inward, and repeat until they meet in the middle.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Two pointers swapping toward the centre. O(n), O(1).

Python solution

def reverse_string(s):
    l, r = 0, len(s) - 1
    while l < r:
        s[l], s[r] = s[r], s[l]
        l, r = l + 1, r - 1

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.