Problem 344

Abstract / Summary

Reverse the characters in a given string and return the reversed string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0344.py

class Solution:
    def reverseString(self, s: List[str]) -> None:
        r = s[::-1]
        for i in range(len(r)):
            s[i] = r[i]
5 lines | 148 bytes | submitted August 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 81% (4+ million submissions).

Typical patterns to solve this problem:
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method reverseString. The method receives a mutable list of single-character strings and reverses its contents in place. The algorithm follows a two-phase approach: it first creates a reversed copy of the input list, then writes the elements of that copy back into the original list. This satisfies the requirement of mutating the input without returning a new list.

Key Steps

The first step constructs a reversed view of the input using Python’s slice syntax with a step of -1. This creates a new list r that holds the elements of s in opposite order.

r = s[::-1]

The second step iterates over the indices of the reversed list and assigns each element back to the corresponding position in the original list. The loop runs from 0 to len(r) - 1, ensuring every slot of s is overwritten.

for i in range(len(r)):
    s[i] = r[i]

By directly indexing into s, the method guarantees that the original list object is mutated, which aligns with the in-place contract of the problem statement.

Edge Cases

The algorithm gracefully handles an empty list. When s is empty, the slice operation s[::-1] yields another empty list, and the range(len(r)) produces an empty range, so the loop body never executes. The original list remains unchanged, which is the correct behavior for reversing an empty collection.

A single-element list also works correctly. The slice creates a copy containing the same single element, and the loop runs once, assigning the element back to its original position. No special handling is required for these minimal cases.

If the input list contains duplicate characters, the reversal still produces the correct order because the algorithm works with positions rather than values. The method does not depend on element uniqueness.

Performance Optimizations

The use of slicing (s[::-1]) leverages Python’s highly optimized C implementation for list copying and reversal. This operation runs in linear time and creates a contiguous block of memory for the reversed copy, which is faster than manually swapping elements one by one in pure Python loops.

The subsequent assignment loop writes directly to the original list without creating intermediate structures. By iterating over indices rather than enumerating elements, the code avoids the overhead of tuple unpacking that occurs with constructs like for i, val in enumerate(r). This choice reduces per-iteration overhead and contributes to a tighter inner loop.

Overall, the combination of a built-in slice reversal and a simple index-based copy yields an implementation that is both concise and performant for typical list sizes encountered in practice.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of colorful blocks, and each block has a letter painted on it. This code is like a little helper that picks up all those blocks and puts them back down in the exact opposite order.

First, the helper looks at the entire row of blocks and makes a secret list that shows exactly what the line would look like if it were turned around backward. Once that secret list is ready, the helper goes through the original row one block at a time. It takes the first block from the secret list and puts it in the first spot, then takes the second block from the secret list and puts it in the second spot, and it keeps doing this until the last block is fixed. By the time the helper is finished, all the letters are standing in a brand new, backwards line.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5.5 | μ = 5.31 | σ = 1.70

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS Go Rust TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
53 links | 37 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
1 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

13 solutions   August 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality