Understand String Matching in an Array Problem

Problem Name: String Matching in an Array
Problem Description:

Problem: String Matching in an Array

You are given an array of strings words. Your task is to find all the strings in the array that are a substring of another string in the same array. Return these strings in any order.

Key Points:

  • A substring is a part of another string. For example, "as" is a substring of "mass".
  • We are looking for strings in the array that can be found as substrings within other strings in the array.

Examples:

Example 1:

Input:
words = ["mass", "as", "hero", "superhero"]
Output:
["as", "hero"]
Explanation:

  • "as" is a substring of "mass".
  • "hero" is a substring of "superhero".
  • The order of the output does not matter. For example, ["hero", "as"] is also correct.

Example 2:

Input:
words = ["leetcode", "et", "code"]
Output:
["et", "code"]
Explanation:

  • "et" is a substring of "leetcode".
  • "code" is a substring of "leetcode".

Example 3:

Input:
words = ["blue", "green", "bu"]
Output:
[]
Explanation:
No string in the array is a substring of another string.


Constraints:

1words.length1001words[i].length30Each string in words contains only lowercase English letters.All strings in words are unique.\begin{aligned} &1 \leq \text{words.length} \leq 100 \\ &1 \leq \text{words[i].length} \leq 30 \\ &\text{Each string in words contains only lowercase English letters.} \\ &\text{All strings in words are unique.} \end{aligned}

What to Do:

  1. Go through each string in the array.
  2. Check if it is a substring of any other string in the array.
  3. Collect all such strings and return them in any order.

Output:

The output is an array containing strings that are substrings of other strings in the input array.

Category:
  • Leetcode Problem of the Day
  • Arrays
  • Strings
Programming Language:
  • Java
Reference Link:

https://leetcode.com/problems/string-matching-in-an-array/?envType=daily-question&envId=2025-01-06

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

Main Function is not defined.

Helper Function:

INPUT: words = ["mass", "as", "hero", "superhero"]

OUTPUT: ["as", "hero"]

public static List<String> stringMatching(String[] words) {

List<String> result = new ArrayList<>();

Arrays.sort(words, (a,b) -> Integer.compare(a.length(), b.length() ) );

for( int i = o; i < words.length; i++) {

for ( int j = i+1; j < words.length; j++) {

if ( words[j].contains(words[i])) {

result.add( words[i] );

break;

}//If End

}//Loop End

}//Loop End

return result;

}//function end

Utility Functions and Global variables:

Utility Function is not required.