Problem 441702 · medium · Level 04 Non-Linear Data Structures

Speed-Dial Abbreviations

trie · prefix counting

A phone lets you ring a contact by typing only the start of their name, as long as no other contact's name starts the same way. Given the distinct names words, return for each name the shortest start that is not also the start of any other name in the list. If even the whole name is the start of some other name, return the whole name.

Return the abbreviations in the same order as words.

Examples

Input:  words = ["moss", "lamp", "lame", "lake"]
Output: ["m", "lamp", "lame", "lak"]
Explanation: "l" and "la" are shared by lamp, lame and lake, and "lam" by lamp and lame,
so those two need four letters while lake needs only "lak".

Input:  words = ["apple", "app"]
Output: ["appl", "app"]
Explanation: every prefix of "app" is also a prefix of "apple", so "app" is returned unchanged.

Constraints

  • 0 <= len(words) <= 10**4, total characters <= 2 * 10**5, lowercase letters and digits
  • Target: O(total characters)

Goals

  • Use per-node counts to find where a word's path becomes unique
  • Handle words that are prefixes of other words
Starting Python…