Airbnb | Phone screen | Lowest Common Ancestor of Two Regions

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2019-03-06Added By Anonymous
Source: Link

AirBnb questions are usually very lengthy, so in short

Given a list of string array,

In each string array, the first element consists of the rest elements.


e.g.

[Earth, South America, North America, Asia, Pacific, Africa]

[Asia, China, Korea, Japan]

[North America, USA, Canada]

[South America, Brazil, Columbia]

[Africa, Algeria, Lybia]

[China, Beijing, Shanhai]

[Japan, Tokyo, Kyoto]

[Korea, Seoul]


Given two valid elements, find its least common ancestor (LCA)

e.g.

input

[Tokyo, Kyoto]

output

Japan

input

[Beijing, Japan]

output

Asia

input

[Seoul, Africa]

output

Earth


My own solution

1function findLowestCommonTerritory(territoryList, inputs) { 2 const parents = {}; 3 territoryList.forEach(t => { 4 t.forEach((a, i) => { 5 if (i !== 0) { 6 parents[a] = t[0]; 7 } 8 }); 9 }); 10 11 const result = []; 12 for (const input of inputs) { 13 result.push(lca(parents, input[0], input[1])); 14 } 15 16 return result; 17} 18 19function lca(parents, node1, node2) { 20 const ancestors = new Set(); 21 while (node1) { 22 ancestors.add(node1); 23 node1 = parents[node1]; 24 } 25 26 while (node2 && !ancestors.has(node2)) { 27 node2 = parents[node2]; 28 } 29 return node2; 30} 31
Comments