Search~30 min2s · 256 MBtarget O((p + q) α(p)) time, O(p) spaceclassic twin: lc-1061union-find
A search engine keeps a list of synonym pairs, such as car and auto. A synonym of a synonym is also a synonym, so car, auto and vehicle mean the same when the pairs link them in a chain.
To match documents, the engine replaces every query term by one standard word for its group: the alphabetically smallest word. A term that appears in no pair stands for itself.
Your team lead asks: What does each query term become?
Write canonical_terms(left, right, query).
left and right have the same length. The words left[i] and right[i] are synonyms.query: the smallest word in the term's group, or the term itself when it is in no pair.Input: left = ["car","drive","auto","ride"], right = ["auto","ride","vehicle","trip"], query = ["vehicle","trip","bus","car"]
Output: ["auto","drive","bus","auto"]The solution gives every word a group. Each pair joins two groups, and the joined group remembers its smallest word.
| Pair read | Groups with their smallest word |
|---|---|
car, auto |
{car, auto}: auto |
drive, ride |
{car, auto}: auto, and {drive, ride}: drive |
auto, vehicle |
{car, auto, vehicle}: auto, and {drive, ride}: drive |
ride, trip |
{car, auto, vehicle}: auto, and {drive, ride, trip}: drive |
The terms vehicle and car become auto, trip becomes drive, and bus is in no pair.
Input: left = ["tea"], right = ["brew"], query = ["tea","brew","cup"]
Output: ["brew","brew","cup"]The word brew comes before tea in the dictionary, so both terms become brew. The term cup has no synonym.
Input: left = [], right = [], query = ["map"]
Output: ["map"]With no pairs, every term stands for itself.
0 ≤ len(left) = len(right) ≤ 100,0001 ≤ len(query) ≤ 100,000A chain of 100,000 pairs can make one group of 100,001 words. If a smaller word has to travel along the chain one pair at a time, that takes about 100,000 passes over the pairs, which is 10,000,000,000 steps. You need a structure that merges whole groups.