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 trueif it is possible to obtain the stringtarget by moving the pieces of the string startany 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 '_'.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
"_L__R__R_"
"L______RR"
Example 2
"R_L_"
"__LR"
Example 3
"_R"
"R_"
Related Problems
Valid Parentheses (valid-parentheses)
Swap Adjacent in LR String (swap-adjacent-in-lr-string)
Step 02
Core Insight
What unlocks the optimal approach
After some sequence of moves, can the order of the pieces change?
Try to match each piece in s with a piece in e.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2337: Move Pieces to Obtain a String
class Solution {
public boolean canChange(String start, String target) {
List<int[]> a = f(start);
List<int[]> b = f(target);
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); ++i) {
int[] x = a.get(i);
int[] y = b.get(i);
if (x[0] != y[0]) {
return false;
}
if (x[0] == 1 && x[1] < y[1]) {
return false;
}
if (x[0] == 2 && x[1] > y[1]) {
return false;
}
}
return true;
}
private List<int[]> f(String s) {
List<int[]> res = new ArrayList<>();
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == 'L') {
res.add(new int[] {1, i});
} else if (s.charAt(i) == 'R') {
res.add(new int[] {2, i});
}
}
return res;
}
}
// Accepted solution for LeetCode #2337: Move Pieces to Obtain a String
func canChange(start string, target string) bool {
f := func(s string) [][]int {
res := [][]int{}
for i, c := range s {
if c == 'L' {
res = append(res, []int{1, i})
} else if c == 'R' {
res = append(res, []int{2, i})
}
}
return res
}
a, b := f(start), f(target)
if len(a) != len(b) {
return false
}
for i, x := range a {
y := b[i]
if x[0] != y[0] {
return false
}
if x[0] == 1 && x[1] < y[1] {
return false
}
if x[0] == 2 && x[1] > y[1] {
return false
}
}
return true
}
# Accepted solution for LeetCode #2337: Move Pieces to Obtain a String
class Solution:
def canChange(self, start: str, target: str) -> bool:
a = [(v, i) for i, v in enumerate(start) if v != '_']
b = [(v, i) for i, v in enumerate(target) if v != '_']
if len(a) != len(b):
return False
for (c, i), (d, j) in zip(a, b):
if c != d:
return False
if c == 'L' and i < j:
return False
if c == 'R' and i > j:
return False
return True
// Accepted solution for LeetCode #2337: Move Pieces to Obtain a String
/**
* [2337] Move Pieces to Obtain a String
*
* 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 <= 10^5
* start and target consist of the characters 'L', 'R', and '_'.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/move-pieces-to-obtain-a-string/
// discuss: https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn can_change(start: String, target: String) -> bool {
false
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2337_example_1() {
let start = "_L__R__R_".to_string();
let target = "L______RR".to_string();
let result = true;
assert_eq!(Solution::can_change(start, target), result);
}
#[test]
#[ignore]
fn test_2337_example_2() {
let start = "R_L_".to_string();
let target = "__LR".to_string();
let result = false;
assert_eq!(Solution::can_change(start, target), result);
}
#[test]
#[ignore]
fn test_2337_example_3() {
let start = "_R".to_string();
let target = "R_".to_string();
let result = false;
assert_eq!(Solution::can_change(start, target), result);
}
}
// Accepted solution for LeetCode #2337: Move Pieces to Obtain a String
function canChange(start: string, target: string): boolean {
if (
[...start].filter(c => c !== '_').join('') !== [...target].filter(c => c !== '_').join('')
) {
return false;
}
const n = start.length;
let i = 0;
let j = 0;
while (i < n || j < n) {
while (start[i] === '_') {
i++;
}
while (target[j] === '_') {
j++;
}
if (start[i] === 'R') {
if (i > j) {
return false;
}
}
if (start[i] === 'L') {
if (i < j) {
return false;
}
}
i++;
j++;
}
return true;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.