""" 1002.1 - Solution 1 - Counter with Min Frequency """
#####################################################################################
# Imports
#####################################################################################
from typing import List
from collections import Counter
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def commonChars(self, words: List[str]) -> List[str]:
"""Find Common Characters Function"""
cnt = Counter(words[0])
for w in words[1:]:
cur_cnt = Counter(w)
for c in cnt:
cnt[c] = min(cnt[c], cur_cnt[c])
res = []
for c in cnt:
for _ in range(cnt[c]):
res.append(c)
return res
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().commonChars(["bella", "label", "roller"]))
# Output: ["e", "l", "l"]
print(Solution().commonChars(["cool", "lock", "cook"]))
# Output: ["c", "o"]
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 1002.2 - Solution 2 - Using reduce and Counter intersection """
#####################################################################################
# Imports
#####################################################################################
from typing import List
from collections import Counter
from functools import reduce
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def commonChars(self, words: List[str]) -> List[str]:
"""Find Common Characters Function"""
common = reduce(lambda a, b: a & b, (Counter(w) for w in words))
return list(common.elements())
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().commonChars(["bella", "label", "roller"]))
# Output: ["e", "l", "l"]
print(Solution().commonChars(["cool", "lock", "cook"]))
# Output: ["c", "o"]
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()