Skip to content
LEETFLIX

Easy · in-place reverse. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 344. Reverse String. The copyrighted prompt is on LeetCode. This page is a working in-place reverse for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

s =
hello

Output

olleh

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Swap the ends

Two pointers, swap, step in, until they meet.

The classic in-place reverse. Each swap puts two characters into their final seats.

Algorithm

  1. lo = 0, hi = n−1.
  2. Swap, then lo++, hi--, while lo < hi.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def reverseString(self, s: list[str]) -> list[str]:        lo, hi = 0, len(s) - 1        while lo < hi:            s[lo], s[hi] = s[hi], s[lo]            lo += 1            hi -= 1        return s
Watch this run

03

Interactive walkthrough

Playing “Swap the ends”. Edit the input, hit Run, then scrub.

Approach: Swap the ends

Loading animation…