3992. Rearrange String to Avoid Character Pair
Description
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
Solutions
Solution 1: Two Pointers
We need to construct a permutation \(t\) of \(s\) such that every occurrence of \(y\) appears before every occurrence of \(x\). There are no extra constraints on the other characters.
Therefore, it suffices to move all occurrences of \(y\) to the front of the string. Traverse the string with two pointers: \(i\) points to the next position where a \(y\) should be placed, and \(j\) scans from left to right. Whenever \(t[j] = y\), swap \(t[i]\) with \(t[j]\) and increment \(i\). After the scan, the prefix of \(t\) consists entirely of \(y\), which naturally satisfies the requirement that all \(y\) appear before all \(x\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of \(s\).
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |