1408. String Matching in an Array LeetCode Solution

In this guide, you will get 1408. String Matching in an Array LeetCode Solution with the best time and space complexity. The solution to String Matching in an Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. String Matching in an Array solution in C++
  4. String Matching in an Array solution in Java
  5. String Matching in an Array solution in Python
  6. Additional Resources
1408. String Matching in an Array LeetCode Solution image

Problem Statement of String Matching in an Array

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.

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”.

Example 3:

Input: words = [“blue”,”green”,”bu”]
Output: []
Explanation: No string of words is substring of another string.

Constraints:

1 <= words.length <= 100
1 <= words[i].length <= 30
words[i] contains only lowercase English letters.
All the strings of words are unique.

Complexity Analysis

  • Time Complexity: O(|\texttt{words}|^2|\texttt{words[i]}|)
  • Space Complexity: O(|\texttt{words}|^2|\texttt{words[i]}|)

1408. String Matching in an Array LeetCode Solution in C++

class Solution {
 public:
  vector<string> stringMatching(vector<string>& words) {
    vector<string> ans;
    for (const string& a : words)
      for (const string& b : words)
        if (a.length() < b.length() && b.find(a) != string::npos) {
          ans.push_back(a);
          break;
        }
    return ans;
  }
};
/* code provided by PROGIEZ */

1408. String Matching in an Array LeetCode Solution in Java

class Solution {
  public List<String> stringMatching(String[] words) {
    List<String> ans = new ArrayList<>();
    for (final String a : words)
      for (final String b : words)
        if (a.length() < b.length() && b.indexOf(a) != -1) {
          ans.add(a);
          break;
        }
    return ans;
  }
}
// code provided by PROGIEZ

1408. String Matching in an Array LeetCode Solution in Python

class Solution:
  def stringMatching(self, words: list[str]) -> list[str]:
    ans = []
    for a in words:
      for b in words:
        if len(a) < len(b) and b.find(a) != -1:
          ans.append(a)
          break
    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.