Skip to content

Commit 86816e4

Browse files
easy: 1002. Find Common Characters
1 parent 006735e commit 86816e4

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @param {string[]} words
3+
* @return {string[]}
4+
*/
5+
function commonChars(words) {
6+
let arr = [];
7+
8+
words[0].split('').forEach((item, index) => {
9+
if (words.every(word => word.includes(item))) {
10+
arr.push(item);
11+
words = words.map(word => word.replace(item, ''));
12+
}
13+
});
14+
15+
return arr;
16+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
![image.png](https://assets.leetcode.com/users/images/a495130a-37f7-405d-b2bb-821bab29b1b5_1717595176.503326.png)
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

Comments
 (0)