|
| 1 | +# [1002. Find Common Characters](https://leetcode.com/problems/find-common-characters/description) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +title: "Finding Common Characters in Strings" |
| 6 | +summary: "A solution to find common characters in multiple strings using a straightforward approach and JavaScript." |
| 7 | +date: 2024-06-05 |
| 8 | +modifiedDate: 2024-06-05 |
| 9 | +tags: ["JavaScript", "Algorithms", "Coding"] |
| 10 | +slug: "finding-common-characters-in-strings" |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +# Intuition |
| 17 | + |
| 18 | +The problem requires finding characters that appear in all given strings. My initial thought was to use a simple approach that iterates over the characters of the first string and checks if each character is present in all other strings. If a character is found in every string, it can be added to the result array. |
| 19 | + |
| 20 | +# Approach |
| 21 | + |
| 22 | +1. Iterate over each character of the first string. |
| 23 | +2. For each character, check if it is present in all other strings. |
| 24 | +3. If a character is found in every string, add it to the result array and remove it from each string to avoid duplicate counting. |
| 25 | +4. Return the result array containing common characters. |
| 26 | + |
| 27 | +# Complexity |
| 28 | + |
| 29 | +- Time complexity: $$O(n \cdot m^2)$$, where $$n$$ is the number of strings and $$m$$ is the average length of the strings. This is because for each character in the first string, we need to check its presence in all other strings, and string operations such as `includes` and `replace` have a linear complexity. |
| 30 | + |
| 31 | +- Space complexity: $$O(n)$$, where $$n$$ is the length of the result array storing common characters. Additional space is used for intermediate string modifications. |
| 32 | + |
| 33 | +# Code |
| 34 | + |
| 35 | +```js |
| 36 | +/** |
| 37 | + * @param {string[]} words |
| 38 | + * @return {string[]} |
| 39 | + */ |
| 40 | +function commonChars(words) { |
| 41 | + let arr = []; |
| 42 | + |
| 43 | + words[0].split("").forEach((item, index) => { |
| 44 | + if (words.every((word) => word.includes(item))) { |
| 45 | + arr.push(item); |
| 46 | + words = words.map((word) => word.replace(item, "")); |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + return arr; |
| 51 | +} |
| 52 | +``` |
0 commit comments