Swap Adjacent in LR String - Problem
Imagine you have a string of characters where 'L' represents people who can only move left, 'R' represents people who can only move right, and 'X' represents empty spaces.
The movement rules are simple:
XLcan becomeLX(L person moves left into empty space)RXcan becomeXR(R person moves right into empty space)
Given a start string like "RXXLRXRXL" and a target result string, determine if you can transform the start string into the result string using only these allowed moves.
Goal: Return true if transformation is possible, false otherwise.
Think of it as a puzzle where people can only move in their designated direction, but they can't jump over each other!
Input & Output
example_1.py โ Basic Transformation
$
Input:
start = "RXXLRXRXL", result = "XLRXXXRXL"
โบ
Output:
true
๐ก Note:
R can move right past X's, L can move left past X's. The sequence R,L,R,R,L is preserved in both strings, and all movements follow the constraints.
example_2.py โ Impossible Transformation
$
Input:
start = "RXL", result = "LXR"
โบ
Output:
false
๐ก Note:
The relative order changes from R,L to L,R, which is impossible since R cannot jump over L (R moves right, L moves left, they can't cross).
example_3.py โ Same String
$
Input:
start = "X", result = "L"
โบ
Output:
false
๐ก Note:
Cannot change X to L since X represents empty space and L represents a person - the total count of L and R characters must remain the same.
Constraints
- 1 โค start.length โค 104
- result.length == start.length
- start and result consist only of characters 'L', 'R', and 'X'
Visualization
Tap to expand
Understanding the Visualization
1
Valid Movement
R moves right: RX โ XR, L moves left: XL โ LX
2
Relative Order
L and R characters maintain their sequence order
3
Position Constraints
L can only be at same position or move left, R can only be at same position or move right
4
Impossible Cases
R cannot move left past L, L cannot move right past R
Key Takeaway
๐ฏ Key Insight: Characters can only move in their designated direction and cannot change their relative order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code