Problem 541

Abstract / Summary

Given a string and an integer k reverse every 2k characters where the first k are reversed and the next k are left as is.

Note

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

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
10 lines | 279 bytes | submitted September 7, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (700k+ 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.52 | σ = 1.52

Complexity Analysis

not analyzed yet

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++ 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++
36 links | 23 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

29 easy 13 medium
43 solutions   September 7, 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