Skip to main content

Merge Close Characters - Solution & Explanation

MediumHash TableString8 min readAsked at: Zoho
Practice this problem

Problem Statement

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:

Input: s = "abca", k = 3

Output: "abc"

Explanation:

  • ​​​​​​​Characters 'a' at indices i = 0 and i = 3 are close as 3 - 0 = 3 <= k.
  • Merge them into the left 'a' and s = "abc".
  • No other equal characters are close, so no further merges occur.

Example 2:

Input: s = "aabca", k = 2

Output: "abca"

Explanation:

  • Characters 'a' at indices i = 0 and i = 1 are close as 1 - 0 = 1 <= k.
  • Merge them into the left 'a' and s = "abca".
  • Now the remaining 'a' characters at indices i = 0 and i = 3 are not close as k < 3, so no further merges occur.

Example 3:

Input: s = "yybyzybz", k = 2

Output: "ybzybz"

Explanation:

  • Characters 'y' at indices i = 0 and i = 1 are close as 1 - 0 = 1 <= k.
  • Merge them into the left 'y' and s = "ybyzybz".
  • Now the characters 'y' at indices i = 0 and i = 2 are close as 2 - 0 = 2 <= k.
  • Merge them into the left 'y' and s = "ybzybz".
  • No other equal characters are close, so no further merges occur.

 

Constraints:

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

Approach Overview

Problem Overview: You are given a string and must merge characters that are considered close (typically adjacent in alphabet order). Characters that differ by at most one position can be grouped together, and the final result depends on combining their frequencies efficiently.

Approach 1: Sorting + Linear Merge (O(n log n) time, O(n) space)

One straightforward strategy is to sort the characters in the string and then scan from left to right. After sorting, characters that are alphabetically close appear next to each other. You iterate through the sorted sequence and merge characters when their ASCII difference is ≤ 1. A running group tracks the current merged characters. Sorting dominates the complexity, giving O(n log n) time and O(n) auxiliary space for the sorted array.

Approach 2: Hash Table Frequency Merge (O(n) time, O(1) space)

The optimal solution counts character frequencies using a hash table. You iterate through the string once and store the frequency of each character. Since lowercase letters come from a fixed alphabet, you then iterate through the possible characters and merge counts of neighbors such as c with c-1 or c+1 if they are considered close. This avoids sorting and relies on constant-time hash lookups. The algorithm processes the string once and scans the alphabet once, giving O(n) time and O(1) space because the alphabet size is fixed.

This approach works well because the problem is fundamentally about frequency aggregation rather than positional ordering. Using a hash map lets you count characters quickly and then reason about adjacency directly in the alphabet rather than in the string itself.

Implementation usually uses a frequency array of size 26 (for lowercase letters) or a dictionary if the character range is larger. Each character contributes a constant-time increment, and merging operations are simple arithmetic on neighboring buckets. The technique is common in string problems where relationships between characters depend on their values rather than positions.

Recommended for interviews: The hash table approach is what interviewers expect. A sorting-based solution demonstrates the basic idea but costs O(n log n). Using a hash map or fixed-size frequency array shows you recognize that the alphabet is bounded and can reduce the complexity to O(n).

Solution

We use a hash table last to record the last occurrence position of each character. We iterate over each character in the string. If the current character has appeared before and the difference between the current index and its last occurrence index is at most k, we skip the character; otherwise, we add the character to the answer and update its position in the hash table.

The time complexity is O(n), and the space complexity is O(|\Sigma|), where n is the length of the string, and |\Sigma| is the size of the character set. In this problem, the character set consists of lowercase English letters, so |\Sigma| is a constant.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sorting + Linear MergeO(n log n)O(n)When simplicity matters and sorting the characters is acceptable
Hash Table Frequency MergeO(n)O(1)General optimal solution using frequency counting and constant-time lookups

Video Solution

LeetCode 3853 | Merge Close Characters | Simulation | Java • Code Kage • 187 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Merge Close Characters easy or hard?
Merge Close Characters is generally considered a medium-level problem. The logic is simple once you recognize that character frequencies matter more than positions, but identifying the hash table optimization is the key step.
Merge Close Characters Python/Java solution
Most implementations use a dictionary or array to count character frequencies, then iterate through the alphabet to combine counts of adjacent characters. The same idea translates directly to Python, Java, C++, Go, and TypeScript with similar O(n) complexity.
How to solve Merge Close Characters in O(n)?
Use a hash table or fixed-size frequency array to count characters while iterating through the string. After building the counts, check neighboring characters (like c-1 and c+1) and merge their frequencies when they are considered close. This avoids sorting and keeps the algorithm linear.
What is the best approach for Merge Close Characters?
The hash table frequency approach is the most efficient. Count occurrences of each character in one pass, then merge counts for characters that are alphabetically close. This reduces the complexity to O(n) time with O(1) extra space when the alphabet size is fixed.
Is Merge Close Characters asked at Google/Amazon/Meta?
String and hash table problems with character grouping patterns frequently appear in interviews at companies like Amazon, Google, and Meta. Variations of frequency merging and alphabet-based grouping are common interview exercises.
What data structure is used in Merge Close Characters?
The primary data structure is a hash table (or a fixed-size frequency array for lowercase letters). It stores counts of characters so that neighboring characters can be merged efficiently using constant-time lookups.
What is the time complexity of Merge Close Characters?
The optimal solution runs in O(n) time where n is the length of the string. The algorithm scans the string once to build a frequency map and then processes a constant-size alphabet to merge neighboring characters.

Ready to solve this problem?

Practice Merge Close Characters with our built-in code editor and test cases.

Practice on FleetCode