DSA Pattern — Finding Common Characters From Words (with Frequency Map Strategy)
Today I solved LeetCode 1002: Find Common Characters — and honestly, it was trickier than it looked. 😅
This problem is marked Easy, but only makes sense once you realize how to use frequency maps across multiple strings.
Let me break it down cleanly so you can reuse the pattern in similar problems.
🔍 Problem Summary
Given an array of strings like:
$words = ["bella", "label", "roller"];
You need to return all characters that appear in every word, including duplicates.
So the answer should be:
["e", "l", "l"]
💡 Key Strategy
The idea is to:
- Count how many times each character appears in each word.
- Only keep the minimum count for each character across all words.
- Rebuild the result based on that minimum count.
🧪 Pseudocode
Initialize freq map from the first word
For each of the remaining words:
Create a currentFreq map of character counts
For each char in freq:
If char exists in currentFreq:
Update freq[char] = min(freq[char], currentFreq[char])
Else:
Remove char from freq (since it doesn’t exist in current word)
Initialize result list
For each char in freq:
Add char to result freq[char] times
Return result
🧑💻 PHP Code
function commonChars($words) {
// Step 1: Get initial frequency map from first word
$freq = array_count_values(str_split($words[0]));
// Step 2: Compare with the rest of the words
for ($i = 1; $i < count($words); $i++) {
$currentFreq = array_count_values(str_split($words[$i]));
foreach ($freq as $char => $count) {
if (isset($currentFreq[$char])) {
$freq[$char] = min($count, $currentFreq[$char]);
} else {
unset($freq[$char]);
}
}
}
// Step 3: Build final result based on freq
$result = [];
foreach ($freq as $char => $count) {
for ($i = 0; $i < $count; $i++) {
$result[] = $char;
}
}
return $result;
}
📊 Time & Space Complexity
Time Complexity: O(N * K)
- N = number of words
- K = average length of each word
- Because we loop through all words and compare frequencies per character.
Space Complexity: O(1)
- We use constant space (at most 26 characters – a-z) for frequency maps.
🔁 Reusable Pattern
This pattern is reusable for:
- Intersection of character arrays
- Finding minimum character frequencies across strings
- Problems with “common across all” conditions
✅ This is now part of my core DSA templates. Hope it helps you too.
Let me know if you solved it differently!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.