Count Pairs Of Similar Strings Problem
#2506
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2506.
You are given a 0-indexed string array words.
Two strings are similar if they consist of the same characters.
- For example,
"abca"and"cba"are similar since both consist of characters'a','b', and'c'. - However,
"abacba"and"bcfd"are not similar since they do not consist of the same characters.
Return the number of pairs (i, j) such that 0 <= i < j <= word.length - 1 and the two strings words[i] and words[j] are similar.
Example 1:
Input: words = ["aba","aabb","abcd","bac","aabc"]
Output: 2
Explanation: There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words[3] and words[4] only consist of characters 'a', 'b', and 'c'.
Example 2:
Input: words = ["aabb","ab","ba"]
Output: 3
Explanation: There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words[0] and words[2] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words[1] and words[2] only consist of characters 'a' and 'b'.
Example 3:
Input: words = ["nba","cba","dba"]
Output: 0
Explanation: Since there does not exist any pair that satisfies the conditions, we return 0.
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]consist of only lowercase English letters.
Solution
Approach: Bitmask + Hash Map
Two strings are similar exactly when they use the same set of letters. Turn each word into a 26-bit mask (one bit per letter), so similar words get the same mask.
Scan the words and keep a hash map from mask to the number of earlier words with that mask. For each word, add the map's count for its mask to the answer, then increment that count.
Complexity: O(L) time, where L is the total length of all words, and O(n) space.
class Solution:
def similarPairs(self, words: List[str]) -> int:
ans = 0
cnt = Counter()
for s in words:
x = 0
for c in map(ord, s):
x |= 1 << (c - ord("a"))
ans += cnt[x]
cnt[x] += 1
return ans