Number of Strings That Appear as Substrings in Word
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an array of strings patterns and a string word, return _thenumber of strings in _patterns _that exist as asubstring in _word.
A substring is a contiguous sequence of characters within a string.
Examples
Example 1
Input: patterns = ["a","abc","bc","d"], word = "abc"
Output: 3
Explanation:
- "a" appears as a substring in "_a_ bc".
- "abc" appears as a substring in "_abc_ ".
- "bc" appears as a substring in "a _bc_ ".
- "d" does not appear as a substring in "abc".
3 of the strings in patterns appear as a substring in word.
Example 2
Input: patterns = ["a","b","c"], word = "aaaaabbbbb"
Output: 2
Explanation:
- "a" appears as a substring in "a _a_ aaabbbbb".
- "b" appears as a substring in "aaaaabbbb _b_ ".
- "c" does not appear as a substring in "aaaaabbbbb".
2 of the strings in patterns appear as a substring in word.
Example 3
Input: patterns = ["a","a","a"], word = "ab"
Output: 3
Explanation: Each of the patterns appears as a substring in word "_a_ b".
Constraints
1 <= patterns.length <= 1001 <= patterns[i].length <= 1001 <= word.length <= 100patterns[i]andwordconsist of lowercase English letters.
Solution
Method 1 – Simple Substring Check
Intuition
For each pattern, check if it appears as a substring in the given word. This is a direct application of the substring operation and is efficient given the constraints.
Approach
- Initialize a counter
ansto 0. - For each string in
patterns, check if it is a substring ofword. - If yes, increment
ans. - Return
ans.
Code
C++
class Solution {
public:
int numOfStrings(vector<string>& patterns, string word) {
int ans = 0;
for (const auto& p : patterns) {
if (word.find(p) != string::npos) ++ans;
}
return ans;
}
};
Go
func numOfStrings(patterns []string, word string) int {
ans := 0
for _, p := range patterns {
if strings.Contains(word, p) {
ans++
}
}
return ans
}
Java
class Solution {
public int numOfStrings(String[] patterns, String word) {
int ans = 0;
for (String p : patterns) {
if (word.contains(p)) ans++;
}
return ans;
}
}
Kotlin
class Solution {
fun numOfStrings(patterns: Array<String>, word: String): Int {
var ans = 0
for (p in patterns) {
if (word.contains(p)) ans++
}
return ans
}
}
Python
class Solution:
def numOfStrings(self, patterns: list[str], word: str) -> int:
ans = 0
for p in patterns:
if p in word:
ans += 1
return ans
Rust
impl Solution {
pub fn num_of_strings(patterns: Vec<String>, word: String) -> i32 {
patterns.iter().filter(|p| word.contains(&**p)).count() as i32
}
}
TypeScript
class Solution {
numOfStrings(patterns: string[], word: string): number {
let ans = 0;
for (const p of patterns) {
if (word.includes(p)) ans++;
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n * m * w), wherenis the number of patterns,mis the average length of a pattern, andwis the length ofword. Each substring check is up toO(m * w). - 🧺 Space complexity:
O(1), as we use only a constant amount of extra space.