Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What is the time complexity and space complexity of traversing a graph?


Asked by Brock Schmitt on Dec 13, 2021 FAQ



Time complexity: O (V + E), where V is the number of vertices and E is the number of edges in the graph. Space Complexity: O (V). Solution: This will happen by handling a corner case. The above code traverses only the vertices reachable from a given source vertex.
Keeping this in consideration,
By definition, the Space complexity of an algorithm quantifies the amount of space or memory taken by an algorithm to run as a function of the length of the input. While Time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the input.
In fact, The complexity of an algorithm f (N) provides the running time and / or storage space needed by the algorithm with respect of N as the size of input data. Space complexity of an algorithm represents the amount of memory space needed the algorithm in its life cycle.
Next,
Time Complexity of the Tree Traversals In the general case, all the traversal algorithms visit each node in a tree exactly once. Therefore the time complexity of all the traversal algorithms would be when a tree contains nodes.
Consequently,
This kind of graph is a dense graph. Time complexity will be O(E) Consider an other example , where the number of vertices is very much larger than the number of edges. This kind of graph is a sparsely connected graph.