#1002
Find Common Characters
EasyArrayHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can count the occurrences of each character in each string and then find the minimum count across all strings. This way, we ensure we only include characters that appear in all strings, considering duplicates.
⚙️
Algorithm
4 steps- 1Step 1: Create a frequency array for the first string.
- 2Step 2: For each subsequent string, update the frequency array to keep the minimum counts.
- 3Step 3: Construct the result based on the frequency array.
- 4Step 4: Return the result.
solution.py14 lines
1def commonChars(words):
2 freq = [0] * 26
3 for char in words[0]:
4 freq[ord(char) - ord('a')] += 1
5 for word in words[1:]:
6 current_freq = [0] * 26
7 for char in word:
8 current_freq[ord(char) - ord('a')] += 1
9 for i in range(26):
10 freq[i] = min(freq[i], current_freq[i])
11 result = []
12 for i in range(26):
13 result.extend([chr(i + ord('a'))] * freq[i])
14 return resultℹ
Complexity note: The time complexity is O(n) because we process each character in each string a constant number of times. The space complexity is O(n) due to the result storage.
- 1Using frequency counts allows us to efficiently track character occurrences across multiple strings.
- 2Minimizing counts ensures that we only consider characters that appear in all strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.