15% off all plans & roadmaps Use code

See plans

Move Pieces to Obtain a String

Updated

TL;DR: Each `L` can slide left and each `R` can slide right through blank cells. No piece can pass another. The answer is `true` exactly when the pieces appear in the same order with the same letters, and each piece sits on the correct side of its target position.

Problem

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

A piece 'L' can move left only when the cell directly to its left is blank. A piece 'R' can move right only when the cell directly to its right is blank. The character '_' is a blank cell that any piece can fill.

Return true if you can turn start into target by moving pieces any number of times. Otherwise, return false.

Example 1

Input: start = "_L__R__R_", target = "L______RR"
Output: true
Explanation: Move the first piece one step left, so start becomes L___R__R_. Move the last piece one step right, so start becomes L___R___R. Move the middle piece three steps right, so start becomes L______RR. That matches target, so the answer is true.

Example 2

Input: start = "R_L_", target = "__LR"
Output: false
Explanation: The R piece can move one step right to get _RL_. After that, no piece can move, so target cannot be reached.

Example 3

Input: start = "_R", target = "R_"
Output: false
Explanation: The piece can only move right, so it cannot reach index 0.

Constraints

  • n == start.length == target.length
  • 1 <= n <= 10^5
  • start and target consist only of 'L', 'R', and '_'.

Constraints that matter

  • n can be 10^5, so any search over reachable strings is too slow. Only a single linear scan fits the limit.
  • Pieces never cross, so only the letters in order and their positions matter. Blanks only tell you where pieces can go.
  • Storing the position of every piece costs O(n) extra space. A solution that uses O(1) space needs to pair pieces as it scans.

View on LeetCode

Hints

Hint 1

Start by ignoring the blanks.

Hint 2

Write down the position of every piece in each string.

Solution

Intuition

Start by ignoring the blanks. Pieces never jump over each other, so the sequence of letters must match. The first piece in start must become the first piece in target, the second must become the second, and so on.

Picture two rows of cards, one row for start and one for target, with blank slots between them. Index i is a finger on the start row and j is one on the target row, each skipping blanks to the next card.

That turns the problem into pairing pieces in order. Two indexes can walk both strings forward, skip blanks, and compare one pair at a time. This is the two-pointer pattern, applied to two strings instead of one array.

The second rule is direction. An L can only end at the same index or further left, so its index in target must be less than or equal to its index in start. An R must end at the same index or further right.

Those two index checks, plus the letter check, decide every case. You never need to simulate a move. Sorting does not help, because the order of the pieces is the very thing you check.

Watch the pattern animation

Worked example

Input: start = "_L__R__R_", target = "L______RR"
Output: true
Explanation: The L at index 1 moves left to index 0. The R at index 4 moves right to index 7, and the R at index 7 moves right to index 8. Every piece stays on the correct side of its target. The pieces keep their order, so the answer is true.

Approach 1: Brute force: list the pieces, then pair them

Write down the position of every piece in each string. List the pieces in order and compare the lists. Pieces keep their order, so the k-th piece in start must become the k-th piece in target. Each pair then gets the letter and direction checks.

This is correct and easy to reason about. It uses two lists that can each hold up to n positions. The next approach removes that cost.

Steps

  1. Scan start and store the index of every 'L' or 'R' in a list.
  2. Scan target and build the same kind of list.
  3. If the two lists have different lengths, return false, because the piece counts differ.
  4. For each rank k, read the k-th index from both lists.
  5. If the letters at those two indexes differ, return false.
  6. If an L has a larger index in start than in target, or an R has a smaller one, return false.
  7. If every pair passes, return true.

Dry run

Pieces in start (_L__R__R_) sit at sIdx = [1, 4, 7]. Pieces in target (L______RR) sit at tIdx = [0, 7, 8].

Pair 1: start[1] = 'L' and target[0] = 'L'. The letters match. The start index 1 is greater than or equal to the target index 0, so the L moves left. The pair passes.

Pair 2: start[4] = 'R' and target[7] = 'R'. The letters match. The start index 4 is less than or equal to 7, so the R moves right. The pair passes.

Pair 3: start[7] = 'R' and target[8] = 'R'. The letters match. The start index 7 is less than or equal to 8. The pair passes.

All pairs pass, so the output is true.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of the strings. Each string is scanned once to build its list, which costs O(n) in total. The comparison loop visits each stored piece once, and there are at most n pieces, so the loop adds O(n). The two lists can hold up to n indexes each, which gives O(n) extra space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canChange(self, start: str, target: str) -> bool:
        # Positions of every piece, left to right
        s_idx = [i for i, c in enumerate(start) if c != '_']
        t_idx = [i for i, c in enumerate(target) if c != '_']
        if len(s_idx) != len(t_idx):
            return False
        # Pieces never cross, so the k-th piece of start must become the k-th piece of target
        for si, ti in zip(s_idx, t_idx):
            if start[si] != target[ti]:
                return False
            if start[si] == 'L' and si < ti:
                return False
            if start[si] == 'R' and si > ti:
                return False
        return True

The In-place Array Modification infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

In-place Array Modification

Part of Two Pointers

Approach 2: Two pointers, no extra listsOptimalIn-place Array Modification

What is slow: the list approach stores the position of every piece, which costs O(n) extra space. It also makes a full pass over each string before it compares anything.

The insight that fixes it: the k-th piece of start always pairs with the k-th piece of target. You never need the whole list. Two indexes can walk forward and produce the next pair on demand. Each index skips blanks, the pair gets checked, and both indexes move past it.

Why it is correct. The pairing is forced, because pieces never pass each other, so the k-th piece of start must end up as the k-th piece of target. No other pairing is possible, so the greedy walk never discards a valid answer and never has to backtrack. If every pair passes the direction check, each L can slide left and each R can slide right into its target slot.

Steps

  1. Set i and j to 0. i walks start and j walks target.
  2. Move i forward past every blank in start. Move j forward past every blank in target.
  3. If either index has reached n, return true only when both have reached n.
  4. Compare start[i] with target[j]. Return false if they differ.
  5. If the piece is 'L' and i < j, return false. If it is 'R' and i > j, return false.
  6. Move both i and j one step forward, then repeat from the skip step.

Dry run

The table below traces the example start = _L__R__R_, target = L______RR. Each row is one pass of the main loop.

Stepi after skipj after skipstart[i]target[j]Checki, j after advance
110LLMatch, and i >= j so the L moves left2, 1
247RRMatch, and i <= j so the R moves right5, 8
378RRMatch, and i <= j so the R moves right8, 9
499endendBoth indexes reached nreturn true

Step 2 skips four blanks in target before it reaches index 7. Step 4 finds both indexes at n, so the output is true.

Complexity

TimeO(n)
SpaceO(1)

Let n be the string length. The index i only moves forward and never passes n, so the total increments across all skip loops is at most n. The same holds for j, so each pass consumes one piece from each string and the total work is O(n). The variables i, j and n are the only storage, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canChange(self, start: str, target: str) -> bool:
        n = len(start)
        i = j = 0
        while True:
            # Skip blanks in each string
            while i < n and start[i] == '_':
                i += 1
            while j < n and target[j] == '_':
                j += 1
            # Both strings must run out of pieces together
            if i == n or j == n:
                return i == n and j == n
            if start[i] != target[j]:
                return False
            # L can only move left, R can only move right
            if start[i] == 'L' and i < j:
                return False
            if start[i] == 'R' and i > j:
                return False
            i += 1
            j += 1

Common mistakes

  • Reversed direction test: if start[i] == 'L' and i > j rejects valid left moves and accepts impossible ones. An L fails only when i < j, because it can stay put or move left.
  • Returning early on one pointer: if i == n: return True ignores pieces still left in target. For start = _ and target = L, that returns true for an impossible case. Require both indexes to reach n.
  • Order-only check: start.replace('_', '') == target.replace('_', '') confirms the letters match but ignores direction. Start L_ and target _L pass that test, yet the L would have to move right. Add the index checks.
  • Advancing only one pointer after a match, or forgetting to advance at all. The same piece is compared again, and the loop never ends. Move both i and j past each matched pair.
  • Brute force without a length check: zip stops at the shorter list, so a string with fewer pieces can pass the loop silently. Compare the list lengths before pairing.
  • Swapped indexes: using ti > si as the test for an L flips the rule. Keep the start index on the left of each comparison, so an L needs si >= ti.

Edge cases

  • start = _ and target = L: the piece counts differ, so the answer is false.
  • start = L_ and target = _L: the L would have to move right, so the answer is false.
  • start = _L and target = L_: the L moves one step left, so the answer is true.
  • start = ____ and target = ____: there are no pieces, so the answer is true.
  • start = _R and target = R_: the R can only move right, so the answer is false.
  • n = 100000 with identical strings full of pieces: the answer is true, and the pointers must never read past index n - 1.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Move Pieces to Obtain a String, with how to answer them.

Unlock the follow-ups

Move Pieces to Obtain a String FAQ

What is the time complexity of Move Pieces to Obtain a String?

The two-pointer solution runs in O(n) time, where n is the string length. Each index moves forward and never passes n. The list-based version also runs in O(n) time, but it uses O(n) extra space.

Why use two pointers for Move Pieces to Obtain a String?

Pieces keep their order, so the k-th piece in start must match the k-th piece in target. Two forward-moving indexes can find each matching pair in one scan. No search or simulation is needed.

Can Move Pieces to Obtain a String be solved in O(1) extra space?

Yes. The two-pointer version stores only two indexes and the length. The list-based approach needs O(n) space because it stores every piece position.

Do I need to simulate the moves?

No. The letter check and the two direction checks decide the answer exactly. Simulating moves would explore a huge number of states and is unnecessary.

Why does comparing the strings with underscores removed fail?

That check confirms the order of letters but ignores direction. For L_ and _L, the letters match, yet the L would have to move right, so the answer is false.

Asked at

See which companies ask this — Pro

Practise it