Problem 454353 · easy · Level 04 Non-Linear Data Structures

How Many Titles Start This Way?

trie · prefix counting · hash map

A library catalogue holds the titles words; the same title may appear several times, and every copy counts. Readers send the lookups prefixes, and for each lookup the catalogue reports how many titles begin with it. The empty lookup "" matches every title.

Return the counts as a list in the same order as prefixes.

Examples

Input:  words = ["apple", "app", "apricot", "banana"], prefixes = ["ap", "app", "b", "c"]
Output: [3, 2, 1, 0]
Explanation: "ap" starts apple, app and apricot; "app" starts apple and app; nothing starts with "c".

Input:  words = ["go", "go", "gone"], prefixes = ["go", ""]
Output: [3, 3]

Constraints

  • 0 <= len(words), len(prefixes) <= 2 * 10**4
  • Words and prefixes consist of lowercase letters and digits; total characters <= 2 * 10**5
  • Target: O(total characters) to build plus O(len(prefix)) per query. Scanning all words for every query is too slow.

Goals

  • Build a trie whose nodes remember how many words pass through them
  • Answer many prefix queries without rescanning the word list each time
Starting Python…