Skip to main content

Find Common Characters

Problem statement

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.

My solution

/**
* @param {string[]} A
* @return {string[]}
*/
var commonChars = function(A) {

const results = [];
const ref = A[0];

for (const char of ref) {
let pushToResult = true;
for(let i = 1; i < A.length; i++) {
const curr = A[i];
const indexOf = curr.indexOf(char);
pushToResult = pushToResult & indexOf > -1;
if (indexOf > -1) {
A[i] = curr.substr(0, indexOf) + curr.substr(indexOf + 1)
}
}
if (pushToResult) {
results.push(char);
}
}

return results;
};


/*

b e 2l a



*/