Rearrange String to Avoid Character Pair Problem
#3992
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3992.
You are given a string s and two distinct lowercase English letters x and y.
Rearrange the characters of s to construct a new string t such that:
tis a permutation ofs.- Every occurrence of
yappears before every occurrence ofxint.
Return any valid string t.
Example 1:
Input: s = "aabc", x = "a", y = "c"
Output: "cbaa"
Explanation:
The string "cbaa" is a permutation of "aabc", and every occurrence of 'c' appears before every occurrence of 'a'.
Example 2:
Input: s = "dcab", x = "d", y = "b"
Output: "cabd"
Explanation:
The string "cabd" is a permutation of "dcab", and every occurrence of 'b' appears before every occurrence of 'd'.
Example 3:
Input: s = "axe", x = "o", y = "x"
Output: "axe"
Explanation:
The string "axe" is already valid. Since 'o' does not occur in the string, the required condition is automatically satisfied.
Constraints:
1 <= s.length <= 100sconsists of lowercase English letters.xandyare lowercase English letters.x != y
Solution
Approach: Two Pointers
The only requirement is that every y comes before every x; the other letters can be anywhere. So it is enough to move all occurrences of y to the front of the string.
Keep a pointer i for the next position where a y should be placed and scan the string with j. Whenever t[j] == y, swap t[i] and t[j] and advance i. At the end the first i characters are all y, so no x can come before any y.
Complexity: time O(n), space O(n).
class Solution:
def rearrangeString(self, s: str, x: str, y: str) -> str:
t = list(s)
i = 0
for j, c in enumerate(t):
if c == y:
t[i], t[j] = c, t[i]
i += 1
return ''.join(t)