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:
'a' at indices i = 0 and i = 3 are close as 3 - 0 = 3 <= k.'a' and s = "abc".Example 2:
Input: s = "aabca", k = 2
Output: "abca"
Explanation:
'a' at indices i = 0 and i = 1 are close as 1 - 0 = 1 <= k.'a' and s = "abca".'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:
'y' at indices i = 0 and i = 1 are close as 1 - 0 = 1 <= k.'y' and s = "ybyzybz".'y' at indices i = 0 and i = 2 are close as 2 - 0 = 2 <= k.'y' and s = "ybzybz".Constraints:
1 <= s.length <= 1001 <= k <= s.lengths consists of lowercase English letters.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:
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:
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 ""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:
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)| Case | How to Handle |
|---|---|
| Empty string or single character string | Return the input string immediately since adjacent pairs cannot exist. |
| String with length two where characters are identical and within distance k | The stack based reduction correctly removes both characters and returns an empty string. |
| K is zero and the string has adjacent identical characters | 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 | 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 | 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 | 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 | 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 | The algorithm traverses the string once and returns the original string unchanged. |