Move Pieces to Obtain a String — LeetCode 2337 Python Solution

MediumTwo PointersString
Problem
#2337
Reading time
3 min

The problem

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.

Example

Input
start = "_L__R__R_", target = "L______RR"
Output
true
Explanation
We can obtain the string target from start by doing the following moves:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2337. Move Pieces to Obtain a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2337. Move Pieces to Obtain a String?
LeetCode 2337. Move Pieces to Obtain a String is rated Medium on LeetCode.
What is the time complexity of LeetCode 2337. Move Pieces to Obtain a String?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 2337. Move Pieces to Obtain a String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2337. Move Pieces to Obtain a String cover?
LeetCode 2337. Move Pieces to Obtain a String is tagged Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview