Find Common Characters - Problem
Find Common Characters
Given an array of strings
Goal: Return an array containing all characters that show up in all strings within the words array (including duplicates).
Example: If you have
You may return the answer in any order.
Given an array of strings
words, your task is to find all characters that appear in every single string. The catch? You need to include duplicates! If a character appears twice in every string, it should appear twice in your result.Goal: Return an array containing all characters that show up in all strings within the words array (including duplicates).
Example: If you have
["bella", "label", "roller"], the characters that appear in all three strings are ['e', 'l', 'l']. Notice how 'l' appears twice because it appears at least twice in each string.You may return the answer in any order.
Input & Output
example_1.py โ Basic case with common characters
$
Input:
["bella", "label", "roller"]
โบ
Output:
["e", "l", "l"]
๐ก Note:
'e' appears once in all words. 'l' appears at least twice in all words, so we include it twice. 'b' and 'a' don't appear in 'roller', and 'r', 'o' don't appear in other words.
example_2.py โ No common characters
$
Input:
["abc", "def", "ghi"]
โบ
Output:
[]
๐ก Note:
No character appears in all three words, so the result is an empty array.
example_3.py โ Single word case
$
Input:
["hello"]
โบ
Output:
["h", "e", "l", "l", "o"]
๐ก Note:
With only one word, all characters in that word are 'common' to all words in the array. The 'l' appears twice, so it's included twice in the result.
Visualization
Tap to expand
Understanding the Visualization
1
Start with first recipe
bella: b(1), e(1), l(2), a(1) - this gives us our initial 'shopping list'
2
Check second recipe
label: l(2), a(1), b(1), e(1) - all ingredients still available, quantities unchanged
3
Check third recipe
roller: r(2), o(1), l(2), e(1) - b and a are missing! Update our list
4
Final shopping list
Only e(1) and l(2) survived all recipes - these are our common characters
Key Takeaway
๐ฏ Key Insight: The frequency of any common character is limited by the word that contains the fewest occurrences of that character. Using a hash table to track minimum counts across all words gives us an optimal O(nรm) solution.
Time & Space Complexity
Time Complexity
O(n ร m)
n words each with m characters, but we process optimally in one pass
โ Linear Growth
Space Complexity
O(k)
Only one frequency map storing k unique characters from first word
โ Linear Space
Constraints
- 1 โค words.length โค 100
- 1 โค words[i].length โค 100
- words[i] consists of lowercase English letters only
- Important: Duplicates matter - if a character appears multiple times in every word, include it multiple times in the result
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code