In a string composed of 'L'
, 'R'
, and 'X'
characters, like "RXXLRXRXL"
, a move consists of either replacing one occurrence of "XL"
with "LX"
, or replacing one occurrence of "RX"
with "XR"
. Given the starting string start
and the ending string result
, return True
if and only if there exists a sequence of moves to transform start
to result
.
Example 1:
Input: start = "RXXLRXRXL", result = "XRLXXRRLX" Output: true Explanation: We can transform start to result following these steps: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX
Example 2:
Input: start = "X", result = "L" Output: false
Constraints:
1 <= start.length <= 104
start.length == result.length
start
and result
will only consist of characters in 'L'
, 'R'
, and 'X'
.This problem asks whether we can transform string start
into string end
using only two types of operations: swapping XL
to LX
and swapping RX
to XR
. The key observation is that the relative order of 'L's and 'R's must remain the same. 'X's can move freely, but they don't affect the order of 'L's and 'R's.
The solution uses a two-pointer approach to efficiently compare the strings. One pointer iterates through start
, and the other iterates through end
. Both pointers skip over 'X' characters. If the non-'X' characters at the pointers don't match, it's impossible to transform start
to end
, so we return false
. If they match, we check the positional constraints:
start
must be greater than or equal to the index in end
. This is because 'L's can only move to the left.start
must be less than or equal to the index in end
. This is because 'R's can only move to the right.If either of these conditions is violated, it's impossible to transform start
to end
, and we return false
.
If both pointers reach the end of the strings and all checks have passed, it means that the transformation is possible, and we return true
.
The solution iterates through the strings at most once. Therefore, the time complexity is O(n), where n is the length of the strings.
The solution uses a constant amount of extra space for pointers. Therefore, the space complexity is O(1).