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 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
๐Ÿ•ต๏ธ String Matching Detective Work"as"Looking for clues...Word Evidence Bank"mass""as""hero""superhero"โœ“ "as" found in "mass"โœ“ "hero" found in "superhero"MATCH!MATCH!๐ŸŽฏ Detective's ReportFound Suspects: ["as", "hero"]Case Status: SOLVED โœ“
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

n
2n
โš  Quadratic Growth
Space Complexity
O(k)

Space for result array where k is number of strings that are substrings

n
2n
โœ“ 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
Asked in
Amazon 35 Microsoft 28 Google 22 Meta 15
28.6K Views
Medium Frequency
~12 min Avg. Time
956 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen