You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words.
Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations:
s1.s1.s1 with any letter, including itself.The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true:
Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique.
Return an array ans of size 2 where:
ans[0] is the maximum number of groups words can be divided into, andans[1] is the size of the largest group.Example 1:
Input: words = ["a","b","ab","cde"] Output: [2,3] Explanation: - words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2]. - words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2]. - words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1]. - words[3] is not connected to any string in words. Thus, words can be divided into 2 groups ["a","b","ab"] and ["cde"]. The size of the largest group is 3.
Example 2:
Input: words = ["a","ab","abc"] Output: [1,3] Explanation: - words[0] is connected to words[1]. - words[1] is connected to words[0] and words[2]. - words[2] is connected to words[1]. Since all strings are connected to each other, they should be grouped together. Thus, the size of the largest group is 3.
Constraints:
1 <= words.length <= 2 * 1041 <= words[i].length <= 26words[i] consists of lowercase English letters only.words[i].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 collection of words and you want to organize them into connected groups based on whether they can be formed by adding, removing, or swapping a single letter. The brute force approach involves testing every possible pair of words to see if they are closely related.
Here's how the algorithm would work step-by-step:
class DisjointSetUnion:
def __init__(self, total_elements):
self.parent_nodes = list(range(total_elements))
self.group_sizes = [1] * total_elements
self.total_groups = total_elements
def find_root(self, element):
current_element = element
while current_element != self.parent_nodes[current_element]:
self.parent_nodes[current_element] = self.parent_nodes[self.parent_nodes[current_element]]
current_element = self.parent_nodes[current_element]
return current_element
def union_groups(self, first_element, second_element):
root_first = self.find_root(first_element)
root_second = self.find_root(second_element)
if root_first != root_second:
self.parent_nodes[root_first] = root_second
self.group_sizes[root_second] += self.group_sizes[root_first]
self.total_groups -= 1
class Solution:
def groupStrings(self, word_list):
total_words = len(word_list)
disjoint_set = DisjointSetUnion(total_words)
word_indices = {word: index for index, word in enumerate(word_list)}
# Exhaustively compare every pair to establish direct one-edit connections between words
for current_index in range(total_words):
current_word = word_list[current_index]
word_length = len(current_word)
for char_index in range(word_length):
deleted_variant = current_word[:char_index] + current_word[char_index + 1:]
if deleted_variant in word_indices:
disjoint_set.union_groups(current_index, word_indices[deleted_variant])
for char_index in range(word_length):
for replacement_code in range(97, 123):
replacement_char = chr(replacement_code)
if replacement_char != current_word[char_index]:
replaced_variant = current_word[:char_index] + replacement_char + current_word[char_index + 1:]
if replaced_variant in word_indices:
disjoint_set.union_groups(current_index, word_indices[replaced_variant])
for char_index in range(word_length + 1):
for replacement_code in range(97, 123):
replacement_char = chr(replacement_code)
added_variant = current_word[:char_index] + replacement_char + current_word[char_index:]
if added_variant in word_indices:
disjoint_set.union_groups(current_index, word_indices[added_variant])
# Find the maximum group size by checking all computed sizes across roots
maximum_size = 0
for index in range(total_words):
if disjoint_set.parent_nodes[index] == index:
if disjoint_set.group_sizes[index] > maximum_size:
maximum_size = disjoint_set.group_sizes[index]
return [disjoint_set.total_groups, maximum_size]To find how strings can be grouped and connected, the optimal strategy views each word as a collection of unique building blocks rather than just a sequence of letters. By cleverly transforming each word into a compact fingerprint, we can instantly recognize which words are related by simple changes like adding, removing, or swapping a letter.
Here's how the algorithm would work step-by-step:
class DisjointSetUnion:
def __init__(self, total_elements):
self.parent_pointers = list(range(total_elements))
self.component_sizes = [1] * total_elements
def find_set_root(self, element):
current_node = element
while current_node != self.parent_pointers[current_node]:
self.parent_pointers[current_node] = self.parent_pointers[self.parent_pointers[current_node]]
current_node = self.parent_pointers[current_node]
return current_node
def union_sets(self, first_element, second_element):
root_of_first = self.find_set_root(first_element)
root_of_second = self.find_set_root(second_element)
if root_of_first != root_of_second:
if self.component_sizes[root_of_first] < self.component_sizes[root_of_second]:
root_of_first, root_of_second = root_of_second, root_of_first
self.parent_pointers[root_of_second] = root_of_first
self.component_sizes[root_of_first] += self.component_sizes[root_of_second]
def group_strings(word_list):
unique_word_list = list(set(word_list))
total_unique_words = len(unique_word_list)
fingerprint_to_index = {}
# Bitmask fingerprints group words by exact character composition, ignoring order.
for word_index, current_word in enumerate(unique_word_list):
bitmask_value = 0
for character in current_word:
bitmask_value |= 1 << (ord(character) - ord('a'))
fingerprint_to_index[bitmask_value] = word_index
union_find_structure = DisjointSetUnion(total_unique_words)
# Bridge words by exploring single-letter mutations like additions and swaps.
for word_index, current_word in enumerate(unique_word_list):
bitmask_value = 0
for character in current_word:
bitmask_value |= 1 << (ord(character) - ord('a'))
for character_index in range(len(current_word)):
reduced_mask = bitmask_value ^ (1 << (ord(current_word[character_index]) - ord('a')))
if reduced_mask in fingerprint_to_index:
union_find_structure.union_sets(word_index, fingerprint_to_index[reduced_mask])
for alphabet_index in range(26):
if not (bitmask_value & (1 << alphabet_index)):
extended_mask = bitmask_value | (1 << alphabet_index)
if extended_mask in fingerprint_to_index:
union_find_structure.union_sets(word_index, fingerprint_to_index[extended_mask])
replaced_mask = reduced_mask | (1 << alphabet_index)
if replaced_mask in fingerprint_to_index:
union_find_structure.union_sets(word_index, fingerprint_to_index[replaced_mask])
total_communities = 0
maximum_community_size = 0
# Count distinct connected components and find the maximum community size.
for word_index in range(total_unique_words):
if union_find_structure.parent_pointers[word_index] == word_index:
total_communities += 1
maximum_community_size = max(maximum_community_size, union_find_structure.component_sizes[word_index])
return [total_communities, maximum_community_size]| Case | How to Handle |
|---|---|
| Array with a single string of length one | The algorithm must correctly initialize a group of size one and return total groups as one and max size as one. |
| Input contains duplicate strings | Duplicates should be grouped together or treated as identical transitions without inflating the distinct string bitmask set. |
| Strings of maximum allowed length and array size | Bitmask representations using integers must avoid overflow and the graph traversal must remain efficient to pass time limits. |
| Strings that differ by a character replacement forming a valid connection | The bitmask manipulation must check all possible single-bit changes efficiently using bitwise operations. |
| Strings that differ by deletion or addition of a character | The algorithm needs to toggle each existing bit and check if the resulting pattern exists in our set of words. |
| Completely disconnected strings with no valid transformations between any of them | Union-Find or graph connected components will naturally place each unique isolated string into its own group of size one. |
| All strings belong to a single giant connected component | The connected component algorithm must correctly merge all subsets and track the cumulative size as the largest group. |
| Strings containing duplicate characters within the same word | Bitmasking naturally ignores character frequencies, treating repeated characters as a single bit representing presence. |