Skip to main content

Move Pieces to Obtain a String - Solution & Explanation

MediumTwo PointersString15 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

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

  • The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' 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 of the 'L' or 'R' pieces.

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.

 

Example 1:

Input: start = "_L__R__R_", target = "L______RR"
Output: true
Explanation: We can obtain the string target from start by doing the following moves:
- Move the first piece one step to the left, start becomes equal to "L___R__R_".
- Move the last piece one step to the right, start becomes equal to "L___R___R".
- Move the second piece three steps to the right, start becomes equal to "L______RR".
Since it is possible to get the string target from start, we return true.

Example 2:

Input: start = "R_L_", target = "__LR"
Output: false
Explanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_".
After that, no pieces can move anymore, so it is impossible to obtain the string target from start.

Example 3:

Input: start = "_R", target = "R_"
Output: false
Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.

 

Constraints:

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

Approach Overview

Problem Overview: You are given two strings start and target containing characters L, R, and _ (blank). Pieces can move only in specific directions: L moves left and R moves right by swapping with blanks. The task is to determine whether the start configuration can transform into target under these movement constraints.

Approach 1: Simulate Piece Movement (O(n) time, O(1) space)

This method walks through both strings and simulates how pieces could move through blanks. You skip underscore characters and align the next non-blank characters in both strings. If the characters differ, the transformation is impossible. When they match, enforce movement rules: an L piece cannot appear to the right of its original index because it can only move left, and an R piece cannot appear to the left of its original index because it can only move right. This approach effectively models valid moves while scanning once, making it efficient for large inputs.

Approach 2: Check Character Positions after Removing Blanks (O(n) time, O(1) space)

The key insight is that blanks do not affect the relative ordering of pieces. First remove all underscores from both strings and verify that the remaining sequence of L and R characters is identical. If the order differs, the transformation cannot happen. Next iterate through the original strings using two pointers to compare positions of corresponding pieces. Enforce the constraints: L must not move right and R must not move left. Because each pointer only moves forward once, the scan runs in linear time.

Both strategies rely on the same structural insight: the order of non-blank characters never changes. The problem becomes a positional constraint check rather than actual simulation of swaps. This turns what looks like a movement puzzle into a simple linear scan over a string.

Recommended for interviews: The position-check method using two pointers is the expected solution. It clearly demonstrates understanding of the movement constraints and achieves O(n) time with O(1) extra space. Simulation works too, but recognizing that only relative order and directional constraints matter shows stronger problem-solving insight.

Approach 1: Check Character Positions after Removing Blanks

In this approach, both start and target strings are reduced by removing the blank spaces ('_'). After that, we directly compare the remaining sequences of characters to check if they match. Each character's position is then validated based on the rules: 'L' can only move left, and 'R' can only move right. If these sequences not only match but also adhere to the movement rules, the transformation is possible.

This Python solution initially checks if both strings can become the same after removing all blanks. Then, it stores the indices of 'L' and 'R' in both strings and compares their positions to ensure all rules are respected: 'L' cannot move right, 'R' cannot move left. The solution returns True only if all conditions are satisfied.

Code

Python

JavaScript

Java

C#

C++

C

Complexity

Time Complexity: O(n), where n is the length of the input strings, since we traverse through the list a fixed number of times.
Space Complexity: O(n) due to the extra lists created for positions of 'L' and 'R'.

Try this approach in the editor β†’

Approach 2: Simulate Piece Movement

This approach simulates the movement of 'L' and 'R' pieces while iterating through both strings simultaneously. It maintains cursors for both strings, moving them forward as each piece is appropriately moved according to the rules. 'L' must be moved only left, while 'R' needs space to go right, ensuring no rule violations exist.

This Python implementation uses two pointers, one for each string, skipping underscores, and comparing positions. It checks the position rules for 'L' and 'R'. The final condition ensures no unmatched characters exist. It’s efficient as it simply processes each character once.

Code

Python

JavaScript

Java

C#

C++

C

Complexity

Time Complexity: O(n), because of the single pass through start and target strings.
Space Complexity: O(1), as no additional space proportional to the input is utilized.

Try this approach in the editor β†’

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Check Character Positions after Removing Blanks

Time Complexity: O(n), where n is the length of the input strings, since we traverse through the list a fixed number of times.
Space Complexity: O(n) due to the extra lists created for positions of 'L' and 'R'.

Simulate Piece Movement

Time Complexity: O(n), because of the single pass through start and target strings.
Space Complexity: O(1), as no additional space proportional to the input is utilized.

Default Approachβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Simulate Piece MovementO(n)O(1)Good for understanding the movement rules step by step
Check Character Positions after Removing BlanksO(n)O(1)Preferred interview solution; simplest linear validation using two pointers

Video Solution

Move Pieces to Obtain a String | Brute Force | Wrong | Optimal | Leetcode 2337 | codestorywithMIK β€’ codestorywithMIK β€’ 10,492 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Move Pieces to Obtain a String easy or hard?
Move Pieces to Obtain a String is rated Medium difficulty. The challenge lies in recognizing that piece order never changes and translating movement rules into index comparisons during a single pass through the strings.
Move Pieces to Obtain a String Python/Java solution
Python and Java implementations follow the same logic: iterate with two indices across both strings, skip underscores, compare characters, and validate movement constraints for L and R. The algorithm runs in O(n) time and constant extra space in both languages.
How to solve Move Pieces to Obtain a String in O(n)?
Scan both strings with two pointers while skipping underscore characters. When the next non-blank characters match, check their indices: L must not move to the right and R must not move to the left. Continue advancing pointers until the end of both strings. This linear scan validates the transformation in O(n) time.
What is the best approach for Move Pieces to Obtain a String?
The most efficient approach uses two pointers to compare positions of non-blank characters in the start and target strings. First ensure the order of L and R characters is identical after removing underscores. Then enforce movement constraints: L cannot move right and R cannot move left. This solution runs in O(n) time and O(1) space.
Is Move Pieces to Obtain a String asked at Google/Amazon/Meta?
String transformation and constraint-validation problems like this commonly appear in interviews at companies such as Amazon, Google, and Meta. The question tests reasoning about movement constraints and efficient string scanning using two pointers.
What data structure is used in Move Pieces to Obtain a String?
The solution mainly relies on string traversal with the two-pointer technique. No complex data structures are required because the problem reduces to comparing character order and validating positional constraints.
What is the time complexity of Move Pieces to Obtain a String?
The optimal solution runs in O(n) time because each string is scanned once with two pointers. Space complexity is O(1) since only index variables are used and no additional data structures are required.

Ready to solve this problem?

Practice Move Pieces to Obtain a String with our built-in code editor and test cases.

Practice on FleetCode