Skip to main content
Back to problems
#2337
Medium Algorithms

Move pieces to obtain a string

Two Pointers String
56.7% acceptance
Feb 25, 2026
1460
85
You are given two strings start and target. Each consists of 'L', 'R', and '_'. 'L' can move left only if there is a blank to its left. 'R' can move right only if there is a blank to its right. Return true if it is possible to obtain target from start by moving pieces any number of times.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn can_change(start: String, target: String) -> bool {
    let s: Vec<char> = start.chars().collect();
    let t: Vec<char> = target.chars().collect();
    let pieces_s: Vec<(char, usize)> = s.iter().copied().enumerate()
      .filter(|(_, c)| *c != '_').map(|(i, c)| (c, i)).collect();
    let pieces_t: Vec<(char, usize)> = t.iter().copied().enumerate()
      .filter(|(_, c)| *c != '_').map(|(i, c)| (c, i)).collect();
    if pieces_s.len() != pieces_t.len() { return false; }
    for (ps, pt) in pieces_s.iter().zip(pieces_t.iter()) {
      if ps.0 != pt.0 { return false; }
      // L can only move left (to smaller index)
      if ps.0 == 'L' && ps.1 < pt.1 { return false; }
      // R can only move right (to larger index)
      if ps.0 == 'R' && ps.1 > pt.1 { return false; }
    }
    true
  }
}