LeetCode 1627: Graph Connectivity With Threshold

Problem Description

Explanation:

To solve this problem, we can use the concept of Disjoint Set Union (DSU) or Union Find data structure. We will initialize each city as its own component. Then, for each pair of cities in the queries, we will check if they share a common divisor greater than the threshold. If they do, we will union their components. Finally, for each query, we will check if the two cities belong to the same component.

Algorithm:

  1. Initialize each city as a separate component.
  2. For each query, check if the two cities share a common divisor greater than the threshold.
  3. If they do, union their components.
  4. After processing all queries, for each query, check if the two cities belong to the same component.
  5. If they do, mark the query as connected; otherwise, mark it as not connected.

Time Complexity: O(n * log(n) + queries), where n is the number of cities and queries is the number of queries. Space Complexity: O(n)

Solutions

class Solution {
    public List<Boolean> areConnected(int n, int threshold, int[][] queries) {
        List<Boolean> result = new ArrayList<>();
        int[] parent = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            parent[i] = i;
        }
        
        for (int i = threshold + 1; i <= n; i++) {
            for (int j = 2 * i; j <= n; j += i) {
                union(parent, i, j);
            }
        }
        
        for (int[] query : queries) {
            result.add(find(parent, query[0]) == find(parent, query[1]));
        }
        
        return result;
    }
    
    private void union(int[] parent, int x, int y) {
        int rootX = find(parent, x);
        int rootY = find(parent, y);
        if (rootX != rootY) {
            parent[rootX] = rootY;
        }
    }
    
    private int find(int[] parent, int x) {
        if (parent[x] != x) {
            parent[x] = find(parent, parent[x]);
        }
        return parent[x];
    }
}

Loading editor...