![]() |
VOOZH | about |
Given a 2D array regions[][] where the first region of each array includes all other regions in that array and two more regions r1 and r2, the task is to return the smallest region that contains both of them.
Note: 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.
Examples:
Input: regions[][] = {{"Earth", "North America", "South America"}, {"North America", "United States", "Canada"}, {"United States", "New York", "Boston"}, {"Canada", "Ontario", "Quebec"}}, r1 = "Quebec", r2 = "New York"
Output: North America
Explanation:
- The first array states that "North America" and "South America" are in region "Earth".
- The second array states that "United States" and "Canada" are in region "North America".
- The third array states that "New York" and "Boston" are in region "United States".
- The fourth array states that "Ontario" and "Quebec" are in region "Canada".
- So, "New York" is in "United States" which in turn is in "North America" and "Quebec" is in "Canada" which in turn is in "United States" which is also in "North America". Therefore, both lies in "North America".
Input: regions[][] = {{"Earth", "North America", "South America"}, {"North America", "United States", "Canada"}, {"United States", "New York", "Boston"}, {"Canada", "Ontario", "Quebec"}, {"South America", "Brazil"}}, r1 = "Canada", r2 = "South America" Output: Earth
Approach: To solve the problem, follow the below idea:
The task is to find the smallest common region that contains two specified regions from a list of hierarchical regions. The problem can be solved using hashmaps to store the parent child relationship and then tracing the path for the common region.
Step-by-Step Approach:
Below is the implementation of the above approach:
North America Earth
Time Complexity: O(N + H), where N is the total number of regions and H is the height of the deepest path between the two specified regions.
Auxiliary Space: O(N + H)