#1408
String Matching in an Array
EasyArrayStringString MatchingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + n*m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + n*m)Space O(n)
An optimal approach involves sorting the words by length and then checking each word against only the longer words. This reduces unnecessary comparisons and improves efficiency.
⚙️
Algorithm
5 steps- 1Step 1: Sort the words array by length.
- 2Step 2: Initialize an empty set to store results (to avoid duplicates).
- 3Step 3: Loop through each word and check if it is a substring of any longer word.
- 4Step 4: If a substring is found, add it to the set.
- 5Step 5: Convert the set to a list and return it.
solution.py9 lines
1def stringMatching(words):
2 words.sort(key=len)
3 result = set()
4 for i in range(len(words)):
5 for j in range(i + 1, len(words)):
6 if words[i] in words[j]:
7 result.add(words[i])
8 break
9 return list(result)ℹ
Complexity note: The time complexity is O(n log n) for sorting the words and O(n*m) for checking substrings, where m is the average length of the strings. The space complexity is O(n) due to the storage of results in a set.
- 1Sorting helps reduce unnecessary comparisons.
- 2Using a set avoids duplicates in the result.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.