Alive-Node Graph Simulator with Gated Edge Insertion
Data Structure DesignAuto-graded · 20 test casesLast updated
Simulate a sequence of node toggles, edge edits, and connectivity queries on an undirected graph where only alive nodes count and edges are only added between alive endpoints.
You are given a graph with n nodes labeled 0 to n - 1 and a list of operations to run in order. Each node is either alive or dead. The graph is undirected and starts with no edges, and every node starts alive.
Implement a function that processes the operations one at a time and returns one result per operation.
Operations
| Operation | Arguments | Effect | Result |
|---|---|---|---|
"activate" | [i] | Mark node i alive. | None |
"deactivate" | [i] | Mark node i dead. | None |
"connect" | [u, v] | Record the edge {u, v} only if both u and v are alive at this moment. Otherwise do nothing. | None |
"disconnect" | [u, v] | Remove the edge {u, v} if it is recorded, whether or not its endpoints are alive. Do nothing if it is not recorded. | None |
"isConnected" | [u, v] | Whether u and v are linked by a path that uses only alive nodes. | bool |
"countComponents" | [] | Number of connected components in the subgraph formed by alive nodes and the recorded edges between them. | int |
Rules
- Edges are undirected:
{u, v}and{v, u}are the same edge. Connecting an edge that is already recorded changes nothing. - Deactivating a node does not erase its recorded edges. They are simply ignored while either endpoint is dead, and they take effect again if that node is reactivated.
- A
connectthat is skipped because an endpoint was dead leaves no trace. Reactivating the node later does not create that edge. isConnected(u, v)isFalseifuorvis dead.isConnected(u, u)isTrueexactly whenuis alive.- Self-loops may be recorded and do not affect connectivity.
- Activating an already-alive node or deactivating an already-dead node changes nothing.
countComponentscounts only alive nodes (an alive node with no usable edges is its own component). If every node is dead, the answer is0.- If an unknown operation name appears, raise a
ValueError.
The output list has the same length as operations, with None for operations that return nothing.
Constraints
1 <= n <= 100000operationsandargumentshave the same length, at most100000.- All node indices are valid, in the range
0..n-1. arguments[k]is[]forcountComponents, a single-element list foractivate/deactivate, and a two-element list for the others.
Examples
Example 1
Input: simulate_alive_graph(5, ['connect', 'connect', 'connect', 'isConnected', 'countComponents', 'deactivate', 'isConnected', 'countComponents'], [[0, 1], [1, 2], [3, 4], [0, 2], [], [1], [0, 2], []])
Output: [None, None, None, True, 2, None, False, 3]
Example 2
Input: simulate_alive_graph(3, ['countComponents', 'deactivate', 'countComponents', 'activate', 'connect', 'isConnected'], [[], [1], [], [1], [0, 1], [0, 1]])
Output: [3, None, 2, None, None, True]
Hints
Hint 1
Keep two pieces of state that are cheap to update: a per-node alive flag and a set of recorded edges stored as normalized (min, max) pairs.
Hint 2
A union-find cannot undo merges, and both disconnect and deactivate are deletions. Derive connectivity from the stored edges when a query arrives instead of maintaining it online.
Hint 3
For a query, build a union-find over only the edges whose endpoints are both alive. The component count is the number of alive nodes minus the number of successful unions. Use a dirty flag so consecutive queries share one rebuild.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store only two pieces of state, both cheap to update:
- an
alivearray, and - a set of recorded edges, each normalized to
(min(u, v), max(u, v))so that direction does not matter and duplicates collapse.
Every mutation is then O(1):
connectchecks the alive flags at call time and adds the edge only if both endpoints are alive.disconnectusesdiscard, so removing an absent edge is harmless.activateanddeactivatejust flip a flag. Edges stay in the set, which gives the "lazy" behavior: they are ignored while an endpoint is dead and come back when it is reactivated.
For queries, connectivity is computed from scratch over the alive subgraph with a disjoint-set union (DSU):
- Reset every node to be its own parent.
- Start the component count at the number of alive nodes.
- For each stored edge whose endpoints are both alive, union them. Each successful union decreases the count by one.
countComponents returns that count. isConnected(u, v) returns False if either node is dead, otherwise it compares the DSU roots of u and v.
A dirty flag is set by any mutation and cleared by a rebuild, so several queries in a row with no mutation between them share a single rebuild.
Why it is correct
- Mutations change exactly the state the rules describe, including the "skipped connect leaves no trace" rule, because a skipped connect never touches the edge set.
- At query time the DSU is built from exactly the edges with both endpoints alive, so its components are the components of the alive induced subgraph.
- Starting with one singleton per alive node, each successful union merges two distinct components, so the final count is
alive_count - successful_unions. - Dead nodes never take part in a union and are not counted. A self-loop yields equal roots, so it never changes anything.
A DSU cannot be maintained online here because it cannot undo merges, and both disconnect and deactivate are deletions. Treating the edge set as the source of truth and rebuilding when needed avoids that problem.
Complexity
Let E be the number of recorded edges.
- Mutations: O(1) each.
- A query after a mutation: O(n + E * alpha(n)) for the rebuild.
- Repeated queries with no mutation between them: near O(1) each.
- Worst case, when mutations and queries alternate: O(Q * (n + E)).
- Space: O(n + E).
This is the simple, verifiable baseline. For heavier workloads, the offline approach (segment tree over time with a rollback DSU) gives O(Q log Q log n), and the online approach (Holm-de Lichtenberg-Thorup) gives polylogarithmic amortized updates.
Reference solution
from typing import List
def simulate_alive_graph(n: int, operations: List[str], arguments: List[List[int]]) -> List[object]:
alive = [True] * n
edges = set()
results: List[object] = []
parent = list(range(n))
components = 0
dirty = True
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def rebuild() -> None:
nonlocal components, dirty
for i in range(n):
parent[i] = i
components = sum(alive)
for u, v in edges:
if alive[u] and alive[v]:
ru, rv = find(u), find(v)
if ru != rv:
parent[ru] = rv
components -= 1
dirty = False
for op, args in zip(operations, arguments):
if op == "activate":
alive[args[0]] = True
dirty = True
results.append(None)
elif op == "deactivate":
alive[args[0]] = False
dirty = True
results.append(None)
elif op == "connect":
u, v = args
if alive[u] and alive[v]:
edges.add((min(u, v), max(u, v)))
dirty = True
results.append(None)
elif op == "disconnect":
u, v = args
edges.discard((min(u, v), max(u, v)))
dirty = True
results.append(None)
elif op == "isConnected":
u, v = args
if not alive[u] or not alive[v]:
results.append(False)
else:
if dirty:
rebuild()
results.append(find(u) == find(v))
elif op == "countComponents":
if dirty:
rebuild()
results.append(components)
else:
raise ValueError("unknown operation")
return results