Smallest Common Region
The problem is about finding the smallest region that contains both region1
and region2
, given a list of regions where each region may contain other regions.
Python solution:
|
|
Explanation
Creating Parent Map: We start by creating a mapping of each subregion to its parent region using the
parent
dictionary. We iterate through theregions
, and for eachsubregion
, we map it to the parent region (first element in the list).Finding Path to Region1: Next, we need to find the path from
region1
to the root region (e.g., “Earth”). We use a setpath_to_region1
to store all the regions in this path, includingregion1
itself.Finding Smallest Common Region: Finally, we use the path from step 2 to find the smallest common region that contains both
region1
andregion2
. We iterate through the parents ofregion2
until we find a region that is also in the path toregion1
. This common region is the smallest region that contains bothregion1
andregion2
, so we return it.