15% off all plans & roadmaps Use code
See plansMove Pieces to Obtain a String
- LeetCode 2337
- Medium
- Two Pointers
- In-place Array Modification
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.length1 <= n <= 10^5startandtargetconsist only of'L','R', and'_'.
Constraints that matter
ncan 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.
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.
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
- Scan
startand store the index of every'L'or'R'in a list. - Scan
targetand build the same kind of list. - If the two lists have different lengths, return
false, because the piece counts differ. - For each rank k, read the k-th index from both lists.
- If the letters at those two indexes differ, return
false. - If an
Lhas a larger index instartthan intarget, or anRhas a smaller one, returnfalse. - 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
| Time | O(n) |
|---|---|
| Space | O(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 TrueThe 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 infographicSolution 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
- Set
iandjto 0.iwalksstartandjwalkstarget. - Move
iforward past every blank instart. Movejforward past every blank intarget. - If either index has reached
n, returntrueonly when both have reachedn. - Compare
start[i]withtarget[j]. Returnfalseif they differ. - If the piece is
'L'andi < j, returnfalse. If it is'R'andi > j, returnfalse. - Move both
iandjone 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.
| Step | i after skip | j after skip | start[i] | target[j] | Check | i, j after advance |
|---|---|---|---|---|---|---|
| 1 | 1 | 0 | L | L | Match, and i >= j so the L moves left | 2, 1 |
| 2 | 4 | 7 | R | R | Match, and i <= j so the R moves right | 5, 8 |
| 3 | 7 | 8 | R | R | Match, and i <= j so the R moves right | 8, 9 |
| 4 | 9 | 9 | end | end | Both indexes reached n | return 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
| Time | O(n) |
|---|---|
| Space | O(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 += 1Common mistakes
- Reversed direction test:
if start[i] == 'L' and i > jrejects valid left moves and accepts impossible ones. AnLfails only wheni < j, because it can stay put or move left. - Returning early on one pointer:
if i == n: return Trueignores pieces still left intarget. Forstart=_andtarget=L, that returnstruefor an impossible case. Require both indexes to reachn. - Order-only check:
start.replace('_', '') == target.replace('_', '')confirms the letters match but ignores direction. StartL_and target_Lpass that test, yet theLwould 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
iandjpast each matched pair. - Brute force without a length check:
zipstops 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 > sias the test for anLflips the rule. Keep the start index on the left of each comparison, so anLneedssi >= ti.
Edge cases
start=_andtarget=L: the piece counts differ, so the answer isfalse.start=L_andtarget=_L: theLwould have to move right, so the answer isfalse.start=_Landtarget=L_: theLmoves one step left, so the answer istrue.start=____andtarget=____: there are no pieces, so the answer istrue.start=_Randtarget=R_: theRcan only move right, so the answer isfalse.n= 100000 with identical strings full of pieces: the answer istrue, and the pointers must never read past indexn - 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-upsMove 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
Related problems
- Sort Colors · same technique: In-place Array Modification
- String Compression · same technique: In-place Array Modification
- Remove Duplicates from Sorted Array II · same technique: In-place Array Modification
- Separate Black and White Balls · same technique: In-place Array Modification
- Trapping Rain Water · same technique: In-place Array Modification
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers