Python 0541.py
class Solution:
def reverseStr(self, s: str, k: int) -> str:
for left in range(0, len(s), 2*k):
right = left + k
rev = s[left:right]
rev = rev[::-1] # reverse
s = s[:left] + rev + s[right:]
return s
Difficulty
and has an acceptance rate of about 54% (700k+ 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 reverseStr. The method receives a string s and an integer k, and returns a new string where every consecutive block of k characters is reversed, while the following block of k characters is left unchanged. This pattern repeats for the entire length of the input string.
The algorithm proceeds by walking through the string in strides of 2*k, extracting the segment that must be reversed, applying Python’s slice-based reversal, and then rebuilding the string with the reversed segment in place. The use of Python slicing and the built-in slice reversal ([::-1]) makes the core operation concise and leverages highly optimized C-level routines.
Key Steps
Iterating over the string in 2*k sized windows
for left in range(0, len(s), 2*k):
The loop variable left marks the start index of each window that may contain a segment to reverse. By stepping with 2*k, the loop automatically skips the block that should remain unchanged, ensuring that only the required portions are processed.
Determining the end of the segment to reverse
right = left + k
right is calculated as the exclusive upper bound of the segment that will be reversed. If the remaining characters are fewer than k, Python’s slicing semantics will safely clamp the index to the end of the string.
Extracting and reversing the target segment
rev = s[left:right]
rev = rev[::-1] # reverse
The slice s[left:right] obtains the characters that need to be reversed. The subsequent slice [::-1] creates a new string with the characters in reverse order. This operation is performed by the interpreter’s internal C implementation, providing a fast in-place reversal without explicit loops.
Rebuilding the string with the reversed segment
s = s[:left] + rev + s[right:]
The original string is reconstructed by concatenating three parts: the prefix before the segment, the reversed segment itself, and the suffix after the segment. Because strings are immutable in Python, a new string object is created at each iteration, but the use of slicing keeps the amount of data copied to a minimum.
Returning the final result
return s
After all windows have been processed, the method returns the fully transformed string.
Edge Cases Handled
When the length of s is not a multiple of 2*k, the final iteration may encounter a segment that is shorter than k. The slice s[left:right] automatically truncates at the string’s end, so the code reverses whatever characters remain without raising an error.
If the remaining characters after a reversed block are fewer than k, the next iteration’s left index will point beyond the string length, causing the range loop to terminate gracefully.
An empty input string (s = "") results in the loop body never executing, and the method returns the empty string unchanged.
When k exceeds the length of s, the first calculation of right yields a value larger than len(s). The slice s[left:right] again clamps to the actual length, causing the entire string to be reversed in a single step, which matches the intended specification for this scenario.
Performance Optimizations Observed
The algorithm minimizes the number of passes over the data by stepping through the string with a stride of 2*k. This reduces the total number of loop iterations roughly by half compared to a naïve approach that would examine each character individually.
Utilizing Python’s slice syntax for both extraction and reversal leverages highly optimized native code paths, avoiding the overhead of manual character manipulation in Python loops.
String reconstruction is performed with a single concatenation per iteration, combining three slices. Because each slice references the original string’s memory without copying until the final concatenation, the amount of temporary data created is limited to the reversed segment and the newly formed string for that iteration.
Overall, the method balances readability with efficient use of built-in operations, resulting in a solution that runs quickly for typical input sizes while keeping the code succinct.
ELI5 - Simplified Explanation
Imagine a long string of colorful building blocks laid out in a straight line. This code is like a little robot helper designed to organize these blocks in a special way. The robot looks at a big pile of blocks and decides to pick up a small chunk of them at a time. It skips over two times the number of blocks you asked for, grabbing a handful and then pausing.
For every handful it grabs, it uses a tiny machine to flip all the blocks in that specific section around so they face the other way. After the blocks are flipped, the robot puts them back exactly where they started in the line. Then, it walks further down the row to find the next handful and does the exact same thing again. It keeps moving along the line, flipping chunks, until it reaches the very end of all the blocks. All the blocks that it did not pick up stay sitting perfectly still just like they were before.
Code Quality
Complexity Analysis
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fengvyi | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| qiyuangong | Java | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fengvyi | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| qiyuangong | Java | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 344: Reverse String
- problem 557: Reverse Words in a String III
- problem 2810: Faulty Keyboard
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 166: Fraction to Recurring Decimal
- problem 223: Rectangle Area
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
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