String Matching in an Array (LeetCode 1408): Solution and Explanation
Return each word that occurs as a contiguous piece of some other word in the list. With at most 100 short words, checking every pair is fast enough.
Intuition
A word belongs in the answer as soon as one other word contains it. So for each word, the only question is whether some other word has it as a substring.
The input is tiny: 100 words of at most 30 letters gives under 10,000 pairs, and each substring test touches at most a few hundred characters. A direct pairwise check is the clean solution.
Once a word is found inside another, stop searching for it. That keeps it from being added twice when several words contain it.
Approach: Pairwise substring check
- Start with an empty result.
- For each word w at index i, loop over every index j other than i.
- If words[j] contains w, append w to the result and break out of the inner loop.
- Return the result after every word has been checked.
Step-by-step example
words = ["mass","as","hero","superhero"]
- "mass": no other word contains it (the others are shorter or different), so skip it.
- "as": it appears in "mass" at index 2, so add "as".
- "hero": not in "mass" or "as", but it appears in "superhero" at index 5, so add "hero".
- "superhero": it is the longest word, so nothing contains it.
- Return ["as","hero"].
Code: Python, Java, C++
1class Solution:
2 def stringMatching(self, words: List[str]) -> List[str]:
3 result = []
4 for i, w in enumerate(words):
5 for j, other in enumerate(words):
6 if i != j and w in other:
7 result.append(w)
8 break
9 return result1class Solution {
2 public List<String> stringMatching(String[] words) {
3 List<String> result = new ArrayList<>();
4 for (int i = 0; i < words.length; i++) {
5 for (int j = 0; j < words.length; j++) {
6 if (i != j && words[j].contains(words[i])) {
7 result.add(words[i]);
8 break;
9 }
10 }
11 }
12 return result;
13 }
14}1class Solution {
2public:
3 vector<string> stringMatching(vector<string>& words) {
4 vector<string> result;
5 for (int i = 0; i < (int)words.size(); i++) {
6 for (int j = 0; j < (int)words.size(); j++) {
7 if (i != j && words[j].find(words[i]) != string::npos) {
8 result.push_back(words[i]);
9 break;
10 }
11 }
12 }
13 return result;
14 }
15};Time and space complexity
O(n^2 * L^2)
n^2 ordered pairs, each with a substring search that costs up to O(L^2) done naively (O(L) with KMP). With n <= 100 and L <= 30 this is tiny.
O(1)
Apart from the output list, only loop indices are stored.
Other approaches
Sort by length (time O(n log n + n^2 * L^2), space O(n))
Sort words by length; a word can only be contained in a longer one, so for each word check only the words after it. This halves the comparisons but changes nothing asymptotically.
Joined string (time O(n * n L), space O(n L))
Join all words with a separator into one string and count occurrences of each word in it. A word that occurs at least twice (once for itself) is inside another word.
Suffix trie (time O(n * L^2), space O(n * L^2))
Insert every suffix of every word into a trie with a count of distinct words passing through each node. A word whose path has a count above one occurs inside another word.
Common mistakes
- Comparing a word with itself: every word contains itself, so skip j == i.
- Adding a word once for every word that contains it. Break after the first match.
- Testing the containment the wrong way round (asking whether w contains words[j]).
Frequently asked questions
Does the order of the answer matter?
No. Any order is accepted, so the natural input order from the double loop is fine.
Why is the brute force acceptable?
At most 100 words of length 30 means fewer than 10,000 pairs, each a cheap substring search. That finishes in well under a millisecond.
Can duplicates appear in the output?
Not with the break: each word is added at most once, and the input words are distinct.