Count Pairs Of Similar Strings - Problem

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 < words.length and the two strings words[i] and words[j] are similar.

Input & Output

Example 1 — Basic Case
$ Input: words = ["aba","aab","abc","cba"]
Output: 2
💡 Note: Pairs (0,1) and (2,3) are similar: "aba" and "aab" both have characters {a,b}, while "abc" and "cba" both have characters {a,b,c}
Example 2 — All Different
$ Input: words = ["aab","ab","aa"]
Output: 1
💡 Note: Only pair (0,1) is similar: "aab" and "ab" both have characters {a,b}, while "aa" only has character {a}
Example 3 — All Same
$ Input: words = ["abc","bac","cab"]
Output: 3
💡 Note: All strings have the same character set {a,b,c}, so all 3 pairs (0,1), (0,2), and (1,2) are similar

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • words[i] consists of only lowercase English letters.

Visualization

Tap to expand
Count Pairs Of Similar Strings INPUT words[] array: "aba" "aab" "abc" "cba" i=0 i=1 i=2 i=3 Unique Characters: "aba" → {a,b} "aab" → {a,b} "abc" → {a,b,c} "cba" → {a,b,c} Same set = Similar! Pair 1: {a,b} Pair 2: {a,b,c} ALGORITHM STEPS 1 Convert to Bitmask Each char → bit position 'a'=bit0, 'b'=bit1, 'c'=bit2 2 Build Bitmask OR all char bits together "aba" → 011 (binary) Word Bitmask "aba" 0b011 = 3 "aab" 0b011 = 3 "abc" 0b111 = 7 "cba" 0b111 = 7 3 Count Same Masks Use HashMap to group 4 Calculate Pairs n*(n-1)/2 for each group FINAL RESULT Grouped by Bitmask: Mask = 3 (count: 2) "aba", "aab" Pairs: 2*(2-1)/2 = 1 Mask = 7 (count: 2) "abc", "cba" Pairs: 2*(2-1)/2 = 1 Total Pairs: 1 + 1 = 2 Output: 2 OK - 2 similar pairs found Key Insight: Use bitmask to represent character sets - each bit represents presence of a character. Two strings are similar if they have the same bitmask. Count pairs with formula: n*(n-1)/2 Time: O(n*m) where n=words, m=avg length | Space: O(n) for HashMap TutorialsPoint - Count Pairs Of Similar Strings | Optimal Solution (Bitmask + HashMap)
Asked in
Amazon 15 Microsoft 12 Google 8
25.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen