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
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.words are unique.This approach is straightforward: for each word in the list, check if it is a substring of any other word. We iterate over each pair of words in the array and use string operations to check for substrings.
The solution defines a helper function isSubstring to check if a word is a substring of another using strstr. The main logic iterates over each word, comparing it with every other word and stores indices of valid substrings.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2 * m)
Space Complexity: O(n)
This approach creates all possible substrings of each word and stores them in a set, which is then used to quickly check for substring membership against other words.
This efficient set-based comparison uses direct substring checking. The main difference from the brute force approach is potential pre-processing for sets (not shown due to C limitations), leading to conceptually similar efficiency given current size constraints.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2 * m)
Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Brute Force Comparison | Time Complexity: O(n^2 * m) |
| Efficient Set-based Comparison | Time Complexity: O(n^2 * m) |
9.1 Knuth-Morris-Pratt KMP String Matching Algorithm • Abdul Bari • 1,929,260 views views
Watch 9 more video solutions →Practice String Matching in an Array with our built-in code editor and test cases.
Practice on FleetCode