LeetCode 1002. Find Common Characters Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1002. Find Common Characters

Description

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.

Solutions

Solution 1: Counting

We use an array cnt of length 26 to record the minimum number of times each character appears in all strings. Finally, we traverse the cnt array and add characters with a count greater than 0 to the answer.

The time complexity is O(n ∑ wi), and the space complexity is O(|Σ|). Here, n is the length of the string array words, wi is the length of the i-th string in the array words, and |Σ| is the size of the character set, which is 26 in this problem.

PythonJavaC++GoTypeScript
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())(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !