Similar String Groups

Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters in distinct positions within the string X.

For example, "tars" and "rats" are similar by swapping positions 0 and 2, and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".

Together, these form connected groups by similarity. Notice that two strings can be in the same group even if they are not directly similar, as long as they are connected through other similar strings. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.

You are given a list strs of strings where every string in strs is an anagram of every other string in strs. Return how many similarity groups there are.

Example 1
Inputstrs = ["tars","rats","arts","star"]
Output2
"tars", "rats", and "arts" form one connected similarity group, while "star" forms another.
Example 2
Inputstrs = ["omv","ovm"]
Output1
"omv" and "ovm" are similar because swapping two letters in one string makes it equal to the other.

Constraints

  • 1 <= strs.length <= 300
  • 1 <= strs[i].length <= 300
  • strs[i] consists of lowercase letters only.
  • All words in strs have the same length and are anagrams of each other.

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate