#777

Swap Adjacent in LR String

Medium
Two PointersStringTwo PointersSliding Window
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 involves checking if we can transform the string by ensuring that the positions of 'L' and 'R' are valid relative to each other, considering the 'X' characters as placeholders. This approach is efficient and avoids unnecessary state exploration.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the counts of 'L' and 'R' in both strings are the same (ignoring 'X').
  2. 2Step 2: Use two pointers to traverse both strings simultaneously, ensuring that 'L' in start can only move left and 'R' can only move right.
  3. 3Step 3: If at any point the conditions are violated (i.e., an 'L' tries to move right of an 'R'), return False.
solution.py19 lines
1def canTransform(start, end):
2    if start.replace('X', '') != end.replace('X', ''):
3        return False
4    p1, p2 = 0, 0
5    while p1 < len(start) and p2 < len(end):
6        while p1 < len(start) and start[p1] == 'X':
7            p1 += 1
8        while p2 < len(end) and end[p2] == 'X':
9            p2 += 1
10        if p1 < len(start) and p2 < len(end):
11            if start[p1] != end[p2]:
12                return False
13            if start[p1] == 'L' and p1 < p2:
14                return False
15            p1 += 1
16            p2 += 1
17        else:
18            break
19    return True

Complexity note: The time complexity is O(n) because we traverse both strings linearly, ensuring we only check each character once.

  • 1The order of 'L' and 'R' matters significantly; 'L' must always be to the left of 'R' in the final configuration.
  • 2The 'X' characters can be treated as flexible spaces that allow 'L' and 'R' to move, but they cannot cross each other.

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