Find Common Characters LeetCode solution in Python

1
# Runtime: 87 ms (Top 42.12%) | Memory: 14.3 MB (Top 6.17%)
2
class Solution:
3
def _get_char_counts(self, s: str) -> dict[str]:
4
"""builds a dict of letters : count"""
5
d = {}
6
for i in s:
7
d[i] = d.get(i, 0) + 1
8
return d
9

10
def commonChars(self, words: list[str]) -> list[str]:
11
"""returns a string of letters common between a list of words (including duplicates)"""
12
if not words:
13
return
14

15
# O(n^2)
16
words = [self._get_char_counts(word) for word in words]
17

18
# O(nm), set intersection
19
common = words[0].keys()
20
for other in words[1:]:
21
common &= other.keys()
22

23
# O(nm), number of common characters across the number of words
24
result = []
25
for c in common:
26
result += [c] * min(count[c] for count in words)
27

28
return result

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0