String Matching in an Array — LeetCode 1408 Python Solution

EasyArrayStringString Matching
Problem
#1408
Pattern
Hash Map
Reading time
2 min

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

Example

Input
words = ["mass","as","hero","superhero"]
Output
["as","hero"]
Explanation
"as" is substring of "mass" and "hero" is substring of "superhero".

Python solution

Python
class Solution:
    def stringMatching(self, words: List[str]) -> List[str]:
        ans = []
        for i, s in enumerate(words):
            if any(i != j and s in t for j, t in enumerate(words)):
                ans.append(s)
        return ans

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1408. String Matching in an Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1408. String Matching in an Array?
LeetCode 1408. String Matching in an Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 1408. String Matching in an Array?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 1408. String Matching in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1408. String Matching in an Array cover?
LeetCode 1408. String Matching in an Array is tagged Array, String and String Matching on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview