Leetcode 2506. Count Pairs Of Similar Strings
You are given a 0-indexed string array words
. Two strings are similar if they consist of the same characters.
Return the number of pairs (i, j)
such that 0 <= i < j < n
and the two strings words[i]
and words[j]
are similar.
words
array?
Set Representation: Convert each word into a set of characters. If two words have the same sets of characters, they are similar.
Map for Counting Sets: Use a hashmap to count the frequency of each unique set of characters.
Count Pairs: For each unique set, count the pairs using the formula for combinations. Specifically, for a set appearing ( k ) times, the number of ways to pick 2 out of ( k ) is ( \binom{k}{2} = \frac{k (k - 1)}{2} ).
#include <vector>
#include <string>
#include <unordered_map>
#include <set>
using namespace std;
class Solution {
public:
int countPairs(vector<string>& words) {
// Map to store the frequency of each unique set of characters
unordered_map<string, int> charsetCount;
// Helper function to get the sorted string representation of a set of characters
auto getCharSet = [](const string& word) {
set<char> charSet(word.begin(), word.end());
string sortedSet(charSet.begin(), charSet.end());
return sortedSet;
};
// Populate the charsetCount map
for (const string& word : words) {
string charSet = getCharSet(word);
charsetCount[charSet]++;
}
// Calculate the number of similar pairs
int count = 0;
for (const auto& [charSet, freq] : charsetCount) {
if (freq > 1) {
count += (freq * (freq - 1)) / 2; // Combination nC2
}
}
return count;
}
};
This solution efficiently counts pairs of similar strings by leveraging the power of sets and hashmaps to group and count the unique character sets.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?