Smallest Common Region - Problem
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 y directly, and region y contains region z directly, then region x is said to contain region z indirectly.
Note that region x also indirectly contains all regions indirectly contained 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.
It is guaranteed the smallest region exists.
Input & Output
Example 1 — Basic Hierarchy
$
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"
💡 Note:
Quebec → Canada → North America → Earth, New York → United States → North America → Earth. First common ancestor is North America.
Example 2 — Same Region
$
Input:
regions = [["Earth","North America","South America"],["North America","United States","Canada"]], region1 = "Canada", region2 = "Canada"
›
Output:
"Canada"
💡 Note:
Both regions are the same, so Canada contains itself.
Example 3 — Parent-Child Relationship
$
Input:
regions = [["Earth","North America"],["North America","United States"]], region1 = "United States", region2 = "North America"
›
Output:
"North America"
💡 Note:
North America directly contains United States, so North America is the smallest common region.
Constraints
- 1 ≤ regions.length ≤ 104
- 1 ≤ regions[i].length ≤ 20
- 1 ≤ regions[i][j].length ≤ 20
- All strings consist of English letters and spaces with at most 20 characters.
- All strings are unique.
- It is guaranteed a valid answer exists.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Region hierarchy and two target regions
2
Process
Build parent map and trace paths to root
3
Output
First common region in both paths
Key Takeaway
🎯 Key Insight: This is a classic Lowest Common Ancestor problem - build parent relationships and find where two ancestor paths first intersect
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code