String Matching in an Array Problem
Description
LeetCode Problem 1408.
Given an array of string words, return all strings in words that are a substring of another word. You can return the answer in any order.
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 <= 1001 <= words[i].length <= 30words[i]contains only lowercase English letters.- All the strings of
wordsare unique.
Solution
Approach: Check Every Pair
The input is small (at most 100 words of at most 30 letters), so we can simply test, for every word, whether it appears inside some other word.
For each word words[i], look at every words[j] with j != i. If words[i] is a substring of words[j], add words[i] to the answer and stop looking, so a word that fits into several others is still added once.
Skipping j == i is what keeps every word from matching itself. Since the words are unique, no other word can be equal to words[i], so a match with another index really is a longer word that contains it.
Complexity: O(n2 · L2) time in the worst case for n words of length at most L (each substring test is O(L2) with the naive search), and O(n) space for the answer.
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
ans = []
for i, w in enumerate(words):
# words are unique, so only another index can contain w
if any(i != j and w in other for j, other in enumerate(words)):
ans.append(w)
return ans