Ctrl K

One-Swap Word Families

Hard
Call two words **similar** if they are equal, or one can be turned into the other by swapping two letters at different positions. You are given a list words where every word has the same length and uses the same multiset of letters (each word is a rearrangement of any other). The words fall into **families**: two words share a family if you can get from one to the other through a chain of words from the list in which every neighboring pair is similar. For example, "abcd" and "badc" are not similar, but they end up in one family if the list also contains "bacd". Return the number of families.
Example 1
words=['stone', 'tones', 'notes', 'onset', 'tonse'] → 3

"tones" is similar to "notes" (swap t and n) and to "tonse" (swap e and s), so these three words form one family. "stone" and "onset" are similar to nothing else in the list, giving two more families. That makes 3.

Example 2
words=['abcd', 'bacd', 'badc', 'cdab'] → 2

"abcd" → "bacd" → "badc" are linked by a chain of swaps, even though "abcd" and "badc" are not directly similar. "cdab" differs from each of them in all four positions. The answer is 2.

Example 3
words=['xy', 'xy'] → 1

Identical words count as similar, so there is one family.

Constraints
  • 1 ≤ len(words) ≤ 300
  • 1 ≤ len(words[i]) ≤ 300
  • words[i] consists of lowercase English letters
  • All words have the same length and are rearrangements of one another
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMerge Contact Cards MediumChains of Synonyms MediumRearrange Through Links MediumWhich Machine to Cure HardWhich Machine to Unplug Hard
loading Python…
Input
words=['stone', 'tones', 'notes', 'onset', 'tonse']
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 30 tests on the server, hidden ones included.