1002. Find Common Characters - Explanation

Problem Link



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

  1. Initialize a frequency array cnt of size 26 (for lowercase letters) with large values (or use the first word's counts).
  2. For each word, count character frequencies in curCnt.
  3. For each character, update cnt[c] = min(cnt[c], curCnt[c]).
  4. Build the result by adding each character cnt[c] times.
  5. Return the result list.
class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        cnt = Counter(words[0])

        for w in words:
            cur_cnt = Counter(w)
            for c in cnt:
                cnt[c] = min(cnt[c], cur_cnt[c])

        res = []
        for c in cnt:
            for i in range(cnt[c]):
                res.append(c)

        return res

Time & Space Complexity

  • Time complexity: O(nm)O(n * m)
  • Space complexity:
    • O(1)O(1) extra space, since we have at most 2626 different characters.
    • O(nm)O(n * m) space for the output list.

Where nn is the number of words and mm 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.