String Matching in an Array - Problem
String Matching in an Array is a fundamental string manipulation problem that tests your ability to identify substring relationships efficiently.
You are given an array of strings called
For example, if you have
The order of the result doesn't matter - you can return the matching strings in any sequence you prefer.
You are given an array of strings called
words. Your task is to find all strings that appear as substrings within other strings in the same array. A substring is a contiguous sequence of characters within a string.For example, if you have
["mass", "as", "hero", "superhero"], both "as" (found in "mass") and "hero" (found in "superhero") should be returned.The order of the result doesn't matter - you can return the matching strings in any sequence you prefer.
Input & Output
example_1.py โ Basic Case
$
Input:
["mass","as","hero","superhero"]
โบ
Output:
["as","hero"]
๐ก Note:
"as" is a substring of "mass", and "hero" is a substring of "superhero"
example_2.py โ Multiple Matches
$
Input:
["leetcode","et","code"]
โบ
Output:
["et","code"]
๐ก Note:
Both "et" and "code" are substrings of "leetcode"
example_3.py โ No Matches
$
Input:
["blue","green","bu"]
โบ
Output:
[]
๐ก Note:
None of the strings is a substring of another string in the array
Visualization
Tap to expand
Understanding the Visualization
1
Gather Evidence
Collect all the word clues in your array
2
Sort by Size
Arrange words from shortest to longest - smaller clues are more likely to be hidden
3
Search for Hidden Words
For each small word, check if it's completely contained in any larger word
4
Record Findings
Keep track of all the words that are found as substrings
Key Takeaway
๐ฏ Key Insight: By sorting strings by length first, we can optimize our search by only looking for shorter strings within longer ones, just like a detective focuses on the most promising leads first!
Time & Space Complexity
Time Complexity
O(n log n + nยฒ ร m)
Sorting takes O(n log n), then we have nested comparisons O(nยฒ) with substring search O(m), but in practice much faster due to fewer comparisons
โ Quadratic Growth
Space Complexity
O(k)
Space for result array where k is number of strings that are substrings
โ Linear Space
Constraints
- 1 โค words.length โค 100
- 1 โค words[i].length โค 30
- words[i] contains only lowercase English letters
- All strings in words are unique
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code