You are given a 0-indexed string array words
.
Two strings are similar if they consist of the same characters.
Return the number of pairs (i, j)
(where 0 <= i < j <= word.length - 1
) such that the two strings words[i]
and words[j]
are similar.
n
times, the number of pairs is n * (n - 1) / 2
.def countPairs(words):
from collections import defaultdict
# Hashmap to store count of each unique character set
count_map = defaultdict(int)
# Populate the hashmap
for word in words:
char_set = ''.join(sorted(set(word))) # Convert to a sorted string for use as key
count_map[char_set] += 1
# Calculate the number of pairs
num_pairs = 0
for count in count_map.values():
if count > 1:
num_pairs += (count * (count - 1)) // 2 # nC2 formula
return num_pairs
Overall, the time complexity can be approximated as (O(n \cdot k \log k)) where:
words = ["aba", "aaba", "baaa", "aaa", "bc"]
print(countPairs(words)) # Output should be 2
Explanation:
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?