#3823

Reverse Letters Then Special Characters in a String

Easy
Two PointersStringSimulationTwo PointersIn-place Reversal
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

Utilizing two pointers allows us to reverse letters and special characters in a single pass, making it efficient. This method minimizes space usage by avoiding extra lists.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers, one at the start and one at the end of the string.
  2. 2Step 2: Move both pointers towards the center, swapping letters and special characters as needed.
  3. 3Step 3: Continue until the pointers meet.
solution.py11 lines
1def reverseString(s):
2    s = list(s)
3    left, right = 0, len(s) - 1
4    while left < right:
5        if s[left].isalpha() and s[right].isalpha():
6            s[left], s[right] = s[right], s[left]
7            left += 1
8            right -= 1
9        if not s[left].isalpha(): left += 1
10        if not s[right].isalpha(): right -= 1
11    return ''.join(s)

Complexity note: The complexity is O(n) since we traverse the string once, and we use O(1) space as we modify the string in place.

  • 1Two pointers can efficiently handle swaps in-place.
  • 2Reversing in-place avoids additional space usage.

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