↓Skip to main content
  1. LeetCode/

LeetCode 541: Reverse String II

·1 min· ·
LeetCode Easy Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Wrong Answer ×2 → Runtime Error → Wrong Answer ×2 → Runtime Error → Accepted → Runtime Error ×2 → Wrong Answer ×2 → Accepted

Approach
#

Step from 0 by 2k and reverse [i, i + k) (Two Pointers Template 1). When fewer than k characters remain, all of them are reversed, and the slice a[i:i + k] truncates at the end, which matches exactly.

My Attempts
#

The 2022 versions reversed only the first block: "cddebd", k = 2 should be "dcdedb"; it returned "dcdebd". In 2026 I reversed only when i + k <= n, skipping a final block shorter than k: "cd", k = 4 should be "dc"; it returned "cd".

Solution
#

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        a = list(s)
        for i in range(0, len(a), 2 * k):
            a[i:i + k] = reversed(a[i:i + k])
        return "".join(a)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Not just the first block: every block of 2k.
  • Fewer than k remaining are reversed too.

Interview Explanation
#

Stepping by 2k, I reverse the first k of each block, and slicing automatically reverses only what remains at the end. Time O(n).

Related

LeetCode 344: Reverse String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 344 note: swap with two pointers and move inward to reverse in place
LeetCode 392: Is Subsequence
·2 mins
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 note: two pointers; the pointer on t always advances, and the one on s advances on a match; bound-check both
LeetCode 125: Valid Palindrome
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 125 note: two pointers skip non-alphanumeric characters and compare lowercase letters, with digits included
LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found
LeetCode 345: Reverse Vowels of a String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 345 note: the same two pointers as LC 917, with the condition switched to “is a vowel” (both cases)
LeetCode 504: Base 7
·1 min
LeetCode Easy Math String
LeetCode 504 note: repeatedly take % 7 and // 7 of the absolute value, then add the sign and reverse; handle 0 separately