Talentd
FleetCode

4019. Merge Close Characters II

Medium78.7% acceptancePremium elsewhere, free here

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.

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 * 105
  • 1 <= k <= s.length
  • s consists of lowercase English letters.
8:06
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples

No sample inputs for this problem yet. The examples in the statement show the format.

Your code is saved on this device.Solution