1002. Find Common Characters #209
-
Topics: Given a string array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem asks us to find the common characters that appear in all the strings of a given array. This includes duplicates, meaning if a character appears twice in all strings, it should appear twice in the output. The result can be in any order. Key Points
ApproachThe main idea is to:
Plan
Let's implement this solution in PHP: 995. Minimum Number of K Consecutive Bit Flips <?php
/**
* @param String[] $words
* @return String[]
*/
function commonChars($words) {
// Initialize a count array for 26 letters with a high number to represent infinity.
$letterCount = array_fill(0, 26, PHP_INT_MAX);
// Loop through each word in the words vector.
foreach ($words as $word) {
// Local count for letters in the current word.
$wordLetterCount = array_fill(0, 26, 0);
// Count each letter in the current word.
foreach (str_split($word) as $letter) {
++$wordLetterCount[ord($letter) - ord('a')];
}
// Compare counts for each letter with the global count and take the minimum.
for ($i = 0; $i < 26; ++$i) {
$letterCount[$i] = min($letterCount[$i], $wordLetterCount[$i]);
}
}
// Prepare the result vector to store common letters.
$result = [];
for ($i = 0; $i < 26; ++$i) {
// Add the appropriate number of the current letter to the result.
while ($letterCount[$i] > 0) {
$result[] = chr($i + ord('a'));
--$letterCount[$i];
}
}
return $result; // Return the final result.
}
// Example 1
$words = ["bella","label","roller"];
echo commonChars($words); // Output: ["e","l","l"]
// Example 2
$words = ["cool","lock","cook"];
echo commonChars($words); // Output: ["c","o"]
?> Explanation:Step-by-Step Breakdown
Example WalkthroughExample 1:Input:
Output: Time Complexity
Overall Complexity: O(N x L). Output for ExampleExample 1:Input: Example 2:Input: This solution efficiently handles the problem within the constraints. It uses the concept of frequency arrays and minimizes space by using constant storage for the alphabet. The logic is simple, and the result respects duplicates. |
Beta Was this translation helpful? Give feedback.
The problem asks us to find the common characters that appear in all the strings of a given array. This includes duplicates, meaning if a character appears twice in all strings, it should appear twice in the output. The result can be in any order.
Key Points
words
with lowercase letters.Approach
The main idea is to: