You are given an array of strings patterns
and a string word
. You want to return the number of patterns[i]
that appear as a substring in word
.
Input:
patterns = ["a", "abc", "bc", "d"]
word = "abc"
Output:
3
Explanation:
1 <= patterns.length <= 100
1 <= patterns[i].length <= 100
1 <= word.length <= 100
patterns[i]
and word
contain only lowercase English letters.Given the constraints, a simple and straightforward approach should work fine:
patterns
.word
using the in
keyword.m
is the length of the pattern and n
is the length of the word.p
, the overall time complexity would be O(p * (m+n)), but since both m
and n
as well as p
are restricted to fairly small values (no more than 100), this approach is efficient.Here’s how you can implement the solution:
def numOfStrings(patterns, word):
count = 0
for pattern in patterns:
if pattern in word:
count += 1
return count
# Example usage
patterns = ["a", "abc", "bc", "d"]
word = "abc"
print(numOfStrings(patterns, word)) # Output: 3
count
to 0.pattern
in the patterns
list.pattern
, we check if it is a substring of word
using the in
operation.pattern
is found in word
, we increment the count
.This code efficiently counts the number of patterns that are substrings of the given word.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?