#3853
Medium Algorithms Merge close characters
Hash Table String
54.2% acceptance
Mar 16, 2026
66
12
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn merge_characters(s: String, k: i32) -> String {
let k = k as usize;
let mut chars: Vec<char> = s.chars().collect();
loop {
let mut found = false;
'outer: for i in 0..chars.len() {
for j in (i + 1)..chars.len() {
if j - i > k {
break;
}
if chars[i] == chars[j] {
chars.remove(j);
found = true;
break 'outer;
}
}
}
if !found {
break;
}
}
chars.into_iter().collect()
}
}