Count Prefixes of a Given String - Problem
Imagine you're a word validator checking which words from a dictionary could be the beginning of a target word. You're given an array of strings words and a target string s, where all characters are lowercase English letters.
Your task is to count how many strings in words are prefixes of s.
A prefix is a substring that appears at the very beginning of a string. For example:
"app"is a prefix of"apple""a"is a prefix of"apple""apple"is a prefix of itself"ppl"is NOT a prefix of"apple"(doesn't start from beginning)
Goal: Return the count of valid prefixes found in the words array.
Input & Output
example_1.py โ Basic Prefix Matching
$
Input:
words = ["a", "b", "c", "ab", "bc", "abc"], s = "abc"
โบ
Output:
3
๐ก Note:
The strings "a", "ab", and "abc" are prefixes of "abc". "b", "c", and "bc" are not prefixes because they don't start from the beginning.
example_2.py โ No Valid Prefixes
$
Input:
words = ["aa", "aaaa", "banana"], s = "aa"
โบ
Output:
2
๐ก Note:
"aa" and "aaaa" need to be checked. "aa" is a valid prefix (exact match), but "aaaa" is longer than "aa" so it cannot be a prefix. "banana" doesn't start with "aa".
example_3.py โ Single Character Prefixes
$
Input:
words = ["a", "aa", "aaa", "aaaa"], s = "aaaa"
โบ
Output:
4
๐ก Note:
All words are prefixes of "aaaa": "a" matches first char, "aa" matches first two chars, "aaa" matches first three chars, and "aaaa" is an exact match.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Search
You have a target book title 'Advanced Algorithms' and several title fragments
2
Check Each Fragment
For each fragment, see if the target title starts with that exact text
3
Valid Matches
'A', 'Adv', 'Advanced' would all be valid - they appear at the beginning
4
Invalid Matches
'Algorithm', 'Book' wouldn't match - they don't start from the beginning
Key Takeaway
๐ฏ Key Insight: Use built-in string methods for cleaner, more efficient prefix checking rather than implementing character-by-character comparison manually.
Time & Space Complexity
Time Complexity
O(n * m)
Where n is number of words and m is average word length. Built-in methods are optimized but still need to check characters.
โ Linear Growth
Space Complexity
O(1)
Only using a counter variable, no additional space needed.
โ Linear Space
Constraints
- 1 โค words.length โค 1000
- 1 โค words[i].length, s.length โค 1000
- words[i] and s consist of lowercase English letters only
- Sum of all words[i].length โค 105
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code