EasyNo. 1002

Find Common Characters — LeetCode 1002 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
Reading time
2 min

The problem

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

Input
words = ["bella","label","roller"]
Output
["e","l","l"]

Python solution

PythonSolution
class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        cnt = Counter(words[0])
        for w in words:
            t = Counter(w)
            for c in cnt:
                cnt[c] = min(cnt[c], t[c])
        return list(cnt.elements())

Complexity

Time
O(n Σ w_i)
Space · auxiliary
O(|Σ|)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1002. Find Common Characters is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy
0522Longest Uncommon Subsequence IIMedium

Frequently asked questions

How hard is LeetCode 1002. Find Common Characters?

LeetCode 1002. Find Common Characters is rated Easy on LeetCode.

What is the time complexity of LeetCode 1002. Find Common Characters?

The Python solution on this page runs in O(n Σ w_i).

What is the space complexity of LeetCode 1002. Find Common Characters?

The Python solution on this page uses O(|Σ|) auxiliary space.

What topics does LeetCode 1002. Find Common Characters cover?

LeetCode 1002. Find Common Characters is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.