#917

Reverse Only Letters

Easy
Two PointersStringTwo PointersString Manipulation
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)

The optimal approach uses a two-pointer technique to reverse the letters in place. This method is efficient because it only requires a single pass through the string, making it faster than the brute-force method.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, one at the start and one at the end of the string.
  2. 2Step 2: Move the left pointer right until it points to a letter, and the right pointer left until it points to a letter.
  3. 3Step 3: Swap the letters at the two pointers, then move both pointers inward.
  4. 4Step 4: Repeat the process until the left pointer is greater than or equal to the right pointer.
solution.py13 lines
1def reverseOnlyLetters(s):
2    s = list(s)
3    left, right = 0, len(s) - 1
4    while left < right:
5        if not s[left].isalpha():
6            left += 1
7        elif not s[right].isalpha():
8            right -= 1
9        else:
10            s[left], s[right] = s[right], s[left]
11            left += 1
12            right -= 1
13    return ''.join(s)

Complexity note: The time complexity is O(n) because we traverse the string only once. The space complexity is O(1) since we are reversing in place without using additional data structures.

  • 1Use two pointers to efficiently reverse elements in place.
  • 2Non-letter characters should be skipped while processing.

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