Merge Close Characters
You are given a string s consisting of lowercase English letters and an integer k.
Two identical characters are close if their index difference in the current string is <= k. When two characters are close, the character on the right merges into the character on the left.
These merges happen one at a time. After a merge occurs, the string immediately updates, shifting remaining characters leftwards, and the process repeats until no more valid merges can be performed.
Return the final string after all possible merges are complete.
Note: If multiple valid merges are possible at the same time, you must strictly merge the pair with the smallest left index. If there is a tie for the left index, pick the pair with the smallest right index.
Example 1:
Input: s = "xxyyxx", k = 3
Output: "xy"
Explanation:
Always prioritizing the leftmost valid pairs, we consecutively merge the 'x's three times ("xxyyxx" -> "xyyxx" -> "xyyx" -> "xyy"). Finally, merging the remaining close 'y's leaves "xy".
Example 2:
Input: s = "aaaa", k = 2
Output: "a"
Explanation:
Multiple valid pairs of 'a' exist. The pair with the smallest left index (0) and smallest right index (1) is chosen to break the tie. Merge 'a' at 0 and 1. The string becomes "aaa". Merge 'a' at 0 and 1 again. The string becomes "aa". Merge 'a' at 0 and 1 one last time. The string becomes "a".
Now Your Turn!
Pick the correct output for the given inputInput: s = "ababa", k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= s.length <= 100
- 1 <= k <= s.length
- s consists entirely of lowercase English letters.