String Matching in an Array — LeetCode 1408 Python Solution
EasyArrayStringString Matching
- Problem
- #1408
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^3) |
| Space | O(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.