Merge Close Characters II Problem
Description
LeetCode Problem 4019.
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 smallesti. If multiple pairs have the samei, choose the one with the smallestj. - Merge the right character into the left character by removing
s[j]froms. The characters[i]remains unchanged, and the remaining characters are reindexed.
Return the resulting string after performing all possible merges.
Example 1:
Input: s = "abca", k = 3
Output: "abc"
Explanation:
- The characters 'a' at indices 0 and 3 are close because 3 - 0 = 3 <= k.
- Remove the right 'a', resulting in s = "abc".
- No close pair remains, so no further merges are performed.
Example 2:
Input: s = "aabca", k = 2
Output: "abca"
Explanation:
- The characters 'a' at indices 0 and 1 are close because 1 - 0 = 1 <= k.
- Remove the right 'a', resulting in s = "abca".
- The remaining 'a' characters are at indices 0 and 3. Since 3 - 0 = 3 > k, no further merges are performed.
Example 3:
Input: s = "yybyzybz", k = 2
Output: "ybzybz"
Explanation:
- The characters 'y' at indices 0 and 1 are close because 1 - 0 = 1 <= k. This pair has the smallest left index among all close pairs.
- Remove the right 'y', resulting in s = "ybyzybz".
- The characters 'y' at indices 0 and 2 are now close because 2 - 0 = 2 <= k.
- Remove the right 'y', resulting in s = "ybzybz".
- No close pair remains, so no further merges are performed.
Constraints:
1 <= s.length <= 5 * 10^51 <= k <= s.lengthsconsists of lowercase English letters.
Solution
Approach: Hash Table
A merge always removes the right character of a close pair, so the final string is a left-to-right selection of the original characters. Scan s once and build the answer: if the current letter occurred before in the answer and its last position there is at most k away from the position it would take now (the current answer length), it is removed; otherwise append it and record its position.
Because only the right character is ever deleted, positions in the answer are exactly the indices in the current string, so this single pass gives the same result as performing the merges one by one.
Complexity: time O(n), space O(1) (26 letters), where n is the length of s.
class Solution:
def mergeCharacters(self, s: str, k: int) -> str:
last = {}
ans = []
for c in s:
cur = len(ans)
if c in last and cur - last[c] <= k:
continue
ans.append(c)
last[c] = cur
return ''.join(ans)