Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is time complexity for BFS/DFS not simply O(E) instead of O(E+V)?

I know there's a similar question in stack overflow, where one person has asked, why time complexity of BFS/DFS is not simply O(V).

The appropriate answer given was that E can be as large as V^2 in case of complete graph, and hence it is valid to include E in time complexity.

But, if V cannot be greater than E+1. So, in that case not having V in the time complexity, should work?

like image 645
Sandy Avatar asked Nov 05 '14 05:11

Sandy


People also ask

What is time complexity of BFS and DFS?

Time Complexity of BFS = O(V+E) where V is vertices and E is edges. Time Complexity of DFS is also O(V+E) where V is vertices and E is edges.

Why time complexity of DFS is V E?

For a directed graph, the sum of the sizes of the adjacency lists of all the nodes is E(total number of edges). So, the complexity of DFS is O(V + E). Show activity on this post. It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1.

Why time complexity of BFS is O v e?

Time complexity to go over each adjacent edges of a vertex is say O(N) , where N is number of adjacent edges. So for V number of vertices time complexity becomes O(V*N) = O(E) , where E is the total number of edges in the graph.

What is the time complexity of the DFS algorithm?

Complexity Of Depth-First Search Algorithm If the entire graph is traversed, the temporal complexity of DFS is O(V), where V is the number of vertices.


2 Answers

If it is given that E = kV + c, for some real constants k and c then,
O(E + V) = O(kV + c + V) = O(V) = O(E) and your argument is correct.

An example of this is trees.

In general (i.e., without any prior information), however, E = O(V^2), and thus we cannot do better than O(V^2).

Why not write just O(E) always?

EDIT: The primary reason for always writing O(E + V) is to avoid ambiguity.

For example, there might be cases when there are no edges in the graph at all (i.e. O(E) ~ O(1)). Even for such cases, we'll have to go to each of the vertex (O(V)), we cannot finish in O(1) time.

Thus, only writing O(E) won't do in general.

like image 170
axiom Avatar answered Oct 11 '22 01:10

axiom


V has to be included because both BFS and DFS rely on arrays of size |V| to track which vertices have been processed/discovered/explored (whatever the case may be). If a graph has 0 edges and 100000 vertices, such arrays will still take more time to initialize than they would if there were only 5 vertices. Thus, the time complexities of BFS and DFS scale on |V|.

like image 37
A K Avatar answered Oct 11 '22 01:10

A K