↓Skip to main content
  1. LeetCode/

LeetCode 1002: Find Common Characters

·1 min· ·
LeetCode Easy Array Hash-Table String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-27

  • Submissions: Runtime Error → Accepted ×3

Approach
#

Each character appears in the answer as many times as its minimum count over all words (Hash Table Template 1). Python’s Counter & Counter takes per-character minimums; intersect over all words and expand with elements().

My Attempts
#

Attempt 1 intersected a set with a string (set & str, TypeError), and a set drops multiplicity anyway: ["bb"] should give two bs. Switching to Counter & passed.

Solution
#

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        common = Counter(words[0])
        for w in words[1:]:
            common &= Counter(w)
        return list(common.elements())

Complexity
#

Time O(total characters), space O(k).

Mistakes to Avoid
#

  • set loses multiplicity: ["bb"] gives ["b", "b"].
  • set & str mixes types and raises TypeError.

Interview Explanation
#

I count each word and intersect the Counters, taking each character’s minimum count, then expand into a list. Time is linear in the total length.

Related

LeetCode 929: Unique Email Addresses
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 929 note: split at @, normalize only the local part (drop everything after +, remove dots), rejoin with the domain and collect in a set
LeetCode 953: Verifying an Alien Dictionary
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 953 note: map letters to their alien index and compare each adjacent pair at the first differing character; with no difference, the shorter must come first
LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned
LeetCode 748: Shortest Completing Word
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 748 note: count the plate’s letters in lowercase, then find the shortest word covering every count, taking the earliest on ties
LeetCode 599: Minimum Index Sum of Two Lists
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 599 note: map list1’s strings to indices, sum both indices while scanning list2, and keep every string with the minimum sum
LeetCode 804: Unique Morse Code Words
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 804 note: translate each word into a Morse string and count the distinct results with a set