Similar String Groups is a fascinating problem about finding connected components in a graph of strings.

Given an array of strings where each string is an anagram of all others, we need to determine how many groups of similar strings exist.

Two strings are similar if:
• They are identical, OR
• We can make them identical by swapping at most 2 characters in one string

For example: "tars" and "rats" are similar (swap positions 0 and 2). Even if string A isn't directly similar to string C, they can be in the same group if there's a chain of similarity through other strings.

Goal: Count the number of distinct groups where each group contains strings that are connected through similarity relationships.

Input & Output

example_1.py — Basic Case
$ Input: ["tars", "rats", "arts", "star"]
› Output: 2
šŸ’” Note: "tars", "rats", and "arts" form one group (all connected through similarity), while "star" forms its own group since it's not similar to any other string.
example_2.py — All Similar
$ Input: ["abc", "acb", "bac"]
› Output: 1
šŸ’” Note: All strings can be made similar through at most 2 swaps, so they form one large connected group.
example_3.py — All Identical
$ Input: ["abc", "abc", "abc"]
› Output: 1
šŸ’” Note: All strings are identical, so they form one group (identical strings are considered similar).

Constraints

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

Visualization

Tap to expand
String Similarity Graph VisualizationGroup 1tarsratsartsstarGroup 2Legend:Similar strings (≤ 2 different positions)String nodeConnected component (group)Each connected component represents one similarity group
Understanding the Visualization
1
Model as Graph
Each string is a node, similarity creates edges
2
Check Similarities
Compare each pair to find all possible connections
3
Group Components
Use Union-Find to efficiently merge connected groups
4
Count Groups
Number of distinct roots equals number of groups
Key Takeaway
šŸŽÆ Key Insight: Model strings as graph nodes with similarity as edges, then count connected components using Union-Find for optimal efficiency.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
52.0K Views
Medium Frequency
~25 min Avg. Time
1.5K 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