Back to the 2023 paper

Module 3: Graph and Tree Algorithms

20232m

What is the time complexity of topological sorting of a directed acyclic graph (DAG) with VV vertices and EE edges using Depth-First Search (DFS)?
(i) O(V2)O(V^2)
(ii) O(E2)O(E^2)
(iii) O(V+E)O(V+E)
(iv) O(V.E)O(V.E)

Worked SolutionAI Assisted

Answer: (iii) O(V+E)O(V+E)

Explanation:

  • Topological sort via DFS: run DFS on DAG, push vertex onto stack when finished (post-order), then reverse. Each vertex visited once, each edge examined once.
  • Time = O(V)O(V) for initialization + O(V+E)O(V+E) for DFS = O(V+E)O(V+E).
  • Kahn's algorithm (BFS with indegree) is also O(V+E)O(V+E).
  • O(V2)O(V^2) / O(E2)O(E^2) would be for adjacency matrix without adjacency lists; with adjacency list it's linear.

Correct choice: (iii) O(V+E)O(V+E)

Similar questions

Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.