String Matching in an Array - Problem

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.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
💡 Note: "as" is a substring of "mass" and "hero" is a substring of "superhero". Return ["as","hero"].
Example 2 — No Substrings
$ Input: words = ["leetcode","et","code"]
Output: ["et","code"]
💡 Note: "et" is a substring of "leetcode" and "code" is also a substring of "leetcode".
Example 3 — No Matches
$ Input: words = ["blue","green","red"]
Output: []
💡 Note: None of the words are substrings of another word, so return empty array.

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 30
  • words[i] contains only lowercase English letters.

Visualization

Tap to expand
String Matching Problem OverviewInput: [mass, as, hero, superhero]massasherosuperheroFind substrings: as ⊆ mass, hero ⊆ superheroOutput: Strings that are substrings of othersashero
Understanding the Visualization
1
Input Array
Array of strings to analyze
2
Substring Check
Find which strings are contained in others
3
Output Result
Return array of substring matches
Key Takeaway
🎯 Key Insight: A string can only be a substring of another string if it's shorter or equal in length
Asked in
Google 25 Facebook 20 Amazon 15
28.3K Views
Medium Frequency
~15 min Avg. Time
856 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