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 (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".

Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar.

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.

We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?

Input & Output

Example 1 — Basic Grouping
$ Input: strs = ["tars","rats","arts","star"]
Output: 2
💡 Note: "tars" and "rats" are similar (swap positions 0,2). "rats" and "arts" are similar (swap positions 0,1). So {"tars","rats","arts"} form one group. "star" forms its own group. Total: 2 groups.
Example 2 — All Connected
$ Input: strs = ["abc","bac"]
Output: 1
💡 Note: "abc" and "bac" are similar by swapping positions 0 and 1. Both strings form one group.
Example 3 — All Separate
$ Input: strs = ["abc","def","ghi"]
Output: 3
💡 Note: None of the strings are similar to each other (would need more than 2 swaps). Each string forms its own group.

Constraints

  • 1 ≤ strs.length ≤ 300
  • 1 ≤ strs[i].length ≤ 300
  • strs[i] consists of lowercase letters only
  • All the strings of strs are the same length
  • All the strings of strs are anagrams of each other

Visualization

Tap to expand
Similar String Groups ProblemInput Strings"tars""rats""arts""star"Similarity Check2 diffs2 diffsNo connectionsConnected ComponentsGroup 1Group 2tars ↔ rats ↔ artsstar (isolated)Output: 2Number of connected groups
Understanding the Visualization
1
Input Strings
Array of anagram strings that may be similar
2
Find Similarities
Check which pairs can be made equal with ≤2 swaps
3
Group Connected
Count connected components of similar strings
Key Takeaway
🎯 Key Insight: Model similarity as graph edges and count connected components using Union-Find or DFS
Asked in
Google 25 Facebook 18 Amazon 15
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen