[LeetCode] Rearrange String to Avoid Character Pair

3992. Rearrange String to Avoid Character Pair

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:

  • t is a permutation of s.
  • Every occurrence of y appears before every occurrence of x in t.

Return any valid string t.

1
2
3
4
5
6
7
8
9
class Solution {
public:
string rearrangeString(string s, char x, char y) {
for(int i = 0, j = 0; i < s.length(); i++) {
if(s[i] == y) swap(s[i], s[j++]);
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/rearrange-string-to-avoid-character-pair/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.