Given a list of strings words and a string s, determine the number of strings in words that are a prefix of s.
A string word is a prefix of s if s starts with word.
Example:
Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Explanation: The strings in words that are prefixes of s are "a", "ab", and "abc".
s be empty?
s will be a non-empty string as per typical problem constraints.words be empty or contain empty strings?
words.s.
.startswith() which returns True if the given string starts with the specified prefix.def countPrefixes(words, s):
count = 0
for word in words:
if s.startswith(word):
count += 1
return count
# Example usage
words = ["a","b","c","ab","bc","abc"]
s = "abc"
print(countPrefixes(words, s)) # Output: 3
.startswith() method has a time complexity of O(m) where m is the length of the word.words: Let n be the number of words in the list.m is the maximum length of any word in words.Thus, the time complexity is generally efficient given that string comparison operations are fast in Python. This should handle typical constraints comfortably unless words or s are exceptionally large.
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?