Hard · Graphs

Similar String Groups

Given a list of equal-length strings that are all anagrams of one another, return the number of groups they form. Two strings are directly linked when they are equal or swapping two letters in one gives the other, and a group is every string connected through a chain of such links.

Examples

Example 1

{
  "strs": ["tars", "rats", "arts", "star"]
}

Output: 2 groups

Example 2

{
  "strs": ["abcd", "abdc", "bacd", "badc", "cdab", "cdab"]
}

Output: 2 groups

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Graphs problems