Skip to main content

String Matching in an Array

Problem Description​

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:

Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.

Example 2:

Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".

Constraints​

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30

Solution for String Matching in an Array​

Code in Different Languages​

Written by @agarwalhimanshugaya
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
vector<string> ans;
for(auto i:words)
{
for(auto j: words)
{
if(i==j) continue;
if(j.find(i)!=-1)
{
ans.push_back(i);
break;
}
}
}
return ans;
}
};

Complexity Analysis​

Time Complexity: O(NlogN+N∗S2)O(NlogN + N * S^2)​

Space Complexity: O(N∗S2)O(N * S^2)​

References​