Hi,

I came with this subproblem while working on something else. Can someone help me understand if it's solvable problem ?

Difficulty: Hard

Design a data structure that maintains a directed graph. A node with node_id=0 is created by default, having no edges. The data-structure supports following queries:

Create() : Create a new node, with node_id assigned from an auto-incrementing counter. Add a directed edge from node-0 to this new node; return node_id of new node.

Add(x, y) : Add a directed edge from node-x to node-y. Ignore if there is already an edge from x to y.

Delete(x, y) : Delete the directed edge from node-x to node-y, and also delete all the nodes (and their edges) of graph which are not reachable from node-0. return the list of deleted edges and nodes.

All APIs should work in amortized complexity O(log(N)) , where N is the number of nodes in the graph at the time of query.

Auto comment: topic has been updated by saharshluthra (previous revision, new revision, compare).Corrected.

Auto comment: topic has been updated by saharshluthra (previous revision, new revision, compare).Lets store two sets for every node V with edges (from; V) and (V; to).

Adding edge U->V: insert V to U's set of "to" vertices and U to V's set of "from" vertices.

Removing U->V: delete same vertices and go recursively to V, if |V's "from" set| = 0.

Assuming From(x) represents the set of all nodes reachable to x and To(x) represents the set of all nodes node-x can reach.

It has two problems:

Doesn't satisfy time complexity requirement. Consider the query set: {create(); create(); create(); create(); create();.. N times ; add(1,2); add(2,3); add(3,4); add(4,5); ....N-1 times} Time complexity = N^2

Handler of deletion is wrong. What you are suggesting works only in acyclic graph.

Garbage collector?

Nah, unless you want $$$O(N+M)$$$ for operations of type 3 — GC has scheduled passes that erase nodes. It also doesn't forbid duplicate edges.

ok