Leetcode Problem 2157. Groups of Strings

2157. Groups of Strings

Leetcode Solutions

Bitmask + Union Find

  1. Initialize a Union Find data structure with the size equal to the number of words.
  2. Create a bitmask for each word and store the mapping from bitmask to index in a hashmap.
  3. For each word, generate all possible connected words by manipulating the bitmask:
    • For adding a letter, set the corresponding bit to 1.
    • For deleting a letter, set the corresponding bit to 0.
    • For replacing a letter, flip the corresponding bit.
  4. If the generated bitmask exists in the hashmap, union the current word with the word represented by the existing bitmask.
  5. After processing all words, iterate through the Union Find to count the number of disjoint sets and find the size of the largest set.
  6. Return the count of disjoint sets and the size of the largest set as the result.
UML Thumbnail

DFS (Depth-First Search) with Bitmask

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...