[LeetCode] Merge Close Characters

3853. Merge Close Characters

You are given a string s consisting of lowercase English letters and an integer k.

Two equal characters in the current string s are considered close if the distance between their indices is at most k.

When two characters are close, the right one merges into the left. Merges happen one at a time, and after each merge, the string updates until no more merges are possible.

Return the resulting string after performing all possible merges.

Note: If multiple merges are possible, always merge the pair with the smallest left index. If multiple pairs share the smallest left index, choose the pair with the smallest right index.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string mergeCharacters(string s, int k) {
string res = "";
for(auto& ch : s) {
bool ok = false;
for(int j = res.length() - 1, op = k; j >= 0 and op > 0 and !ok; op--,j--) {
if(res[j] == ch) ok = true;
}
if(!ok) res.push_back(ch);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/merge-close-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.