The task is taken from leetcode
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter
My imperative solution:
function commonChars(A) { const [first, ...rest] = A.sort((a,b) => -(a.length - b.length)); const duplicates = []; [...first].forEach(e => { let isDuplicate = true; for (let x = 0, len = rest.length; x < len; x++) { let letters = rest[x]; const i = letters.search(e); if (i !== -1) { letters = letters.slice(0, i) + letters.slice(i + 1); rest[x] = letters; } else { isDuplicate = false; } } if (isDuplicate) { duplicates.push(e); } }); return duplicates; } const arr = ["cool","lock","cook"]; console.log(commonChars(arr));
My declarative solution
const commonChars2 = A => { const [first, ...rest] = A.sort((a,b) => b.length - a.length)); return [...first].reduce((duplicates, e) => { let isDuplicate = true; for (let x = 0, len = rest.length; x < len; x++) { const letters = rest[x]; const i = letters.search(e); if (i !== -1) { rest[x] = letters.slice(0, i) + letters.slice(i + 1); } else { isDuplicate = false; } } if (isDuplicate) { duplicates.push(e); } return duplicates; }, []); }; const arr = ["cool","lock","cook"]; console.log(commonChars2(arr));
Is there also a good functional approach?