JS | Arrays | Find Common Characters | Interview Question

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));

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store