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

Open every published interview problem, solution, scene, and memory room free, with no account.

More Graphs problems