LeetCode 1257: Smallest Common Region Solution

Master LeetCode problem 1257 (Smallest Common Region), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

To find the smallest common region between two given regions in a hierarchy, we can follow these steps:

  1. Build a map to store the parent-child relationships for each region.
  2. Find the path from the given regions to the root.
  3. Compare the two paths to find the smallest common region.

Time complexity: O(n) where n is the number of regions Space complexity: O(n) for storing the parent-child relationships

Solution Code

import java.util.*;

class Solution {
    public String findSmallestRegion(List<List<String>> regions, String region1, String region2) {
        Map<String, String> parent = new HashMap<>();
        
        for (List<String> region : regions) {
            String par = region.get(0);
            for (int i = 1; i < region.size(); i++) {
                parent.put(region.get(i), par);
            }
        }
        
        Set<String> path1 = new HashSet<>();
        String curr = region1;
        while (curr != null) {
            path1.add(curr);
            curr = parent.get(curr);
        }
        
        curr = region2;
        while (curr != null) {
            if (path1.contains(curr)) {
                return curr;
            }
            curr = parent.get(curr);
        }
        
        return null;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1257 (Smallest Common Region)?

This page provides optimized solutions for LeetCode problem 1257 (Smallest Common Region) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1257 (Smallest Common Region)?

The time complexity for LeetCode 1257 (Smallest Common Region) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1257 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1257 in Java, C++, or Python.

Back to LeetCode Solutions