1474. Sorted Lexicon Prefix Tally
A dictionary app keeps its entries in words, sorted in ordinary lexicographic (alphabetical) order; the same word may appear several times and every entry counts. For each string in prefixes, report how many entries of words start with it. A word that equals the prefix exactly also counts.
Return an array with one count per prefix, in the same order as prefixes.
Because the entries are sorted, all words sharing a prefix form one contiguous block. Two binary searches per query find its edges: the first position not smaller than the prefix, and the first position not smaller than the prefix followed by the character '{' (which sorts right after 'z'). Aim for O(q * L * log w) time and O(1) extra space beyond the answer.
Example 1
- Input:
- words = ["apple","apply","apt","bat","batch","bath","cat"]prefixes = ["ap","bat","c","d"]
- Output:
- [3,3,1,0]
- Explanation:
Three words start with 'ap', three with 'bat', one with 'c', and none with 'd'.
Example 2
- Input:
- words = ["a","a","aa","b"], prefixes = ["a","aa","aaa"]
- Output:
- [3,1,0]
- Explanation:
Both copies of 'a' and the word 'aa' start with 'a', only 'aa' starts with 'aa', and nothing starts with 'aaa'.
Constraints
1 ≤ words.length ≤ 500
1 ≤ prefixes.length ≤ 200
1 ≤ length of every string ≤ 10
lowercase English letters only
words is sorted lexicographically
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(q * L * log w)
- Space
- O(q)