Graph Connectivity With Threshold LeetCode solution in Python
1# Runtime: 881 ms (Top 97.89%) | Memory: 49.3 MB (Top 35.92%)2class Solution:3def areConnected(4self, n: int, threshold: int, queries: List[List[int]]5) -> List[bool]:6parent = list(range(n + 1))78def find(i):9if parent[i] != i:10parent[i] = find(parent[i])11return parent[i]1213def union(i, j):14parent[find(i)] = find(j)1516if not threshold:17return [True] * len(queries)18for i in range(1, n + 1):19for j in range(2 * i, n + 1, i):20if i > threshold:21union(i, j)22return [find(i) == find(j) for i, j in queries]