1002. Find Common Characters - Explanation

Problem Link



1. Frequency Count

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.