Move Pieces to Obtain a String - Problem

You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where:

Movement Rules:

  • The character 'L' represents a piece that can move to the left only if there is a blank space directly to its left
  • The character 'R' represents a piece that can move to the right only if there is a blank space directly to its right
  • The character '_' represents a blank space that can be occupied by any piece

Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false.

Input & Output

Example 1 — Valid Transformation
$ Input: start = "_L__R__R_", target = "L______RR"
Output: true
💡 Note: L can move from position 1 to position 0. Both R pieces can move right: first R from position 4 to position 7, second R from position 7 to position 8.
Example 2 — Invalid Movement
$ Input: start = "R_L_", target = "__LR"
Output: false
💡 Note: R cannot move left (from position 0 to position 3) and L cannot move right (from position 2 to position 2). The pieces cannot reach their target positions.
Example 3 — Different Piece Count
$ Input: start = "_R", target = "R_"
Output: false
💡 Note: The R piece at position 1 cannot move left to position 0, as R pieces can only move right.

Constraints

  • n == start.length == target.length
  • 1 ≤ n ≤ 105
  • start and target consist of characters 'L', 'R', and '_'

Visualization

Tap to expand
Move Pieces to Obtain a StringStart:_L_RTarget:L___R✓ Valid: L moved left, R moved rightBoth pieces follow their directional constraints
Understanding the Visualization
1
Input Analysis
Two strings with L, R pieces and blank spaces
2
Movement Rules
L moves left only, R moves right only
3
Validation
Check if transformation is possible
Key Takeaway
🎯 Key Insight: Pieces maintain relative order and follow strict directional movement rules
Asked in
Amazon 15 Microsoft 12 Google 8
23.4K Views
Medium Frequency
~15 min Avg. Time
867 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