Answer Reachability Queries on an Undirected Graph
Trees & GraphsAuto-graded · 18 test casesLast updated
Build connected components from an edge list with Union-Find, then answer many connectivity queries quickly.
You are given an undirected graph whose vertices are numbered 1 through n. A list edges describes the graph, where each element [u, v] is an undirected edge joining vertices u and v. You are also given a list queries, where each element [a, b] asks whether vertex a and vertex b lie in the same connected component of the graph.
Return a list of booleans, one per query, in the same order as the queries. For each query [a, b], the corresponding entry is True if some path of edges joins a and b, and False otherwise.
Details to respect:
- A vertex is always considered connected to itself, so any query with
a == bmust returnTrue, even if that vertex has no edges at all. - The graph may contain duplicate edges and self-loops (
[x, x]); these must not change any answer. - Vertices with no incident edges are isolated; two distinct isolated vertices are not connected.
- If
queriesis empty, return an empty list. - The answers must be correct even if the graph is disconnected and the queries are numerous, so a fresh traversal per query is too slow.
Constraints
1 <= n <= 1000000 <= len(edges) <= 2000000 <= len(queries) <= 200000- Every edge and query contains exactly two integers, each in the range
1..n. - Each vertex may appear in any number of edges.
Examples
Example 1
Input: answer_connectivity_queries(5, [[1, 2], [2, 3], [4, 5]], [[1, 3], [1, 4], [4, 5], [3, 3]])
Output: [True, False, True, True]
Example 2
Input: answer_connectivity_queries(4, [[1, 2], [2, 3], [1, 3]], [[1, 3], [1, 4], [2, 2]])
Output: [True, False, True]
Hints
Hint 1
Connectivity is transitive, so the graph splits into components; precompute which component each vertex belongs to and each query becomes a single comparison.
Hint 2
Union-Find (Disjoint Set Union) is a natural fit: merge the endpoints of every edge, then check whether both endpoints of a query share a root.
Hint 3
Use path compression in `find` and attach the shallower tree under the deeper one in `union` (union by rank/size) to keep operations near-constant; guards like `a == b` or a query with a single vertex still work through `find`, since a lone vertex is its own root.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the graph's connectivity as an equivalence relation and maintain it with a Disjoint Set Union (Union-Find) structure. Initialize each vertex 1..n as its own set (index 0 is a harmless unused slot that keeps indexing 1-based). For every edge [u, v], merge the sets containing u and v. After all edges are processed, two vertices are in the same component exactly when they have the same root, so each query [a, b] reduces to find(a) == find(b).
Two optimizations keep operations fast:
- Path compression: in
find, after locating the root, re-point every vertex along the path directly at the root. - Union by rank: attach the root with the smaller rank under the root with the larger rank; on ties, pick one and increment its rank. Rank is only an upper bound on tree height, so compression never needs to update it.
Why it is correct
The invariant is that two vertices share a root if and only if a path of processed edges connects them. Initially every vertex is its own root, matching a graph with no edges. Each union(u, v) merges exactly the two components that the edge joins, leaving all others untouched. Path compression only re-points vertices toward the root of their own tree, so it never changes set membership. Thus at the end, find(a) == find(b) is true precisely when a and b are connected.
Duplicate edges and self-loops are handled by the early return when the two roots already match; isolated vertices remain their own roots, so a query of a vertex with itself returns True and two distinct isolated vertices return False.
Complexity
Let m = len(edges) and q = len(queries). With both optimizations, each union and each find costs amortized O(α(n)), where α is the inverse Ackermann function (effectively a small constant). Total time is O(n + (m + q) · α(n)), and space is O(n) for the parent and rank arrays plus O(q) for the output.
from typing import List
def answer_connectivity_queries(n: int, edges: List[List[int]], queries: List[List[int]]) -> List[bool]:
parent = list(range(n + 1))
rank = [0] * (n + 1)
def find(x: int) -> int:
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x: int, y: int) -> None:
root_x = find(x)
root_y = find(y)
if root_x == root_y:
return
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root_y]:
parent[root_y] = root_x
else:
parent[root_y] = root_x
rank[root_x] += 1
for u, v in edges:
union(u, v)
return [find(u) == find(v) for u, v in queries]