Formatted question description: https://leetcode.ca/all/1257.html

1257. Smallest Common Region

Level

Medium

Description

You are given some lists of regions where the first region of each list includes all other regions in that list.

Naturally, if a region X contains another region Y then X is bigger than Y. Also by definition a region X contains itself.

Given two regions region1, region2, find out the smallest region that contains both of them.

If you are given regions r1, r2 and r3 such that r1 includes r3, it is guaranteed there is no r2 such that r2 includes r3.

It’s guaranteed the smallest region exists.

Example 1:

Input:
regions = [["Earth","North America","South America"],
["North America","United States","Canada"],
["United States","New York","Boston"],
["Canada","Ontario","Quebec"],
["South America","Brazil"]],
region1 = "Quebec",
region2 = "New York"
Output: "North America"

Constraints:

  • 2 <= regions.length <= 10^4
  • region1 != region2
  • All strings consist of English letters and spaces with at most 20 letters.

Solution

Use a map to store each region and its parent. Say region X is region Y’s parent if region X directly includes region Y. Also say region X is region Z’s ancestor if there exists a path such that X -> X1 -> X2 -> … -> Xn -> Xn+1 -> … -> Z where “->” represents a parent-child relation (that is to say, Xn is a parent of Xn+1).

Use a set to store region1 and all its ancestors. Then for region2, find the lowest ancestor that is in the set, which is the lowest ancestor of region1. Return the lowest ancestor.

class Solution {
    public String findSmallestRegion(List<List<String>> regions, String region1, String region2) {
        Map<String, String> map = new HashMap<String, String>();
        for (List<String> list : regions) {
            int size = list.size();
            String first = list.get(0);
            for (int i = 1; i < size; i++)
                map.put(list.get(i), first);
        }
        Set<String> set = new HashSet<String>();
        String str1 = region1;
        while (str1 != null) {
            set.add(str1);
            str1 = map.get(str1);
        }
        String str2 = region2;
        while (!set.contains(str2))
            str2 = map.get(str2);
        return str2;
    }
}

All Problems

All Solutions