[LeetCode] Merge Close Characters II

4019. Merge Close Characters II

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

Two equal characters s[i] and s[j], where 0 <= i < j < s.length, are considered close if j - i <= k. All indices refer to the current string.

Repeatedly perform the following operation until no close pair remains:

  • Among all close pairs (i, j), choose the pair with the smallest i. If multiple pairs have the same i, choose the one with the smallest j.
  • Merge the right character into the left character by removing s[j] from s. The character s[i] remains unchanged, and the remaining characters are reindexed.

Return the resulting string after performing all possible merges.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string mergeCharacters(string s, int k) {
string res = "";

for(auto& ch : s) {
bool ok = false;

int start = max(0, int(res.length()) - k);

for(int j = start; j < res.length(); 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/03/PS/LeetCode/merge-close-characters-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.