algoadvance

Given a string that consists of only ‘L’, ‘R’, and ‘X’ characters. You need to determine if the string can be transformed into another string by swapping adjacent ‘L’ and ‘X’, or ‘R’ and ‘X’. The ‘L’ can only move to the left and ‘R’ can only move to the right.

Clarifying Questions

  1. String Length: Is there any constraint on the length of the input strings?
    • Assume reasonable constraints typical of LeetCode problems, e.g., up to (10^4) characters.
  2. Input Validity: Can we assume the input strings are always valid and contain only ‘L’, ‘R’, and ‘X’?
    • Yes, you can assume the input constraints are respected.
  3. Transformation Rules: Just confirm – ‘L’ can only move left through ‘X’ and ‘R’ can only move right through ‘X’?
    • Correct.

Strategy

  1. Character Mismatch: First, ensure both strings have the same number of ‘L’, ‘R’, and ‘X’ characters.
  2. Position Validity for ‘L’ and ‘R’:
    • For ‘L’: Since ‘L’ can only move left, its position in the first string must be greater than or equal to its position in the second string.
    • For ‘R’: Since ‘R’ can only move right, its position in the first string must be less than or equal to its position in the second string.
  3. Pairwise Check: Traverse both strings while skipping ‘X’, and check the validity of positions for ‘L’ and ‘R’.

Code

def canTransform(start: str, end: str) -> bool:
    # Check if both strings have the same number of 'L's and 'R's
    if start.replace('X', '') != end.replace('X', ''):
        return False

    # Check positions of 'L'
    t = [(i, c) for i, c in enumerate(start) if c != 'X']
    e = [(i, c) for i, c in enumerate(end) if c != 'X']

    for (i, c1), (j, c2) in zip(t, e):
        if c1 != c2:
            return False
        if c1 == 'L' and i < j:
            return False
        if c1 == 'R' and i > j:
            return False

    return True

# Example usage:
start = "RXXLRXRXL"
end = "XRLXXRRLX"
print(canTransform(start, end))  # Output: True

Time Complexity

This efficiently checks all the transformation constraints. If you have any specific edge cases or further details, do let me know!

Try our interview co-pilot at AlgoAdvance.com