JS | Arrays | Find Common Characters | Interview Question

--

Super East Solution

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.

Input: words = ["bella","label","roller"]
Output: ["e","l","l"]
- Get intersection of string with duplicates. At a minimum all characters must share a min frequency.

Solution, O(n)

const findCommonCharacters = (str1, str2) => {
let commonChars= "";
const obj1 = {};
for (let key of str1) {
if (obj1[key]) {
obj1[key] = obj1[key] + 1
} else {
obj1[key] = 1
}
}

for (let key of str2) {
if (obj1[key] > 0) {
commonChars = commonChars + key;
}
}
return commonChars
}
const getCommonCharacters = (words) => {
if(words.length === 0) return [];
let commonCharacters = words[0];


for (let i = 1; i < words.length; i++) {
if (commonCharacters !== words[i]) {
commonCharacters = findCommonCharacters(words[i], commonCharacters)
}
}

return commonCharacters;
}
const words = ["bella","label","roller"];
console.log(getCommonCharacters(words));

--

--

Sonika | @Walmart | Senior Developer | 10 Year+Exp

Working in Walmart as Senior IV Engineer | React | JavaScript | Data Structure