Skip to content

1002. Find Common Characters

Description

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.

 

Solutions

Solution: Hash Map

  • Time complexity: O(n*word.length)
  • Space complexity: O(1)

 

JavaScript

js
/**
 * @param {string[]} words
 * @return {string[]}
 */
const commonChars = function (words) {
  const BASE_CHAR_CODE = 'a'.charCodeAt(0);
  const result = [];
  const counts = Array.from({length: 26}).fill(Number.MAX_SAFE_INTEGER);

  for (const word of words) {
    const currentCounts = Array.from({length: 26}).fill(0);

    for (const char of word) {
      const index = char.charCodeAt(0) - BASE_CHAR_CODE;

      currentCounts[index] += 1;
    }
    for (let index = 0; index < 26; index++) {
      counts[index] = Math.min(currentCounts[index], counts[index]);
    }
  }
  for (let index = 0; index < 26; index++) {
    const char = String.fromCharCode(BASE_CHAR_CODE + index);
    const count = counts[index];

    result.push(...char.repeat(count));
  }
  return result;
};

Released under the MIT license