Taro Logo

Groups of Strings

Hard
Asked by:
Profile picture
4 views
Topics:
ArraysStringsBit ManipulationGraphs

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:

  • Adding exactly one letter to the set of the letters of s1.
  • Deleting exactly one letter from the set of the letters of s1.
  • Replacing exactly one letter from the set of the letters of 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:

  • It is connected to at least one other string of the group.
  • It is the only string present in the group.

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, and
  • ans[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 * 104
  • 1 <= words[i].length <= 26
  • words[i] consists of lowercase English letters only.
  • No letter occurs more than once in words[i].

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 are the constraints on the length of the `words` array and the maximum length of an individual string?
  2. How should identical strings in the input array be handled—do they belong to the same group and count towards the group size?
  3. Can a single-letter change include replacing a character with the exact same character (i.e., a no-op), or must it be a distinct character?
  4. If a string can be transformed into multiple other strings through allowed operations, does that transitively connect all of them into a single group?
  5. What should be returned if the `words` array is empty?

Brute Force Solution

Approach

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:

  1. Start by taking the first word in your collection.
  2. Compare this word against every other word in the collection one by one.
  3. For each comparison, check if you can transform the first word into the second by performing one allowed change, like adding or deleting a letter.
  4. If a direct connection is found, note that these two words belong to the same group.
  5. Repeat this exhaustive checking process for every single word against all other words so that no potential connection is missed.
  6. Once all pairs have been checked, connect words that belong to the same chain of relationships into larger groups.
  7. Finally, count the total number of groups you formed and figure out the size of the largest group.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(n^2 * k) – The brute force approach requires comparing each of the n words against every other word in the collection to check for valid single-letter transformations. For each of the n words, we perform roughly n comparisons, and each comparison involves evaluating words of average length k. This leads to approximately n * n / 2 string comparisons scaled by length k, which simplifies to the final Big O time complexity.
Space Complexity
O(N) – To determine the groups and their connections, we utilize a Disjoint Set Union or hash map structure along with a visited set to track relationships among the N words. In the worst-case scenario where every word belongs to the same chain or distinct groups, these auxiliary data structures store up to N elements and string representations. As the total number of words N increases, the memory consumed by these tracking structures scales proportionally. Thus, the overall auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

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:

  1. Examine every single word on the list and convert it into a unique digital fingerprint based on the exact letters it contains, ignoring order.
  2. Group together all the words that share the exact same fingerprint because they are already identical in letter composition.
  3. Next, figure out how to bridge words that are just one small tweak apart, such as adding a missing letter or swapping one character for another.
  4. Check every possible single-letter mutation for each word's fingerprint and see if another known word fingerprint matches it.
  5. Think of this as building a vast web of connections where each word is a point and valid single-step transformations are roads connecting them.
  6. Count how many distinct communities or islands of connected words exist within this web.
  7. Finally, find the size of the absolute largest community so you know the maximum number of words you can bring together through these allowed transformations.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(n * L^2) – Let n be the number of words and L be the maximum length of a word. For each of the n words, we generate its fingerprint and check all possible single-character mutations, which involves 26 * L variations for each of the L character positions. Since L is typically a small constant (like up to 26 for English alphabet sizes), the total operations scale linearly with n times a squared factor of the word length, simplifying to O(n * L^2).
Space Complexity
O(N * 26 + N * L) – To analyze the auxiliary space, let N be the number of words in the input list and L be the maximum length of a word. The algorithm uses a hash map to store unique digital fingerprints and their corresponding word groups, where each fingerprint represents bitmasks or character sets of size up to 26. Additionally, we store the mutated variations of these fingerprints to bridge connections between words, consuming memory proportional to the number of words and their possible single-letter alterations. As the input size N grows, these hash maps and lookup sets scale linearly with N, leading to an overall auxiliary space complexity of O(N * 26 + N * L).

Edge Cases

Array with a single string of length one
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The bitmask manipulation must check all possible single-bit changes efficiently using bitwise operations.
Strings that differ by deletion or addition of a character
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Bitmasking naturally ignores character frequencies, treating repeated characters as a single bit representing presence.