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 a Given Prefix INPUT words[] array: "pay" "attention" "practice" "attend" prefix (pref): "at" [0] [1] [2] [3] ALGORITHM STEPS 1 Initialize counter count = 0 2 Iterate each word for word in words[] 3 Check prefix word.startsWith(pref) 4 Increment if match count++ when true Prefix Check Results: "pay" NO (starts: "pa") "attention" OK (starts: "at") "practice" NO (starts: "pr") "attend" OK (starts: "at") FINAL RESULT Words matching prefix "at": "attention" "attend" Total count: 2 Output: 2 Key Insight: The built-in startsWith() method efficiently checks if a string begins with the given prefix. Time Complexity: O(n * m) where n = number of words, m = prefix length. Space: O(1). TutorialsPoint - Counting Words With a Given Prefix | Built-in String Prefix Check Approach
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