#541

Reverse String II

Easy
Two PointersStringTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the string with a two-pointer technique to reverse segments in place, which is more efficient than the brute-force method.

⚙️

Algorithm

5 steps
  1. 1Step 1: Convert the string to a list of characters for mutability.
  2. 2Step 2: Loop through the string in increments of 2k.
  3. 3Step 3: For each segment, reverse the first k characters in place using two pointers.
  4. 4Step 4: Continue until the end of the string.
  5. 5Step 5: Convert the list back to a string and return it.
solution.py15 lines
1# Full working Python code
2
3def reverseStr(s: str, k: int) -> str:
4    chars = list(s)
5    n = len(chars)
6    for i in range(0, n, 2 * k):
7        left, right = i, min(i + k - 1, n - 1)
8        while left < right:
9            chars[left], chars[right] = chars[right], chars[left]
10            left += 1
11            right -= 1
12    return ''.join(chars)
13
14# Example usage
15print(reverseStr('abcdefg', 2))  # Output: 'bacdfeg'

Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(1) since we are modifying the string in place without using extra space.

  • 1Understanding how to manipulate strings and characters is crucial.
  • 2Recognizing patterns in the problem, such as reversing segments, can lead to efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.