You are given an array of strings strs. All strings are anagrams of each other.
Two strings are considered similar if they are identical, or if you can make them equal by swapping exactly two characters in one of the strings.
Similarity is transitive: if string a is similar to b, and b is similar to c, then all three belong to the same group.
Return the number of groups of similar strings.
Examples
01 · Example 1
strs = ["tars", "rats", "arts", "star"] return = 2
"tars" is similar to "rats", and "rats" is similar to "arts", so they form one group. "star" forms another group.
02 · Example 2
strs = ["omv", "ovm"] return = 1
The two strings differ in exactly two positions, so one swap makes them equal.
Constraints
- All strings in
strsare anagrams of each other. - All strings have the same length.
More Amazon problems
- Count Promotional PeriodsOA · Seen Jun 2026
- Find Maximum Total Amount (SDE I, Fungible :)Seen Jun 2026
- Get Minimum AmountOA · Seen Jun 2026
- Find Minimum CostOA · Seen Jun 2026
- Get Smallest Base SegmentOA · Seen Jun 2026
- Maximum Non-Adjacent House ValueONSITE INTERVIEW · Seen Jun 2026
- Running Delivery Time MediansONSITE INTERVIEW · Seen Jun 2026
- Select Least Resource TasksOA · Seen Jun 2026
public int countSimilarStringGroups(String[] strs) {
// write your code here
}strs["tars", "rats", "arts", "star"]
expected2
sign in to submit