Problem
Given an array of string words
, return all strings in words
that is a substring of another word. You can return the answer in any order.
A substring is a contiguous sequence of characters within a string
Examples
Example 1:
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.
Example 2:
Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".
Example 3:
Input: words = ["blue","green","bu"]
Output: []
Explanation: No string of words is substring of another string.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 30
words[i]
contains only lowercase English letters.- All the strings of
words
are unique.
Solution
Method 1 - Naive approach
For each word in the array, we can check if it is a substring of any other word. Here is what we can do:
- Iterate through the list of words.
- For each word, compare it against every other word to check if it is a substring.
- If it is a substring of any other word, add it to the result list.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
Java
class Solution {
public List<String> stringMatching(String[] words) {
List<String> ans = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words.length; j++) {
if (i != j && words[j].contains(words[i])) {
ans.add(words[i]);
break;
}
}
}
return ans;
}
}
Python
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
ans: List[str] = []
for i in range(len(words)):
for j in range(len(words)):
if i != j and words[i] in words[j]:
ans.append(words[i])
break
return ans
Complexity
- ⏰ Time complexity:
O(n^2 * l^2)
wheren
is the number of words andl
is the average length of a word inwords
. Because we run 2 loops to match the words and then contains method takesO(l1*l2)
and assuming average length of words is l, it becomesO(l^2)
. - 🧺 Space complexity:
O(n)
for storing the result list.