Algorithm
Problem Name: 1002. 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.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public List commonChars(String[] words) {
int[] commonFrequency = new int[26];
Arrays.fill(commonFrequency, Integer.MAX_VALUE);
for (String word : words) {
int[] wordFreq = new int[26];
for (char c : word.toCharArray()) {
wordFreq[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
commonFrequency[i] = Math.min(commonFrequency[i], wordFreq[i]);
}
}
List < String> result = new ArrayList<>();
for (int i = 0; i < 26; i++) {
int count = commonFrequency[i];
while (count-- > 0) {
result.add(String.valueOf((char) (97 + i)));
}
}
return result;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const commonChars = function(A) {
const minArr = minEl(A)
const res = []
for(let i = 0; i < minArr[1]; i++) {
let target = A[minArr[0]][i]
let all = true
for(let j = 0; j < A.length; j++) {
if(j === minArr[0]) continue
if(all === false) continue
let idx
if( (idx = A[j].indexOf(target)) === -1) {
all = false
} else {
A[j] = A[j].slice(0, idx) + A[j].slice(idx + 1)
}
}
if(all) res.push(target)
}
return res
};
function minEl(arr) {
const res = [0, Number.MAX_SAFE_INTEGER] // [idx, len]
for(let i = 0; i < arr.length; i++) {
if(arr[i].length < res[1]> {
res[0] = i
res[1] = arr[i].length
}
}
return res
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
cnt, res = {s: [float('inf'), 0] for s in string.ascii_lowercase}, []
for w in A:
for k, v in collections.Counter(w).items():
cnt[k][0] = min(cnt[k][0], v)
cnt[k][1] += 1
for k in cnt:
if cnt[k][1] == len(A):
res += [k] * cnt[k][0]
return res
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _1002_FindCommonCharacters
{
public IList < string> CommonChars(string[] A)
{
var current = new int[26];
for (int i = 0; i < 26; i++)
current[i] = int.MaxValue;
foreach (var word in A)
{
var temp = new int[26];
foreach (var ch in word)
temp[ch - 'a']++;
for (int i = 0; i < 26; i++)
current[i] = Math.Min(current[i], temp[i]);
}
var result = new List < string>();
for (int i = 0; i < 26; i++)
{
while (current[i]-- > 0)
result.Add(((char)('a' + i)).ToString());
}
return result;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output