Merge Close Characters

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.

Example 1
Inputs = "abca", k = 3
Output"abc"
Characters 'a' at indices 0 and 3 are close, so the right one merges into the left and no further merges are possible.
Example 2
Inputs = "aabca", k = 2
Output"abca"
Characters 'a' at indices 0 and 1 merge first, producing "abca", and the remaining 'a' characters are too far apart to merge.

Constraints

  • 1 <= s.length <= 100
  • 1 <= k <= s.length
  • s consists of lowercase English letters.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate