Counting Words With a Given Prefix (LeetCode 2185): Solution and Explanation
Given a list of words and a string pref, count how many words begin with pref. A word that only contains pref somewhere in the middle does not count.
Intuition
Think of pref as a stencil. Place it over the first letters of a word: the word counts only if every letter of the stencil sits on the same letter.
Letters after the stencil never matter, so each word costs at most pref.length comparisons. The first mismatch ends the check for that word.
A word shorter than pref runs out of letters before the stencil does, so it can never match. Built-in prefix checks handle that case for you.
Approach: Prefix check per word
- Set
count = 0. - For each word, test whether it starts with
pref(startswith, startsWith, HasPrefix, or compare the first pref.length letters). - If it does, add 1 to
count. - Return
count.
Step-by-step example
words = ["pay","attention","practice","attend"], pref = "at"
- "pay": 'p' is not 'a', so the check stops at the first letter. count stays 0.
- "attention": 'a' and 't' both match the stencil. count becomes 1.
- "practice": 'p' is not 'a'. count stays 1.
- "attend": 'a' and 't' match. count becomes 2.
- Return 2.
Code: Python, Java, C++
1class Solution:
2 def prefixCount(self, words: List[str], pref: str) -> int:
3 count = 0
4 for word in words:
5 if word.startswith(pref):
6 count += 1
7 return count1class Solution {
2 public int prefixCount(String[] words, String pref) {
3 int count = 0;
4 for (String word : words) {
5 if (word.startsWith(pref)) {
6 count++;
7 }
8 }
9 return count;
10 }
11}1class Solution {
2public:
3 int prefixCount(vector<string>& words, string pref) {
4 int count = 0;
5 for (const string& word : words) {
6 if (word.compare(0, pref.size(), pref) == 0) {
7 count++;
8 }
9 }
10 return count;
11 }
12};Time and space complexity
O(n * m)
n is the number of words and m is the length of pref. Each word needs at most m letter comparisons.
O(1)
Only the counter is stored.
Other approaches
Slice and compare (time O(n * m), space O(m))
Compare word[:len(pref)] == pref. Same result, but the slice copies up to m letters per word.
Trie (time O(total letters + m), space O(total letters))
Insert every word into a trie that stores how many words pass through each node, then walk pref down the trie. Worth it only when many different prefixes are queried against the same words.
Common mistakes
- Using a substring search such as
pref in wordorcontains. "leetcode" contains "code" but does not start with it. - Indexing past the end of a word shorter than pref when comparing letters by hand.
- Counting a word more than once. Each word adds at most 1.
Frequently asked questions
Does a word equal to pref count?
Yes. Every string is a prefix of itself, so a word that is exactly pref adds 1.
Why not build a trie?
There is only one prefix to test. A direct check of each word is already linear in the letters that matter, and a trie would only add memory.
What happens when pref is longer than a word?
That word cannot start with pref, so it is skipped. Built-in prefix functions return false for it without reading past the end.