You are given some lists of regions where the first region of each list
directly contains all other regions in that list.
If a region x contains a region ydirectly , and region y contains region zdirectly , then region x is said to contain region zindirectly. Note that region x also indirectly contains all regions
indirectly containd in y.
Naturally, if a region x contains (either directly or indirectly) another region y, then x is bigger than or equal to y in size. Also, by definition, a region x contains itself.
Given two regions: region1 and region2, return the smallest region that contains both of them.
Build a parent map for each region. For both region1 and region2, trace their ancestors up to the root. The first common ancestor is the answer (lowest common ancestor in a tree).
import java.util.*;
classSolution {
public String findSmallestRegion(List<List<String>> regions, String region1, String region2) {
Map<String, String> parent =new HashMap<>();
for (List<String> reg : regions) {
for (int i = 1; i < reg.size(); ++i)
parent.put(reg.get(i), reg.get(0));
}
Set<String> path =new HashSet<>();
while (region1 !=null) {
path.add(region1);
region1 = parent.get(region1);
}
while (region2 !=null) {
if (path.contains(region2)) return region2;
region2 = parent.get(region2);
}
return"";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
deffindSmallestRegion(self, regions, region1, region2):
parent = {}
for reg in regions:
for r in reg[1:]:
parent[r] = reg[0]
path = set()
while region1:
path.add(region1)
region1 = parent.get(region1)
while region2:
if region2 in path:
return region2
region2 = parent.get(region2)
return""