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]
Difficulty
and has an acceptance rate of about 81% (4+ million submissions).
Typical patterns to solve this problem:
- String
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 345: Reverse Vowels of a String
- problem 541: Reverse String II
Solved On The Same Day
- problem 342: Power of Four
- problem 345: Reverse Vowels of a String
- problem 349: Intersection of Two Arrays
- problem 350: Intersection of Two Arrays II
- problem 387: First Unique Character in a String
- problem 412: Fizz Buzz
- problem 414: Third Maximum Number
- problem 434: Number of Segments in a String
- problem 448: Find All Numbers Disappeared in an Array
- problem 485: Max Consecutive Ones
- problem 504: Base 7
- problem 507: Perfect Number
Extra
- 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