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.
Example 1:
Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2Explanation: The two strings that contain "at" as a prefix are: "attention" and "attend".
Example 2:
Input: words = ["neetcode","neet","nee","code"], pref = "ne"
Output: 3Explanation: The three strings that contain "ne" as a prefix are: "neetcode","neet" and "nee".
Constraints:
1 <= words.length <= 1001 <= words[i].length, pref.length <= 100words[i] and pref consist of lowercase English letters.Before attempting this problem, you should be comfortable with:
To check if a word has a given prefix, we compare the first few characters of the word with the prefix string. If the word is shorter than the prefix, it cannot have that prefix. Otherwise, we check character by character until we either find a mismatch or confirm all prefix characters match.
0.Where is the number of words and is the length of the string .
Most programming languages provide built-in methods to check if a string starts with a given prefix. These methods handle the character comparison internally and are optimized for the task, making the code cleaner and less error-prone.
0.startsWith or hasPrefix).Where is the number of words and is the length of the string .
A Trie (prefix tree) is a tree structure where each node represents a character. By inserting only the first few characters of each word (up to the prefix length), we build a compact structure. Each node keeps a count of how many words pass through it. After inserting all words, we traverse the trie following the prefix characters and return the count at the final node.
prefix.length characters into the trie.0.class PrefixNode:
def __init__(self):
self.children = {} # a -> PrefixNode
self.count = 0
class PrefixTree:
def __init__(self):
self.root = PrefixNode()
def add(self, w: str, length: int) -> None:
cur = self.root
for i in range(length):
if w[i] not in cur.children:
cur.children[w[i]] = PrefixNode()
cur = cur.children[w[i]]
cur.count += 1
def count(self, pref: str) -> int:
cur = self.root
for c in pref:
if c not in cur.children:
return 0
cur = cur.children[c]
return cur.count
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
prefix_tree = PrefixTree()
for w in words:
if len(w) >= len(pref):
prefix_tree.add(w, len(pref))
return prefix_tree.count(pref)Where is the number of words, is the length of the string and is the maximum length of a word.
The problem asks for words that start with the prefix, not words that contain the prefix anywhere. Using a contains/includes check instead of a starts-with check will incorrectly count words where the prefix appears in the middle.
# Wrong: Checks if prefix exists anywhere in the word
if pref in word:
count += 1
# Correct: Checks if word starts with prefix
if word.startswith(pref):
count += 1When manually comparing characters, forgetting to check if the word is at least as long as the prefix leads to index out of bounds errors or incorrect matches.
# Wrong: May cause index error if word is shorter than prefix
for i in range(len(pref)):
if word[i] != pref[i]: # Error when len(word) < len(pref)
break
# Correct: Skip words shorter than the prefix
if len(word) < len(pref):
continue
for i in range(len(pref)):
if word[i] != pref[i]:
break