JS | Arrays | Find Common Characters | Interview Question
1 min readSep 1, 2022
--
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));
- Follow me for more coding interviews.
- This problem is very popular in coding interviews.
- Keep learning, keep growing!
- Don’t forget to follow me for more such articles, and subscribe to our newsletter.
- Let’s connect on LinkedIn!. Please read more for more data structure javascript questions.