Monitoring~25 min2s · 256 MBtarget O(L + M) time, O(L + M) spaceclassic twin: lc-648trie
A monitoring app groups alerts by their wording. Each team registers short root codes for its components, such as db for the database and net for the network. An alert word such as dbserver should show up as db, so that related alerts land in one group.
You get the list of root codes and one alert message. Every word that begins with a root must be cut down to that root.
Write shorten_alert(roots, message).
roots is a list of lowercase root codes. A code can appear more than once.message is made of lowercase words separated by single spaces. It has no space at either end.Input: roots = ["net", "db", "cache"], message = "network timeout on dbserver and cached reply"
Output: "net timeout on db and cache reply"| Word | Roots that fit | Result |
|---|---|---|
network |
net |
net |
timeout |
none | timeout |
on |
none | on |
dbserver |
db |
db |
and |
none | and |
cached |
cache |
cache |
reply |
none | reply |
Only words that begin with a root change. Every other word stays.
Input: roots = ["a", "aa", "aaa"], message = "aaaa aab b"
Output: "a a b"All three roots fit aaaa, and the shortest is a. The word aab also begins with a. The word b fits no root.
Input: roots = ["cat"], message = "ca cat category"
Output: "ca cat cat"The word ca is shorter than the root, so it stays. The word cat equals the root. The word category begins with it.
1 ≤ length of roots ≤ 5000, and every root has 1 to 20 lowercase letters1 ≤ length of message ≤ 100000, made of the letters a to z and single spacesA message of 100,000 characters can hold about 20,000 short words, and there can be 5,000 roots. Testing every root against every word is up to 100 million comparisons, which is too slow.
A root has at most 20 letters, so a word never needs more than its first 20 letters to be decided. A trie of the roots finds the answer for a word in at most 20 steps, however many roots there are.