Count Prefixes of a Given String - Problem
You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.
Return the number of strings in words that are a prefix of s.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.
Input & Output
Example 1 — Basic Case
$
Input:
words = ["a", "b", "c", "ab", "bc", "abc"], s = "abc"
›
Output:
3
💡 Note:
The words "a", "ab", and "abc" are prefixes of "abc". "b", "c", and "bc" do not start at the beginning of "abc".
Example 2 — No Matches
$
Input:
words = ["a", "a"], s = "aa"
›
Output:
2
💡 Note:
Both instances of "a" are prefixes of "aa". The string "a" matches the beginning of "aa".
Example 3 — Empty Prefix Not Allowed
$
Input:
words = ["hello", "world", "hi"], s = "hi"
›
Output:
1
💡 Note:
Only "hi" exactly matches the target string "hi" as a prefix. "hello" and "world" don't match the beginning.
Constraints
- 1 ≤ words.length ≤ 1000
- 1 ≤ words[i].length, s.length ≤ 100
- words[i] and s consist of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of words and target string s
2
Check Prefixes
Test each word against beginning of s
3
Count Matches
Return number of valid prefixes found
Key Takeaway
🎯 Key Insight: A prefix must match the target string starting from the very beginning - any mismatch means it's not a valid prefix.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code