Engineering platform~40 min2s · 256 MBtarget O(n × L^2 + q × L) time, O(n × L^2 × 27) spaceclassic twin: lc-745trie
A build platform gives every release a short lowercase label, such as login or billing. Labels are listed in the order they were published, so position 0 is the oldest. The same label can be published more than once.
An on-call engineer often remembers only how a label starts and how it ends. Your team lead asks: "For each pair of a start and an end, which is the newest label that has both?"
Write newest_matching(labels, prefixes, suffixes).
labels[i] is the label published at position i.q is the pair prefixes[q] and suffixes[q]. A label matches when it starts with the prefix and ends with the suffix. The two parts may share letters.-1 when no label matches.Input: labels = ["bill", "billing", "sibling", "ailing"], prefixes = ["b", "b", "s", "a", "x"], suffixes = ["l", "g", "ing", "ng", "g"]
Output: [0, 1, 2, 3, -1]Every label is stored once for each place its end can start. A query walks the text "end, a separator, start" through that store. The last stop of the walk remembers the newest position that passed through it.
| Query (start, end) | Text walked | Newest position at the end of the walk |
|---|---|---|
b, l |
l{b |
0 (only bill starts with b and ends with l) |
b, g |
g{b |
1 (billing) |
s, ing |
ing{s |
2 (sibling) |
a, ng |
ng{a |
3 (ailing) |
x, g |
g{x |
no stop for x, so -1 |
Input: labels = ["tag", "tag", "tags"], prefixes = ["t", "t"], suffixes = ["g", "s"]
Output: [1, 2]Positions 0 and 1 both match the first query, and the newer one wins. Only position 2 ends with s.
Input: labels = ["aba"], prefixes = ["ab"], suffixes = ["ba"]
Output: [0]The label aba starts with ab and ends with ba. The two parts overlap on the middle letter, and that is allowed.
1 ≤ len(labels) ≤ 5,000 and each label has 1 to 7 lowercase letters1 ≤ len(prefixes) = len(suffixes) ≤ 5,000 and each part has 1 to 7 lowercase lettersChecking every label for every query costs 5,000 × 5,000 = 25 million checks, and every check reads up to 14 letters. A real registry grows, and the number of queries grows with it.
The labels are short, at most 7 letters. So a label has at most 7 ends, each stored with the label as a text of at most 14 letters. That store holds at most 5,000 × 84 = 420,000 letters, and a query then costs at most 15 steps, whatever the number of labels.