Leetcode•Nov 12, 2026
Swap Adjacent in LR String
Hazrat Ali
Leetcode
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
Solution
var canTransform = function(start, result) {
if (start.length !== result.length) return false;
let i = 0;
let j = 0;
const n = start.length;
while (i < n && j < n) {
while (i < n && start[i] === 'X') i++;
while (j < n && result[j] === 'X') j++;
if (i === n || j === n) {
return i === n && j === n;
}
if (start[i] !== result[j]) return false;
if (start[i] === 'L' && i < j) return false;
if (start[i] === 'R' && i > j) return false;
i++;
j++;
}
while (i < n && start[i] === 'X') i++;
while (j < n && result[j] === 'X') j++;
return i === n && j === n;
};