You are given an array words
of strings. A move consists of choosing any two even indexed characters of a string and swapping them, or choosing any two odd indexed characters of a string and swapping them.
Two strings are special-equivalent if after any number of moves, they are equal. For example, “abcde” and “adcbe” are special-equivalent because we can swap the ‘b’ and ‘d’ which are both at odd indices to make the strings equal.
Return the number of groups of special-equivalent strings from the input array words
.
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all special-equivalent.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"].
words[i]
have the same length.words[i]
consist of only lowercase English letters.def numSpecialEquivGroups(words):
def normalize(word):
even_chars = sorted(word[0::2])
odd_chars = sorted(word[1::2])
return (tuple(even_chars), tuple(odd_chars))
normalized_set = set(normalize(word) for word in words)
return len(normalized_set)
# Example Usage
words = ["abcd", "cdab", "cbad", "xyzz", "zzxy", "zzyx"]
print(numSpecialEquivGroups(words)) # Output: 3
Let’s analyze the time complexity:
n
is the length of the word.m
is the number of words and n
is the length of each word.m
tuples in the set, each containing up to n
characters, which is O(m * n).Thus, the final time complexity is O(m * n log n) and the space complexity is O(m * n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?