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 String INPUT start = "_L__R__R_" _ L _ _ R _ _ R _ 0 1 2 3 4 5 6 7 8 target = "L______RR" L _ _ _ _ _ _ R R Movement Rules: L: Can only move LEFT _L --> L_ R: Can only move RIGHT R_ --> _R _ : Blank space (swappable) ALGORITHM STEPS 1 Remove blanks, compare "LRR" == "LRR" ? YES 2 Two-pointer approach Skip blanks in both strings 3 Check L positions L in start must be >= target 4 Check R positions R in start must be <= target Position Validation: Piece Start Target Valid L 1 0 OK R 4 7 OK R 7 8 OK All positions valid! FINAL RESULT Transformation Steps: Initial: _L__R__R_ | v L moves: L___R__R_ | v R moves: L____R_R_ | v R moves: L_____RR_ | v R moves: L______RR Output: true Transformation possible! Target reached successfully Key Insight: 1. The relative order of L and R pieces must be the same in both strings (ignoring blanks). 2. L can only move left: its index in start must be >= its index in target. 3. R can only move right: its index in start must be <= its index in target. TutorialsPoint - Move Pieces to Obtain a String | Optimal Two-Pointer Approach
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