Solving Leetcode Interviews in Seconds with AI: Swap Adjacent in LR String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "777" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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 1: Input: start = "RXXLRXRXL", result = "XRLXXRRLX" Output: true Explanation: We can transform start to result following these steps: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX Example 2: Input: start = "X", result = "L" Output: false Constraints: 1 <= start.length <= 104 start.length == result.length Both start and result will only consist of characters in 'L', 'R', and 'X'.
Explanation
Here's the breakdown of the solution:
- Focus on 'L' and 'R': The 'X' characters are essentially placeholders that can be moved around. We only need to ensure that the relative order of 'L' and 'R' characters remains the same between the start and end strings.
- 'L' Movement: An 'L' can only move to the left (towards the beginning of the string). Therefore, in the transformed string, an 'L' must be at or to the left of its original position.
'R' Movement: An 'R' can only move to the right (towards the end of the string). Therefore, in the transformed string, an 'R' must be at or to the right of its original position.
Runtime Complexity: O(n), where n is the length of the strings.
- Storage Complexity: O(1)
Code
def canTransform(start: str, end: str) -> bool:
n = len(start)
i, j = 0, 0
while i < n and j < n:
while i < n and start[i] == 'X':
i += 1
while j < n and end[j] == 'X':
j += 1
if i < n and j < n:
if start[i] != end[j]:
return False
if start[i] == 'L':
if i < j:
return False
elif start[i] == 'R':
if i > j:
return False
i += 1
j += 1
while i < n and start[i] == 'X':
i += 1
while j < n and end[j] == 'X':
j += 1
return i == n and j == n