Counting Words With a Given Prefix - Problem
Imagine you're building a search autocomplete feature! You have an array of strings words and a search prefix pref.
Your task is to count how many words in the array start with the given prefix. A prefix is simply the beginning part of a string - any leading contiguous substring.
Goal: Return the number of strings in words that have pref as a prefix.
Example: If words = ["apple", "app", "apricot", "banana"] and pref = "ap", then 3 words start with "ap": "apple", "app", and "apricot".
Input & Output
example_1.py โ Basic prefix matching
$
Input:
words = ["pay","attention","practice","attend"], pref = "at"
โบ
Output:
2
๐ก Note:
The words that start with "at" are "attention" and "attend", so we return 2.
example_2.py โ No matches found
$
Input:
words = ["leetcode","win","loops","success"], pref = "code"
โบ
Output:
0
๐ก Note:
None of the words start with "code" as a prefix, so we return 0.
example_3.py โ All words match
$
Input:
words = ["apple","app","application"], pref = "app"
โบ
Output:
3
๐ก Note:
All three words start with "app": "apple", "app", and "application".
Visualization
Tap to expand
Understanding the Visualization
1
User types prefix
Search box receives 'ap' as input
2
Scan word database
System checks each word in the database
3
Match prefixes
Count words that start with 'ap'
4
Return count
Display number of matching results
Key Takeaway
๐ฏ Key Insight: Modern string prefix checking is essentially what powers autocomplete systems - count matches efficiently using built-in methods!
Time & Space Complexity
Time Complexity
O(n * m)
Where n is number of words and m is length of prefix (built-in methods are optimized)
โ Linear Growth
Space Complexity
O(1)
Only using a counter variable, no extra space needed
โ Linear Space
Constraints
- 1 โค words.length โค 1000
- 1 โค words[i].length, pref.length โค 1000
- words[i] and pref consist of lowercase English letters only
- Edge case: Empty prefix matches all words
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code