Meta Data#
Difficulty: medium First Attempt: 2026-02-01
- Submissions: Wrong Answer ×2 → Accepted
Approach#
Translate the moves:
"XL" → "LX":Lmoves one step left."RX" → "XR":Rmoves one step right.
X is a blank, and L and R cannot pass each other, so this is exactly LeetCode 2337:
- With
Xremoved,startandresultmust have the same sequence. - Each
L’s index instartmust be>=its index inresult; eachR’s must be<=.
My Attempts#
- Attempt 1 only compared
Counter(start) == Counter(result). Forstart = "LR",result = "RL", the counts match butLandRcannot pass each other, so the answer isFalse; this version returnedTrue. - Attempt 2 used two pointers to skip
Xand compare order, but did not check direction. Forstart = "LX",result = "XL", the order matches butLwould have to move right, so the answer isFalse; this version returnedTrue.
Adding the direction checks passed.
Solution#
class Solution:
def canTransform(self, start: str, result: str) -> bool:
n = len(start)
i = j = 0
while True:
while i < n and start[i] == "X":
i += 1
while j < n and result[j] == "X":
j += 1
if i == n or j == n:
return i == n and j == n
if start[i] != result[j]:
return False
if start[i] == "L" and i < j:
return False # L only moves left
if start[i] == "R" and i > j:
return False # R only moves right
i += 1
j += 1
Complexity#
Time O(n), space O(1).
Mistakes to Avoid#
- Comparing character counts only.
- Comparing order only and forgetting that
Lonly moves left andRonly moves right.
Interview Explanation#
Replacing XL with LX moves L left, and replacing RX with XR moves R right; X is a blank and pieces cannot pass each other. Two pointers skip X and pair the k-th pieces: same type, an L in start not left of its spot in result, an R not right of it, and both sides run out together. Time O(n).
