LeetCode 1627: Graph Connectivity With Threshold Solution
Master LeetCode problem 1627 (Graph Connectivity With Threshold), a hard 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.
1627. Graph Connectivity With Threshold
Problem Explanation
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:
- Initialize each city as a separate component.
- For each query, check if the two cities share a common divisor greater than the threshold.
- If they do, union their components.
- After processing all queries, for each query, check if the two cities belong to the same component.
- 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)
Solution Code
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];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1627 (Graph Connectivity With Threshold)?
This page provides optimized solutions for LeetCode problem 1627 (Graph Connectivity With Threshold) 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 1627 (Graph Connectivity With Threshold)?
The time complexity for LeetCode 1627 (Graph Connectivity With Threshold) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1627 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1627 in Java, C++, or Python.