Counting Words With a Given Prefix - Problem

You are given an array of strings words and a string pref.

Return the number of strings in words that contain pref as a prefix.

A prefix of a string s is any leading contiguous substring of s.

Input & Output

Example 1 — Basic Case
$ Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2
💡 Note: Only "attention" and "attend" start with "at", so return 2
Example 2 — No Matches
$ Input: words = ["leetcode","win","loops","success"], pref = "code"
Output: 0
💡 Note: None of the words start with "code" as a prefix
Example 3 — All Match
$ Input: words = ["car","care","careful"], pref = "car"
Output: 3
💡 Note: All three words start with "car"

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length, pref.length ≤ 100
  • words[i] and pref consist of lowercase English letters

Visualization

Tap to expand
Counting Words With PrefixInput: words = ["pay", "attention", "practice", "attend"], pref = "at"payattentionpracticeattend✗ starts with "pa"✓ starts with "at"✗ starts with "pr"✓ starts with "at"Looking for prefix: "at"Output: 2Two words start with "at": "attention" and "attend"
Understanding the Visualization
1
Input
Array of words and target prefix
2
Process
Check each word if it starts with prefix
3
Output
Count of matching words
Key Takeaway
🎯 Key Insight: Use built-in string methods to efficiently check prefix matching for each word
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~8 min Avg. Time
892 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