Finding a Common Character

Setu Potnis
1 min readJun 3, 2020

--

Day 44

Hey guys, I hope your Tuesday was amazing! For today’s algorithm problem, I’m going to create a function that can detect what the common characters are in an array of strings. Here’s an example:

Input: ["bella","label","roller"]
Output: ["e","l","l"]
Input: ["cool","lock","cook"]
Output: ["c","o"]

I started off by iterating through the array and making a copy of the original array’s first element. The consequent iterations would compare each entry to the other entries by using a .filter() built-in method. I filter the new array and return the array once it goes past a certain length, the length of the original array. Here’s how it looks in code:

var commonChars = function(A) {
let res = [...A[0]];
for (let i = 1; i < A.length; i++) {
res = res.filter(c => {
const l = A[i].length;
A[i] = A[i].replace(c, "");
return l > A[i].length;
});
console.log(res);
}
return res;
};

Anyways, if you guys learned something interesting or think the solution is pretty cool, click the clap button! If you have any better ways to solve it, feel free to leave a reply or contact me, thanks!

--

--

Setu Potnis

An IBM Software Engineer passionate about crafting exceptional digital experiences for users