Problem · String
Count Prefix Matches in a Sorted Array
Learn this problemProblem statement
Given a lexicographically sorted array of lowercase strings words and a lowercase string prefix, return the number of array entries that begin with prefix.
Duplicate words count separately. For this exercise, assume all words and the prefix are non-empty and use ordinary lowercase lexicographic order.
Use the sorted order to locate the contiguous matching range with binary search.
Function
countPrefixMatches(words: String[], prefix: String) → intExamples
Example 1
words = ["apple","apply","apt","banana"]prefix = "app"return = 2Only apple and apply begin with app.
Example 2
words = ["a","a","ab","b"]prefix = "a"return = 3Both copies of a and the word ab match, so duplicates contribute separately.
Constraints
0 <= words.length <= 2 * 10^5- Every word and
prefixis a non-empty lowercase English string. wordsis sorted in nondecreasing lexicographic order.- The total number of characters in
wordsandprefixis at most2 * 10^5.