#2506

Count Pairs Of Similar Strings

Easy
ArrayHash TableStringBit ManipulationCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k log k)
Space
O(1)
O(n)
💡

Intuition

Time O(n * k log k)Space O(n)

Instead of comparing each pair, we can use a hash map to group words by their unique characters. This allows us to count similar strings efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hash map to store the frequency of each unique character set as a string.
  2. 2Step 2: For each word, convert it into a sorted string of unique characters and update its count in the hash map.
  3. 3Step 3: For each unique character set in the hash map, calculate the number of pairs using the formula count * (count - 1) / 2.
  4. 4Step 4: Sum all the pairs and return the result.
solution.py15 lines
1# Full working Python code
2
3def countSimilarPairs(words):
4    from collections import defaultdict
5    count_map = defaultdict(int)
6    for word in words:
7        unique_chars = ''.join(sorted(set(word)))
8        count_map[unique_chars] += 1
9    count = 0
10    for c in count_map.values():
11        count += c * (c - 1) // 2
12    return count
13
14# Example usage
15print(countSimilarPairs(["aba", "aabb", "abcd", "bac", "aabc"]))  # Output: 2

Complexity note: The time complexity is O(n * k log k) where n is the number of words and k is the average length of the words due to sorting. The space complexity is O(n) for storing the hash map.

  • 1Two strings are similar if they have the same unique characters.
  • 2Using a hash map to group strings by their unique characters can significantly reduce the number of comparisons.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.