KatInterview

Answer Reachability Queries on an Undirected Graph

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsunion-findgraphdisjoint-set

Last 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 == b must return True, 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 queries is 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 <= 100000
  • 0 <= len(edges) <= 200000
  • 0 <= 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.