Leetcode 777. Swap Adjacent in LR String
The problem statement can be found on LeetCode under the title “777. Swap Adjacent in LR String”. Below is a summary of the problem statement.
In a string composed of ‘L’, ‘R’, and ‘X’ characters:
Given two strings start
and end
, determine if it’s possible to transform the start
string into the end
string using a finite number of moves.
start
and end
are of the same length.true
?
true
only if it’s possible to transform start
to end
.Check Length and Characters: Ensure both strings are of the same length and contain the same set of characters when ‘X’ is ignored (since ‘X’ can be both present and moved around freely).
Double Pointer Technique:
i
for start
and j
for end
.start[i]
with end[j]
:
false
.i
is not less than j
because ‘L’ can only move left.i
is not greater than j
because ‘R’ can only move right.Here’s the implementation of the strategy:
#include <iostream>
#include <string>
bool canTransform(std::string start, std::string end) {
int n = start.size();
int i = 0, j = 0;
while (i < n || j < n) {
// Skip all 'X' in start
while (i < n && start[i] == 'X') i++;
// Skip all 'X' in end
while (j < n && end[j] == 'X') j++;
// If both pointers reach the end
if (i == n && j == n) return true;
// If only one of them reaches the end
if (i == n || j == n) return false;
// If characters are not matching
if (start[i] != end[j]) return false;
// If characters are 'L'
if (start[i] == 'L' && i < j) return false;
// If characters are 'R'
if (start[i] == 'R' && i > j) return false;
// Move both pointers
i++;
j++;
}
return true;
}
int main() {
std::string start = "RXXLRXRXL";
std::string end = "XRLXXRRLX";
bool result = canTransform(start, end);
std::cout << (result ? "True" : "False") << std::endl;
return 0;
}
The time complexity of this approach is O(n)
where n
is the length of the strings because we are essentially traversing each string once with our pointers.
i
and j
to traverse start
and end
, respectively.This ensures an efficient check in linear time with respect to the length of the strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?