Open In App

Time and Space Complexity of Depth First Search (DFS)

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Depth First Search (DFS) algorithm is used to traverse a graph. It starts with a given source node and explores as far as possible along each branch before backtracking. It mainly traverses all vertices reachable through one adjacent, then it goes to the next adjacent.

C++
DFS(graph, root):
    create a visited set
    call DFS-Visit(graph, root, visited)

DFS-Visit(graph, node, visited):
    mark node as visited
    process(node)
    
    for each neighbor of node in graph:
        if neighbor is not visited:
            DFS-Visit(graph, neighbor, visited)

Time Complexity of Depth First Search (DFS):

In DFS, we explore the graph by recursively visiting nodes. The process involves two key steps: visiting nodes and exploring their neighbors. Here’s how the time complexity works:

Node Processing – Recursive Calls:

  • In the DFS-Visit function, each node is visited exactly once.
  • The recursive calls ensure that every node is processed exactly once, so the total time in processing the nodes is proportional to the number of nodes, V, i.e., O(V).

Edge Processing – Exploring Neighbors:

  • Within DFS-Visit, for each node, we explore all of its neighbors (adjacent vertices).
  • Each edge is examined once when traversing from one node to its neighbor. In an undirected graph, each edge is checked twice (once for each endpoint), but this constant factor does not affect the overall complexity.
  • Therefore, the total time in processing the edges is proportional to the number of edges, E, i.e., O(E).

Putting It All Together:

  • Node Work: The time in processing nodes is O(V), as each node is visited exactly once.
  • Edge Work: The time in processing edges is O(E), as each edge is explored once.

Thus, the overall time complexity of DFS traversal is O(V + E), which applies in all cases (best, average, and worst).

Auxiliary Space of Depth First Search (DFS):

The auxiliary space of Depth-First Search (DFS) algorithm is O(V), where V is the number of vertices in the graph, this is due to the recursion stack or visited array.

Here's why the auxiliary space complexity is O(V):

Recursion Stack:

  • DFS uses a function call stack to track vertices.
  • Space complexity depends on the maximum recursion depth.
  • Maximum depth in a graph with V vertices is O(V).

Visited Array:

  • Uses a visited array to mark visited vertices.
  • Size equals the number of vertices (V).

Therefore, the auxiliary space complexity of DFS is dominated by the recursion stack and the visited array, both of which require O(V) space, making the overall space complexity O(V).


Next Article
Practice Tags :

Similar Reads