You are given an array of strings words
and a string pref
.
Return the number of strings in words
that contain pref
as a prefix.
A prefix of a string s
is any leading contiguous substring of s
.
For example:
words = ["pay","attention","practice","attend"]
and pref = "at"
, the output should be 2 because "attention" and "attend" contain "at" as a prefix.words = ["leetcode","win","loops","success"]
and pref = "code"
, the output should be 0 because none of the words contain "code" as a prefix.Write a function that takes an array of strings words
and a string pref
as input and returns the number of strings in words
that have pref
as a prefix. What is the time and space complexity of your solution? Consider edge cases such as an empty words
array or an empty pref
string.
The most straightforward approach is to iterate through the words
array and, for each word, check if the pref
is a prefix of that word. We can use string slicing or built-in prefix checking methods to achieve this.
def prefix_count_naive(words, pref):
count = 0
for word in words:
if word.startswith(pref):
count += 1
return count
O(N * M), where N is the number of words in the words
array, and M is the maximum length of a word in words
or the length of pref
.
O(1), as we use only a constant amount of extra space.
The optimal solution has the same time and space complexity as the naive solution because we still need to iterate through all the words to check for the prefix. However, the code can be slightly optimized for readability and conciseness.
def prefix_count_optimal(words, pref):
return sum(1 for word in words if word.startswith(pref))
O(N * M), where N is the number of words in the words
array, and M is the maximum length of a word in words
or the length of pref
.
O(1), as we use only a constant amount of extra space.
words
array: Should return 0.pref
: Every word has an empty string as a prefix, so return the number of words.pref
longer than a word in words
: The word cannot have pref
as a prefix, so it should not be counted.Both solutions have the same time and space complexity. The optimal solution is just a more concise way to express the same logic. We iterate through the words
array and check if each word starts with the given prefix pref
. The count of such words is then returned.