DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

2 1

Find Common Characters

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 1:

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

Example 2:

Input: words = ["cool","lock","cook"]
Output: ["c","o"]

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters.

SOLUTION:

from collections import Counter

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        common = set.intersection(*[set(w) for w in words])
        ctrs = [Counter(w) for w in words]
        ans = []
        for c in common:
            ans += [c] * min([ctr[c] for ctr in ctrs])
        return ans
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay