Union-find or repeated graph traversal for connectivity queries as edges keep arriving?
answer
- When do the edges arrive
- Queries between mutations, or after all of them
- A traversal per query repeats O(V+E)
- Merging only, never splitting
- Amortized inverse Ackermann, not strictly constant
basics
~20 sThe interleaving decides, not the graph. If edges arrive between queries, union-find answers each merge and check in amortized near-constant time. If the edge set is known up front, one traversal labels every component and each check is a label comparison.
solid answer
~50 sAsk when the edges arrive relative to the questions. In the online case — a warehouse network where links are added over time and "are these two connected yet?" is asked in between — re-running a traversal per query costs O(V+E) *every time*, so q queries cost O(q(V+E)). Union-find turns each merge and each check into an amortized near-constant operation (inverse Ackermann, with union by rank and path compression), giving about O(m) for m operations overall. In the offline case — all edges known before any question — a single traversal assigning a component label to every vertex costs O(V+E) once, after which each query is a label comparison; that is simpler code and needs no extra structure. Two things push you back to traversal even when queries interleave: you need the actual route between the two nodes, or edges can be removed as well as added.
go deeper
Know that repeating a graph traversal for every connectivity question re-walks the whole graph each time, and that a structure exists for grouping nodes into components as links appear.
Explain the selection by interleaving: edges arriving between queries favour disjoint-set union at amortized near-constant cost, while a fixed edge set favours one labelling pass followed by constant-time comparisons.
Demonstrate the qualifiers that matter in production: no cheap deletion, no path reconstruction, and a rebuild strategy for when links are decommissioned. Say what you would do the first time a lane is removed.
Own the call between the simple labelling pass and an extra structure. A specialised container that only one engineer understands is a real cost, and the static solution is often defensible far longer than people assume.
## The selection axis is time, not topology Both candidates answer the same question — are these two nodes in the same connected component? — and both are correct. What separates them is *when the edges arrive relative to the queries*, and that is the axis a candidate is expected to name out loud. Picture a logistics network. Warehouses are nodes; a new transfer lane between two of them is an edge. Two very different products sit on this data: - **Offline / static.** The lane table is loaded at start of day and does not change. Planners then ask thousands of "can goods reach B from A?" questions against that fixed snapshot. - **Online / incremental.** Lanes are commissioned through the day, and each commissioning is followed by connectivity checks from the routing service. ## The offline case: one traversal, then labels With all edges known, run a single sweep over the graph — repeatedly pick an unvisited vertex and explore everything reachable from it, stamping each visited vertex with the same component label. That is one O(V+E) pass in total, whatever traversal order you use. Afterwards each query is `label[a] == label[b]`, genuinely O(1). This is worth defending against the reflex to reach for a fancy structure: it is less code, it needs no extra invariant, and as a by-product you have the component sizes and membership, which reports usually want anyway. Reaching for a specialised structure when a single pass would do is a real interview mistake in the opposite direction from the usual one. The failure mode in this quadrant is running a *fresh* traversal per query: O(V+E) each, so q queries cost O(q(V+E)). On a graph with a hundred thousand edges and a thousand queries that is a hundred million edge visits to answer a thousand yes/no questions. ## The online case: disjoint-set union When edges arrive between queries, the label array from the offline trick is invalidated by every new edge — merging two components would require relabelling one of them, which is another linear pass. Disjoint-set union is exactly the structure for this: each component is represented by one element, `find(x)` returns that representative, and `union(a, b)` merges two components by linking one representative under the other. A connectivity query is `find(a) == find(b)`. With both standard optimisations — union by rank or size, so the shallower tree is attached under the deeper one, and path compression, so every traversed node is re-pointed at the representative — a sequence of m operations over n elements costs O(m · α(n)), where α is the inverse Ackermann function. That is *amortized near-constant*, not strictly O(1): the bound is on the whole sequence, and α(n) is at most a very small number for any n you will ever store. Stating it as "O(1) per operation" is the sloppy version and interviewers notice. The cost model comparison, for m edge additions and q queries: | Approach | Add an edge | One query | Total | | --- | --- | --- | --- | | Traversal per query | O(1) | O(V+E) | O(q(V+E)) | | One traversal, then labels | invalidates labels | O(1) | O(V+E) once, but static only | | Disjoint-set union | amortized ~O(1) | amortized ~O(1) | O((m+q)·α(n)) | ## What pushes you back to traversal Three requirements disqualify plain disjoint-set union even when the workload is online: 1. **You need the path, not the verdict.** Union-find knows that two nodes are in one component; it cannot tell you the route, because the representative tree is not the graph — path compression has deliberately rewired it for lookup speed. If the answer must be "yes, via these three lanes", you need a traversal, and if the lanes are weighted you need a shortest-path algorithm rather than either candidate. 2. **Edges are removed as well as added.** The structure only merges; there is no cheap split. A workload where lanes are decommissioned needs either a rebuild from the surviving edges, an offline technique that processes the whole operation sequence in a different order, or a genuinely more complex dynamic-connectivity structure. Recognising that deletion is the breaking requirement is the strongest signal a candidate can give here. 3. **The question is about something other than connectivity.** Distance, bipartiteness by traversal, cycle detection in a directed graph, ordering — union-find answers none of these directly; it answers "same component" and closely related grouping questions. ## How to narrate the choice A good answer takes about three sentences: name the interleaving ("edges and queries alternate, so the edge set is never final"), give the cost of the naive option ("a traversal per query is O(V+E) each"), and pick with the qualifier attached ("disjoint-set union, amortized near-constant per operation — assuming edges are only ever added"). That last clause is what distinguishes someone who has used the structure from someone who has memorised its name.
- Which requirement rules out disjoint-set union even though the workload is online?Edge removal. The structure merges components and has no cheap way to split one, so a decommissioned lane forces a rebuild from the surviving edges or a substantially more complex dynamic-connectivity approach. Needing the actual route between two nodes rules it out too, since the representative tree is not the graph.
- Why is "amortized near-constant" the right phrase rather than O(1)?The bound is over a whole sequence of operations, not per call: an individual find can walk a chain before path compression flattens it. And the factor is the inverse Ackermann function of n, which is tiny but not literally one. Saying O(1) overstates a guarantee the structure does not give.
- The edge set is fixed and thousands of connectivity queries follow. What do you do?One traversal that stamps a component label on every vertex, O(V+E) total, after which each query is a label comparison in constant time. It is less machinery than a specialised structure and hands you component sizes and membership for free, which reports usually need as well.
saying these in an interview costs you the question
- Runs a fresh traversal for every query
- Says union-find is always faster than traversal
- Claims union-find can return the connecting path
- Forgets that edge deletion breaks the structure
- States the cost as strictly O(1) per operation