Taro Logo

Merge Close Characters

Medium
Asked by:
Zoho
4 views
Topics:
StringsStacks

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set does the string `s` consist of? For example, are we strictly dealing with lowercase English letters, or could it include uppercase letters, digits, or Unicode characters?
  2. How is the alphabet distance defined for non-lowercase characters (e.g., case sensitivity, wrap-arounds, or ASCII values)?
  3. Could the removal of a pair create a *new* adjacent pair of identical characters that also satisfy the distance condition, and should those be processed subsequently?
  4. What should be returned if the input string is empty, or if no such adjacent pairs exist from the start?
  5. When the problem states 'distance in the alphabet is at most k', does it mean the absolute difference in their alphabetical positions (e.g., 'a' and 'c' have a distance of 2), and is `k` guaranteed to be a non-negative integer?

Brute Force Solution

Approach

Imagine you have a string of letters where certain characters are too close to each other and need to be combined or eliminated. The brute force approach tries every possible combination of merging adjacent characters until no more forbidden closeness remains.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire sequence of characters from beginning to end.
  2. Identify any two neighboring characters that violate the closeness rule.
  3. Try merging that specific pair into a single combined character or removing them entirely, creating a brand new version of the sequence.
  4. Take this new version of the sequence and repeat the process of checking for any remaining close characters.
  5. If you run into a dead end where new violations appear, undo your last change and try merging a different pair of neighboring characters instead.
  6. Exhaustively explore every single path of choices, trying different orders of merging until you find at least one final sequence that has no close characters left.
  7. Compare all the successful final sequences you managed to create and pick the best one according to the goals of the problem.

Code Implementation

def merge_close_characters_brute_force(input_string):    # We use recursion to exhaustively try every possible merging order to explore all paths    def explore_merge_paths(current_sequence):        for character_index in range(len(current_sequence) - 1):            if current_sequence[character_index] == current_sequence[character_index + 1]:                modified_sequence = current_sequence[:character_index] + current_sequence[character_index + 2:]                successful_result = explore_merge_paths(modified_sequence)                if successful_result is not None:                    return successful_result        # When no violations remain, this base path is successful and returns the final sequence        if not any(current_sequence[index] == current_sequence[index + 1] for index in range(len(current_sequence) - 1)):            return current_sequence        return None    # Initiate the recursive search starting from the original input sequence    final_output = explore_merge_paths(input_string)    return final_output if final_output is not None else ""

Big(O) Analysis

Time Complexity
O(2^n) – The brute force approach uses exhaustive recursion to try every possible combination of merging adjacent characters in a string of length n. At each step, if a violation is found, the algorithm branches by trying different valid pairs to merge, creating a search tree of choices. In the worst case, the number of recursive branches and possible sequences grows exponentially with the length of the string. This mirrors combinations where the total operations approximate 2^n paths, which simplifies to the exponential Big O time complexity.
Space Complexity
O(n) – The space complexity is driven by the recursion stack used to exhaustively explore every single path of character merges and the temporary strings generated at each decision level. In the worst-case scenario, where merging happens sequentially, the maximum depth of the recursive calls reaches N, where N is the length of the input string. Additionally, storing intermediate versions of the sequence during backtracking consumes auxiliary space proportional to the depth of the exploration tree. Therefore, the total extra memory required scales linearly with the input size N, leading to an overall space complexity of O(n).

Optimal Solution

Approach

Instead of repeatedly scanning and removing characters from the beginning, the optimal approach uses a temporary holding area to build the final result efficiently in a single pass. By remembering what we have seen and comparing it to what we are currently looking at, we can safely combine characters on the fly.

Here's how the algorithm would work step-by-step:

  1. Set up a temporary holding space to collect characters as we process them one by one from the original text.
  2. Look at the current character you want to add to the holding space.
  3. Compare this current character to the most recently added character sitting at the very end of the holding space.
  4. If the current character is too similar or matches the one at the end of the holding space, discard both of them instead of adding the new one.
  5. If they are different, go ahead and add the current character to the end of the holding space.
  6. Continue this process for every character in the text, allowing characters that were previously separated to meet and combine once their neighbors are removed.
  7. Once all characters have been processed, the contents of the holding space represent the final merged result.

Code Implementation

def merge_close_characters(input_text):
    holding_space = []

    # We use a stack to track characters, allowing adjacent matches to cancel out efficiently in one pass.
    for current_character in input_text:
        if holding_space and holding_space[-1] == current_character:
            # Matching adjacent elements cancel each other out to handle cascading removals correctly.
            holding_space.pop()
        else:
            # Non-matching elements are kept to form the new sequence after previous neighbors vanish.
            holding_space.append(current_character)

    return "".join(holding_space)

Big(O) Analysis

Time Complexity
O(n) – As we process each of the n characters in the input text in a single pass, we perform constant-time operations to compare and push or pop from the temporary holding space. Each character is pushed onto the holding space at most once and popped at most once. This linear traversal and localized checking means the total operations grow directly proportional to n, which simplifies to O(n).
Space Complexity
O(N) – The auxiliary space is driven by the temporary holding space used to build the final result string, where N represents the length of the input text. In the worst-case scenario where no characters are discarded, this holding space will store all N characters. Therefore, the memory consumed by this holding space scales directly and linearly with the size of the input, resulting in a linear space complexity.

Edge Cases

Empty string or single character string
How to Handle:
Return the input string immediately since adjacent pairs cannot exist.
String with length two where characters are identical and within distance k
How to Handle:
The stack based reduction correctly removes both characters and returns an empty string.
K is zero and the string has adjacent identical characters
How to Handle:
Only identical characters with an alphabet distance of zero will be removed iteratively.
K is large enough that any two adjacent characters satisfy the distance condition
How to Handle:
The algorithm collapses all adjacent identical characters from left to right until no adjacent duplicates remain.
Removal of a pair creates a new adjacent identical pair of close characters
How to Handle:
Using a stack data structure allows newly formed adjacent pairs to be evaluated and merged correctly.
Multiple valid adjacent pairs exist at the same time
How to Handle:
Iterating linearly or using a stack ensures the leftmost pair is always prioritized and removed first.
Maximum length constraints up to one hundred thousand characters
How to Handle:
Using a linear time stack based approach prevents the quadratic time complexity of repeated string slicing.
String with no adjacent identical characters satisfying the distance k constraint
How to Handle:
The algorithm traverses the string once and returns the original string unchanged.