When it comes to finding connected components in a graph we can use DFS or DSU. Does there exist an algorithm which is stable to a changing graph, where node can be added, edge can be removed, node can be removed. Eg. If we add a node to a graph and we use DSU(with path compression and rank optimization), we can change the count of connected components in O(1) [Average time] by just doing the Union operation on the newly formed edge. But in case an edge is removed, we have to run the whole algorithm again.
Is there an algorithm stable for above scenario?
As you say, adding new edges and nodes is still efficient thanks to the union operation. The problematic cases are edge removals (node removals translate to the removals of its edges).
When you remove an edge, there are two possible outcomes: the connected component remains the same, or a new one is created (the edge was joining two subsets that now are disconnected). That already gives us some good news: we only have to worry about the subset where the edge belonged.
So, after you remove the edge
(A,B), start two DFS, one fromAand the other fromBand interleave them.Here you have some Python-like pseudocode for this algorithm:
You'll find other alternatives in the page of wikipedia about dynamic connectivity, but this one seemed simple and fast enough.