Swap Adjacent in LR String — LeetCode 777 Python Solution

MediumTwo PointersString
Problem
#777
Reading time
3 min

The problem

In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string result, return True if and only if there exists a sequence of moves to transform start to result.

Example

Input
start = "RXXLRXRXL", result = "XRLXXRRLX"
Output
true
Explanation
We can transform start to result following these steps:

Python solution

Python
class Solution:
    def canTransform(self, start: str, end: str) -> bool:
        n = len(start)
        i = j = 0
        while 1:
            while i < n and start[i] == 'X':
                i += 1
            while j < n and end[j] == 'X':
                j += 1
            if i >= n and j >= n:
                return True
            if i >= n or j >= n or start[i] != end[j]:
                return False
            if start[i] == 'L' and i < j:
                return False
            if start[i] == 'R' and i > j:
                return False
            i, j = i + 1, j + 1

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 777. Swap Adjacent in LR 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 777. Swap Adjacent in LR String?
LeetCode 777. Swap Adjacent in LR String is rated Medium on LeetCode.
What is the time complexity of LeetCode 777. Swap Adjacent in LR 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 777. Swap Adjacent in LR String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 777. Swap Adjacent in LR String cover?
LeetCode 777. Swap Adjacent in LR 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