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 INPUT String Array (strs) "tars" "rats" "arts" "star" Similarity Graph tars rats arts star Connected: tars-rats-arts Isolated: star ALGORITHM STEPS 1 Union-Find Init Each string = own parent 2 Check Similarity Compare all pairs tars vs rats: diff=2 [OK] rats vs arts: diff=2 [OK] star vs tars: diff=4 [NO] 3 Union Similar Merge connected groups union(tars, rats) union(rats, arts) 4 Count Groups Count unique parents Time: O(n^2 * m) | Space: O(n) FINAL RESULT Group 1 (Connected) tars rats arts All similar (diff <= 2) Group 2 (Isolated) star Not similar to others Output 2 Key Insight: Two strings are "similar" if they differ by exactly 0 or 2 positions (one swap). Use Union-Find to group similar strings. Even if A and C aren't directly similar, they're in the same group if A~B and B~C. Count distinct root parents to find number of groups. "star" forms its own group (4 differences from others). TutorialsPoint - Similar String Groups | Union-Find Optimal Approach
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