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 StringsInput: String Array"aba""aab""abc""cba"Process: Group by Character SetsGroup 1: {a, b}"aba", "aab"Group 2: {a, b, c}"abc", "cba"Output: Count Pairs2 strings → 1 pair2 strings → 1 pairTotal: 1 + 1 = 2
Understanding the Visualization
1
Input
Array of strings with different character combinations
2
Process
Group strings by their unique character sets
3
Output
Count total pairs within all groups
Key Takeaway
🎯 Key Insight: Similar strings have identical character sets - use bit masks or string signatures to group efficiently
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