|
| 1 | +/** |
| 2 | + * 1257. Smallest Common Region |
| 3 | + * https://leetcode.com/problems/smallest-common-region/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given some lists of regions where the first region of each list directly contains |
| 7 | + * all other regions in that list. |
| 8 | + * |
| 9 | + * If a region x contains a region y directly, and region y contains region z directly, then |
| 10 | + * region x is said to contain region z indirectly. Note that region x also indirectly contains |
| 11 | + * all regions indirectly containd in y. |
| 12 | + * |
| 13 | + * Naturally, if a region x contains (either directly or indirectly) another region y, then x |
| 14 | + * is bigger than or equal to y in size. Also, by definition, a region x contains itself. |
| 15 | + * |
| 16 | + * Given two regions: region1 and region2, return the smallest region that contains both of them. |
| 17 | + * |
| 18 | + * It is guaranteed the smallest region exists. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {string[][]} regions |
| 23 | + * @param {string} region1 |
| 24 | + * @param {string} region2 |
| 25 | + * @return {string} |
| 26 | + */ |
| 27 | +var findSmallestRegion = function(regions, region1, region2) { |
| 28 | + const map = new Map(); |
| 29 | + |
| 30 | + for (const region of regions) { |
| 31 | + const parent = region[0]; |
| 32 | + for (let i = 1; i < region.length; i++) { |
| 33 | + map.set(region[i], parent); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + const path1 = getPath(region1); |
| 38 | + const path2 = getPath(region2); |
| 39 | + const set = new Set(path1); |
| 40 | + |
| 41 | + for (const ancestor of path2) { |
| 42 | + if (set.has(ancestor)) { |
| 43 | + return ancestor; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + function getPath(region) { |
| 48 | + const path = []; |
| 49 | + let current = region; |
| 50 | + while (current) { |
| 51 | + path.push(current); |
| 52 | + current = map.get(current); |
| 53 | + } |
| 54 | + return path; |
| 55 | + } |
| 56 | +}; |
0 commit comments