#1967
Number of Strings That Appear as Substrings in Word
EasyArrayStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * m) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
Using a set to store patterns allows for efficient membership testing. This reduces the need for repeated substring searches and improves performance.
⚙️
Algorithm
5 steps- 1Step 1: Convert the patterns list into a set to eliminate duplicates.
- 2Step 2: Initialize a count variable to 0.
- 3Step 3: For each pattern in the set, check if it exists in the word using the built-in substring function.
- 4Step 4: If it exists, increment the count.
- 5Step 5: Return the count after checking all patterns.
solution.py7 lines
1def count_patterns(patterns, word):
2 unique_patterns = set(patterns)
3 count = 0
4 for pattern in unique_patterns:
5 if pattern in word:
6 count += 1
7 return countℹ
Complexity note: This complexity is due to the time taken to create a set of unique patterns (O(n)) and the substring search in the word (O(m)).
- 1Using a set can reduce the number of checks needed if there are duplicate patterns.
- 2Built-in substring search functions are optimized and can save time compared to manual checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.