laura
laura

Reputation: 389

Calculating Outdegree and Indegree of Adjacency list

Question

Calculate time complexity in calculating Outdegree and Indegree of Adjacency list.

My Approach/Doubt

Let Adj[] be an array of size V where V=No. of vertices in a directed graph for representing adjacency list.

I know that ,

Outdegree of vertex u (u belongs to V) is actually the length of Adj[u]

and

Indegree of vertex u (u belongs to V) is actually the count of u in list Adj.

In both the cases , i think the time complexity should be theta (V*E)

Where V=no. of vertices

  E=no. of edges

because for calculating outdegree,we scan all vertices and under each vertices we scan all the edges of that vertices.

Then why it is Thrta (V+E)

Please correct me where i am wrong?

Thanks!

Upvotes: 2

Views: 8029

Answers (2)

Rajinder
Rajinder

Reputation: 1

we can allocate an array arr[] of size |V| and initialize its entries to zero. Then we only need to scan the lists in Adj once, incrementing arr [u] when we see u in the lists.

The values in arr[] will be the out-degrees of every vertex. This can be done in Θ (|V| + |E|) time with Θ (|V|) additional storage.

Upvotes: 0

user3064980
user3064980

Reputation:

Okay, lets say we have V vertices and E edges.
In both bidirectional and unidirectional graph, for each edge Ei, we get two Vertices V1, V2. We can easily get the direction of the edge and update the outdegree and indegree counter of a certain vertex.

Example:

Vertices: 1, 2, 3, 4
Edges: 1 -> 2, 2 -> 4, 3 -> 1, 2 -> 3
Outdegree: 0 0 0 0
Indegree: 0 0 0 0

Pass 1:
Edge 1 -> 2
Outdegree: 1 0 0 0
Indegree: 0 1 0 0

Pass 2:
Edge 2 -> 4
Outdegree: 1 1 0 0
Indegree: 0 1 0 1

Pass 3:
Edge 3 -> 1
Outdegree: 1 1 1 0
Indegree: 1 1 0 1

Pass 4:
Edge 2 -> 3
Outdegree: 1 2 1 0
Indegree: 1 1 1 1

So here, we need to run a loop through each edge and each vertex exactly once thus resulting in complexity (V + E).

Upvotes: 1

Related Questions