Leetcode 777: Swap Adjacent in LR String

grid47
grid47
Exploring patterns and algorithms
Aug 21, 2024 7 min read

A string where adjacent characters are swapped, glowing softly with each swap.
Solution to LeetCode 777: Swap Adjacent in LR String Problem

You are given a string start and a string result composed of the characters ‘L’, ‘R’, and ‘X’. A move consists of either replacing an occurrence of ‘XL’ with ‘LX’, or replacing an occurrence of ‘RX’ with ‘XR’. Return true if it is possible to transform start into result by applying a sequence of these moves.
Problem
Approach
Steps
Complexity
Input: The input consists of two strings: start and result. Both strings are composed of characters 'L', 'R', and 'X'.
Example: Input: start = 'XRRXXLRX', result = 'XRRLXXRX'
Constraints:
• 1 <= start.length <= 10^4
• start.length == result.length
• Both strings consist only of the characters 'L', 'R', and 'X'.
Output: Return true if it is possible to transform start into result through a series of valid moves, otherwise return false.
Example: Output: true
Constraints:
• The output must be either true or false based on the possibility of transformation.
Goal: The goal is to check if a sequence of moves can transform the start string into the result string.
Steps:
• First, ensure that both the start and result strings contain the same number of 'L' and 'R' characters.
• Then, compare the positions of 'L' and 'R' in the start and result strings.
• Finally, verify that no illegal swaps (such as moving 'L' after 'R' in the wrong direction) are attempted.
Goal: The constraints ensure that both start and result strings have the same length, and the solution needs to handle strings of size up to 10^4 efficiently.
Steps:
• Both start and result strings are guaranteed to have the same length.
• Both strings only consist of characters 'L', 'R', and 'X'.
• The number of 'L' and 'R' in the start string must match the result string.
Assumptions:
• The input strings will be of equal length and consist only of 'L', 'R', and 'X'.
Input: Example 1: Input: start = 'XRRXXLRX', result = 'XRRLXXRX'
Explanation: The transformation is possible in one step: XRRXXLRX → XRRLXXRX.

Input: Example 2: Input: start = 'LR', result = 'RL'
Explanation: No sequence of moves can transform 'LR' to 'RL', so the result is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus