Back to blog
Jan 02, 2025
8 min read

Reverse String II

Given a string s and an integer k, reverse the first k characters for every 2k characters.

Difficulty: Easy | Acceptance: 53.70% | Paid: No Topics: Two Pointers, String

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the others as original.

Examples

Example 1

Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Explanation: 
- Reverse first 2 chars: "ab" -> "ba"
- Keep next 2 chars: "cd" -> "cd"
- Reverse next 2 chars: "ef" -> "fe"
- Keep remaining: "g" -> "g"
Result: "bacdfeg"

Example 2

Input: s = "abcd", k = 2
Output: "bacd"
Explanation:
- Reverse first 2 chars: "ab" -> "ba"
- Keep remaining: "cd" -> "cd"
Result: "bacd"

Constraints

1 <= s.length <= 10⁴
s consists of only lowercase English letters.
1 <= k <= 10⁴

Iterative Approach

Intuition Process the string in chunks of 2k, reversing the first k characters of each chunk using string slicing.

Steps

  • Iterate through the string with step size 2k
  • For each chunk, reverse the first k characters using slicing
  • Append the reversed part and the remaining part to result
  • Join all parts and return
python
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        result = []
        n = len(s)
        for i in range(0, n, 2 * k):
            chunk = s[i:i + k]
            result.append(chunk[::-1])
            result.append(s[i + k:i + 2 * k])
        return ''.join(result)

Complexity

  • Time: O(n) where n is the length of the string
  • Space: O(n) for the result string
  • Notes: Simple and readable, uses extra space for result

Two Pointers Approach

Intuition Convert string to mutable array and use two pointers to reverse segments in-place for better space efficiency.

Steps

  • Convert string to character array
  • Iterate with step 2k
  • For each segment, use two pointers to reverse the first k characters
  • Convert array back to string and return
python
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        chars = list(s)
        n = len(chars)
        for i in range(0, n, 2 * k):
            left = i
            right = min(i + k - 1, n - 1)
            while left &lt; right:
                chars[left], chars[right] = chars[right], chars[left]
                left += 1
                right -= 1
        return ''.join(chars)

Complexity

  • Time: O(n) where n is the length of the string
  • Space: O(n) for the character array (O(1) extra space for C++)
  • Notes: More efficient for languages with mutable strings

Built-in Reverse Approach

Intuition Leverage built-in reverse functions to simplify the code and improve readability.

Steps

  • Iterate through the string with step 2k
  • Use built-in reverse to reverse the first k characters of each segment
  • Return the modified string
python
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        s = list(s)
        for i in range(0, len(s), 2 * k):
            s[i:i + k] = reversed(s[i:i + k])
        return ''.join(s)

Complexity

  • Time: O(n) where n is the length of the string
  • Space: O(n) for the character array
  • Notes: Cleanest code using language built-ins