0% completed
Problem Statement
Two strings, X
and Y
, are considered similar if they are identical or can be made identical by swapping at most two distinct positions.
For example, "abcd"
and "bacd"
are similar (swapping at positions 0 and 1), "abcd"
and "acbd"
are also similar, but "dabc"
is not similar to "abcd"
, "bacd"
, and "acbd"
.
Together, these form two connected groups by similarity: {"abcd"
, "bacd"
, "acbd"
} and {"dabc"
}. Notice that "bacd"
and "acbd"
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.
Given a list of strings, where each string is an anagram of every other string in the list, find the total number of groups of strings.
Examples
Example 1
- Input: strs =
["rstuv", "uvrst", "rsutv", "urvst", "vutsr"]
- Expected Output:
3
- Justification: The groups are
["rstuv", "rsutv"]
,["uvrst", "urvst"]
and["vutsr"]
. All strings within each group can be made identical by swapping at most two characters.
Example 2
- Input: strs =
["abcd", "acbd", "bacd", "dabc"]
- Expected Output:
2
- Justification: The groups are
["abcd", "acbd", "bacd", ]
and["dabc"]
. "abcd", "acbd", and "bacd" can be made identical by swapping at most two characters. "dabc" form another group.
Example 3
- Input: strs =
["xyz", "xzy", "yxz", "yzx", "zxy", "zyx"]
- Expected Output:
1
- Justification: All strings are belongs to the same group.
Constraints:
- 1 <= strs.length <= 300
- 1 <= strs[i].length <= 300
- strs[i] consists of lowercase letters only.
- All words in strs have the same length and are anagrams of each other.
Try it yourself
Try solving this question here:
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible