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:
|
|
Example 2:
|
|
Example 3:
|
|
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
|
|
|
|
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.