July 31, 2022

1257. Smallest Common Region

1257. Smallest Common Region

class Solution {
    public String findSmallestRegion(List<List<String>> regions, String region1, String region2) {
        Map<String, String> map = new HashMap<>();
        for (List<String> region : regions) {
            String parentRegion = region.get(0);
            for (int i = 1; i < region.size(); i++) {
                map.put(region.get(i), parentRegion);
            }
        }
        Set<String> set = new HashSet<>();
        while (region1 != null) {
            set.add(region1);
            region1 = map.get(region1);
        }
        
        while (region2 != null) {
            if (set.contains(region2)) {
                return region2;
            } else {
                region2 = map.get(region2);
            }
        }
        return null;
    }
}
comments powered by Disqus