Practice problem · easy
A dictionary app builds an index so that it can suggest words while you type. The index needs one entry for every different start of a word, such as c, ca and car for the word car.
Before building it, the team wants to know how big it will be. You get the word list, and you must count the different non-empty prefixes.
Write count_prefixes(words).
words is the word list, in lowercase letters. A word can appear more than once.Input: words = ["car", "cat", "cart"]
Output: 5| Word | Its prefixes |\n|---|---|\n| car | c, ca, car |\n| cat | c, ca, cat |\n| cart | c, ca, car, cart |\n\nThe different ones are c, ca, car, cat and cart: 5.
Input: words = ["a", "a", "a"]
Output: 1Every copy has the same single prefix, a, so the count is 1.
Input: words = ["ab", "cd"]
Output: 4The words share nothing: a, ab, c and cd.
1 ≤ length of words ≤ 5000a to z)There can be 5,000 words of 20 letters, so up to 100,000 prefixes in all. Writing every prefix into a set of strings costs the letters of each prefix again and again.
A trie makes one node for each different prefix and reads each letter of each word once.
count_prefixes · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.