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 in an Array INPUT words array: "mass" "as" "hero" "superhero" len:4 len:2 len:4 len:9 Sorted by length: ["as","mass","hero","superhero"] (2, 4, 4, 9 chars) ALGORITHM STEPS 1 Sort by Length Shorter strings first 2 For each word Check longer words only 3 Check substring Use contains/find method 4 Add to result If match found Matching Process: "as" in "mass" ---> OK "hero" in "superhero" ---> OK "mass" in others ---> NO Time: O(n^2 * m) | Space: O(n) FINAL RESULT Substrings found: "as" "hero" Why these? "as" is substring of "mass" "hero" is substring of "superhero" Output: ["as", "hero"] Key Insight: Sorting by length first allows us to only check if shorter strings are substrings of longer ones. This optimization avoids redundant comparisons since a longer string cannot be a substring of a shorter one. A substring must be smaller than or equal to the containing string in length. TutorialsPoint - String Matching in an Array | Optimized: Sort by Length First
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