#3853

Merge Close Characters

Medium
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a single pass with a stack to keep track of characters and their indices. This allows efficient merging by checking the top of the stack.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: For each character, check if it can merge with the top of the stack (within k distance).
  3. 3Step 3: If it can merge, pop the stack; otherwise, push the character onto the stack.
solution.py8 lines
1def mergeCloseCharacters(s, k):
2    stack = []
3    for i, char in enumerate(s):
4        if stack and stack[-1][0] == char and i - stack[-1][1] <= k:
5            stack.pop()
6        else:
7            stack.append((char, i))
8    return ''.join(c[0] for c in stack)

Complexity note: Each character is processed once, and the stack operations are efficient.

  • 1Merging depends on proximity and equality of characters.
  • 2Using a stack allows efficient tracking of characters and their indices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.