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.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of lowercase English letters.
Solution
Method 1 - Find min number of characters in all words
Here is the approach we can follow:
- Create
commonCharCnt
as common character frequency map, which is an int array of 26 characters, as we have to take care of only lower case alphabets. - Now, for each word we calculate the frequency map for it say in
currCharCnt
array - Update
commonCharCnt
such thatcommonCharCnt[i] = currCharCnt[i]
- Now, we return all the characters from
commonCharCnt
where frequency of character is not 0.
Here is the video explanation:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
(2O(26)
count arrays for common and current word.)