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
Search Autocomplete SystemSearch: apDatabase Wordsapple โœ“app โœ“apricot โœ“banana โœ—Matching ResultsCount: 3Search Results Previewโ€ข apple - red fruitโ€ข app - mobile applicationโ€ข apricot - orange fruit
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)

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a counter variable, no extra space needed

n
2n
โœ“ 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
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
28.8K Views
Medium Frequency
~8 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen