You are given an array of strings words
and a string pref
. A string is considered a suitable word if it starts with the prefix pref
.
Return the number of strings in words
that are suitable.
Input: words = ["pay", "attention", "practice", "attend"], pref = "at"
Output: 2
Input: words = ["leetcode", "win", "loops", "success"], pref = "code"
Output: 0
words
array be empty?
words
array is empty, the output should be 0.pref
is non-empty.words
and pref
lowercase letters?
words
and pref
?
words
can have up to 10^4 elements and each string can be up to 100 characters long.words
.pref
using the startswith
method.def count_words_with_prefix(words, pref):
count = 0
for word in words:
if word.startswith(pref):
count += 1
return count
The time complexity of this solution is O(n * m), where:
n
is the number of words in the words
list.m
is the length of the prefix pref
.This is because the startswith
method internally checks up to len(pref)
characters for each word, leading to a complexity of O(m) per word. Looping through all words results in the total time complexity of O(n * m). This is efficient given typical constraints in competitive programming.
Let’s walk through the example in the problem statement:
For words = ["pay", "attention", "practice", "attend"]
and pref = "at"
:
Therefore, the function returns 2.
The code is designed to handle the general case and efficiently count words with a given prefix.
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?