#2337

Move Pieces to Obtain a 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)

In the optimal approach, we will use a two-pointer technique to efficiently check if we can transform the start string into the target string by moving the pieces according to the rules.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the characters 'L' and 'R' in both strings are the same after removing all '_' characters.
  2. 2Step 2: Use two pointers to traverse both strings simultaneously, skipping over '_' characters.
  3. 3Step 3: For each character, ensure the movement rules are not violated (i.e., 'L' should not move right and 'R' should not move left).
solution.py23 lines
1# Full working Python code
2
3def canTransform(start: str, target: str) -> bool:
4    if start.replace('_', '') != target.replace('_', ''):
5        return False
6    n = len(start)
7    i, j = 0, 0
8    while i < n and j < n:
9        while i < n and start[i] == '_':
10            i += 1
11        while j < n and target[j] == '_':
12            j += 1
13        if i < n and j < n:
14            if start[i] != target[j]:
15                return False
16            if start[i] == 'L' and i < j:
17                return False
18            if start[i] == 'R' and i > j:
19                return False
20            i += 1
21            j += 1
22    return True
23

Complexity note: The time complexity is O(n) because we only traverse the strings once using two pointers, making it efficient.

  • 1The order of 'L' and 'R' must remain the same in both strings.
  • 2The number of '_' characters can affect the movement of 'L' and 'R'.

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