1002. Find Common Characters - Explanation
Description
You are given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.
Example 1:
Input: words = ["bella","label","roller"]
Output: ["e","l","l"]Example 2:
Input: words = ["cool","lock","cook"]
Output: ["c","o"]Constraints:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]consists of lowercase English letters.
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Hash Maps / Frequency Counting - Counting character occurrences in strings using arrays or dictionaries
- String Iteration - Processing each character in a string and comparing across multiple strings
- Array Manipulation - Using fixed-size arrays (size 26 for lowercase letters) as frequency counters
1. Frequency Count
Intuition
A character appears in all words only if it exists in every single word. Moreover, if a character appears twice in every word, we can include it twice in our result. The key insight is to track the minimum frequency of each character across all words. We start with the frequency counts from the first word, then for each subsequent word, we reduce each count to the minimum of the current count and that word's count.
Algorithm
- Initialize a frequency array
cntof size26(for lowercase letters) with large values (or use the first word's counts). - For each word, count character frequencies in
curCnt. - For each character, update
cnt[c] = min(cnt[c], curCnt[c]). - Build the result by adding each character
cnt[c]times. - Return the result list.
Time & Space Complexity
- Time complexity:
- Space complexity:
- extra space, since we have at most different characters.
- space for the output list.
Where is the number of words and is the length of the longest word.
Common Pitfalls
Initializing Counts to Zero Instead of Infinity
Starting the global frequency array with zeros causes min(0, curCnt[c]) to always be zero. Initialize with a large value or use the first word's counts as the starting point.
Adding Characters Once Instead of by Frequency
The result must include each common character as many times as it appears in all words. Appending each character only once ignores duplicates that appear in every word.
Sign in to join the discussion