Similar Problems
Similar Problems not available
Swap Adjacent In Lr String - Leetcode Solution
Companies:
LeetCode: Swap Adjacent In Lr String Leetcode Solution
Difficulty: Medium
Topics: string two-pointers
Problem Statement:
Given a string composed of L and R characters, swap any two adjacent characters of the string so that the resulting string is lexicographically smaller. Return the lexicographically smallest string possible after performing the swap.
Approach:
To solve the problem, we need to find a character 'R' present in the string, which is on the left of any 'L' character. Such 'R' will be swapped with the left adjacent 'L' character.
For example, in the above string "RLRRLLRLRL", the 'R' character present at index 0 is on the left of 'L' character present at index 1. So, we swap these two characters, and we get the string "LRRRLLRLRL", which is lexicographically smaller.
If there are no such 'R' characters, we return the original string.
Algorithm:
-
Loop through the input string from left to right.
-
If current character is 'R', check if there is any 'L' character on the left side of current character or not.
-
If there is any 'L' character on the left side of current character, swap both characters and return the new string.
-
If there is no 'L' character on the left side of current character, continue with next character.
-
If no such 'R' character is found, return the original string.
Code:
Here's the Python code that implements the above algorithm:
class Solution: def canTransform(self, s: str) -> str:
s = list(s)
n = len(s)
# Loop through the string from left to right
for i in range(n):
# If current character is 'R'
if s[i] == 'R':
# Check if there is any 'L' character on the left side of current character
for j in range(i):
if s[j] == 'L':
# Swap both characters
s[i], s[j] = s[j], s[i]
# Return the new string
return ''.join(s)
# If there is no 'L' character on the left side of current character, continue with next character
continue
# If no such 'R' character is found, return the original string
return ''.join(s)
Time Complexity:
The time complexity of the above algorithm is O(n^2). We are looping through the input string two times, first to find the 'R' character and then to find the 'L' character. In the worst case, when the string has no 'R' character on the left of 'L' character, we will loop through the input string n times. This results in a time complexity of O(n^2).
Space Complexity:
The space complexity of the above algorithm is O(n). We are creating a list of characters for the input string, which requires n units of extra space.
Swap Adjacent In Lr String Solution Code
1