Skip to content

Files

Latest commit

 

History

History
74 lines (59 loc) · 3.06 KB

File metadata and controls

74 lines (59 loc) · 3.06 KB

< Previous                  Next >

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.

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.

Related Topics

[Array] [Hash Table] [String] [Tree] [Depth-First Search] [Breadth-First Search]

Similar Questions

  1. Lowest Common Ancestor of a Binary Search Tree (Easy)
  2. Lowest Common Ancestor of a Binary Tree (Medium)

Hints

Hint 1 Try to model the problem as a graph problem.
Hint 2 The given graph is a tree.
Hint 3 The problem is reduced to finding the lowest common ancestor of two nodes in a tree.