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
Count Prefixes of a Given String INPUT words array: "a" "b" "c" "ab" "bc" "abc" Target string s: "abc" Possible prefixes of "abc": "a" "ab" "abc" Check if each word is a prefix of target string s ALGORITHM STEPS 1 Initialize counter count = 0 2 Loop through words for each word in words[] 3 Check prefix s.startsWith(word) 4 Increment if match if true: count++ Prefix Checks: "a" startsWith? OK count=1 "b" startsWith? NO "c" startsWith? NO "ab" startsWith? OK count=2 "bc" startsWith? NO "abc" startsWith? OK count=3 FINAL RESULT Matching prefixes found: "a" "ab" "abc" All are prefixes of "abc" Output: 3 3 words are prefixes of the string "abc" Key Insight: Use built-in string methods like startsWith() or substring() to check if each word is a prefix of the target string. A word is a prefix if the target string begins with that word. Time Complexity: O(n * m) where n = number of words, m = average word length. TutorialsPoint - Count Prefixes of a Given String | Built-in String Methods Approach
Asked in
Amazon 15 Microsoft 12
23.0K Views
Medium Frequency
~10 min Avg. Time
890 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