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
Both start and result will only consist of characters in 'L', 'R', and 'X'.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
"RXXLRXRXL"
"XRLXXRRLX"
Example 2
"X"
"L"
Related Problems
Move Pieces to Obtain a String (move-pieces-to-obtain-a-string)
Step 02
Core Insight
What unlocks the optimal approach
Think of the L and R's as people on a horizontal line, where X is a space. The people can't cross each other, and also you can't go from XRX to RXX.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #777: Swap Adjacent in LR String
class Solution {
public boolean canTransform(String start, String end) {
int n = start.length();
int i = 0, j = 0;
while (true) {
while (i < n && start.charAt(i) == 'X') {
++i;
}
while (j < n && end.charAt(j) == 'X') {
++j;
}
if (i == n && j == n) {
return true;
}
if (i == n || j == n || start.charAt(i) != end.charAt(j)) {
return false;
}
if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) {
return false;
}
++i;
++j;
}
}
}
// Accepted solution for LeetCode #777: Swap Adjacent in LR String
func canTransform(start string, end string) bool {
n := len(start)
i, j := 0, 0
for {
for i < n && start[i] == 'X' {
i++
}
for j < n && end[j] == 'X' {
j++
}
if i == n && j == n {
return true
}
if i == n || j == n || start[i] != end[j] {
return false
}
if start[i] == 'L' && i < j {
return false
}
if start[i] == 'R' && i > j {
return false
}
i, j = i+1, j+1
}
}
# Accepted solution for LeetCode #777: Swap Adjacent in LR String
class Solution:
def canTransform(self, start: str, end: str) -> bool:
n = len(start)
i = j = 0
while 1:
while i < n and start[i] == 'X':
i += 1
while j < n and end[j] == 'X':
j += 1
if i >= n and j >= n:
return True
if i >= n or j >= n or start[i] != end[j]:
return False
if start[i] == 'L' and i < j:
return False
if start[i] == 'R' and i > j:
return False
i, j = i + 1, j + 1
// Accepted solution for LeetCode #777: Swap Adjacent in LR String
struct Solution;
impl Solution {
fn can_transform(start: String, end: String) -> bool {
let mut iter_a = start.chars();
let mut iter_b = end.chars();
let mut count_a = 0;
let mut count_b = 0;
while let (Some(mut a), Some(mut b)) = (iter_a.next(), iter_b.next()) {
while a == 'X' {
count_a += 1;
a = if let Some(c) = iter_a.next() { c } else { 'Y' };
}
while b == 'X' {
count_b += 1;
b = if let Some(c) = iter_b.next() { c } else { 'Y' };
}
if a != b {
return false;
}
if a == 'R' && count_a > count_b {
return false;
}
if a == 'L' && count_a < count_b {
return false;
}
}
true
}
}
#[test]
fn test() {
let start = "RXXLRXRXL".to_string();
let end = "XRLXXRRLX".to_string();
let res = true;
assert_eq!(Solution::can_transform(start, end), res);
let start = "XXRXXLXXXX".to_string();
let end = "XXXXRXXLXX".to_string();
let res = false;
assert_eq!(Solution::can_transform(start, end), res);
}
// Accepted solution for LeetCode #777: Swap Adjacent in LR String
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #777: Swap Adjacent in LR String
// class Solution {
// public boolean canTransform(String start, String end) {
// int n = start.length();
// int i = 0, j = 0;
// while (true) {
// while (i < n && start.charAt(i) == 'X') {
// ++i;
// }
// while (j < n && end.charAt(j) == 'X') {
// ++j;
// }
// if (i == n && j == n) {
// return true;
// }
// if (i == n || j == n || start.charAt(i) != end.charAt(j)) {
// return false;
// }
// if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) {
// return false;
// }
// ++i;
// ++j;
// }
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.