DEV Community

Cover image for 1002. Find Common Characters
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

1002. Find Common Characters

1002. Find Common Characters

Easy

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.

Solution:

class Solution {

    /**
     * @param String[] $words
     * @return String[]
     */
    function commonChars($words) {
        $letterCount = array_fill(0, 26, PHP_INT_MAX);
        foreach ($words as $word) {
            $wordLetterCount = array_fill(0, 26, 0);
            foreach (str_split($word) as $letter) {
                ++$wordLetterCount[ord($letter) - ord('a')];
            }
            for ($i = 0; $i < 26; ++$i) {
                $letterCount[$i] = min($letterCount[$i], $wordLetterCount[$i]);
            }
        }
        $result = [];
        for ($i = 0; $i < 26; ++$i) {
            while ($letterCount[$i] > 0) {
                $result[] = chr($i + ord('a'));
                --$letterCount[$i];
            }
        }
        return $result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Contact Links

Top comments (0)