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:

  • XL can become LX (L person moves left into empty space)
  • RX can become XR (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
Movement RulesValid MovesRXโ†’XRXLโ†’LXInvalid MovesRLโœ—LRR cannot jump over L
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
Asked in
Google 25 Meta 18 Amazon 12 Microsoft 8
27.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen