leetcodedaybyday - Beats 100% with C++ and Beats 50.44% with Python3
IntuitionThe problem requires us to find pairs of words that have the same unique character set (i.e., ignoring order and duplicate letters).
Since there are on
# Intuition
The problem requires us to find pairs of words that have the **same unique character set** (i.e., ignoring order and duplicate letters).  
Since there are only **26 lowercase English letters**, we can efficiently **represent each word as a bitmask**, where each bit represents the presence of a character.

Instead of comparing words directly, we convert them into bitmasks and **use a hash map** to count similar words.

---

# Approach
1. **Use Bitmasking to Represent Each Word**  
   - Each word is converted into a **26-bit integer mask**, where each bit represents a character.
   - If a character `'a'` appears, set `mask |= 1 << (ord('a') - ord('a'))`.
   - If `'b'` appears, set `mask |= 1 << (ord('b') - ord('a'))`, and so on.

2. **Use a Hash Map (`unordered_map` in C++ / `defaultdict` in Python)**  
   - Store how many times each unique bitmask has appeared.
   - If a bitmask already exists, every occurrence contributes to **valid similar pairs**.

3. **Count Similar Pairs Efficiently**  
   - If a mask has been seen `k` times before, it contributes `k` pairs.
   - After checking, increment the frequency of the mask.

---

# Complexity
- **Time Complexity:**  
  - **O(n * k)** → Where `n` is the number of words and `k` is the average word length (at most `26`).
  - Each word is processed in **O(k) ~ O(1)** using bitwise operations.
  - Hash map operations (`unordered_map` / `defaultdict`) are **O(1)** on average.

- **Space Complexity:**  
  - **O(n)** → The hash map stores bitmask frequencies, at most **2^26** different values, but practically much fewer.

---

# Code
```cpp []
class Solution {
public:
    int similarPairs(vector<string>& words) {
        int ans = 0;
        unordered_map<int, int> freq;
        for (auto& word : words){
            int mask = 0;
            for (auto& c : word)
                mask |= 1 << (c - 'a');
            ans += freq[mask]++;
        }
        return ans;
    }
};


```
```python3 []
class Solution:
    def similarPairs(self, words: List[str]) -> int:
        ans = 0
        freq = defaultdict(int)

        for word in words:
            mask = 0
            for c in word:
                mask |= 1 << ord(c) - ord('a')
            ans += freq[mask]
            freq[mask] += 1

        return ans



```

['Array', 'Hash Table', 'String', 'C++', 'Python3']