Skip to content

Time & Space Complexity

Understanding the performance characteristics of graph algorithms is critical for choosing the right approach in interviews.


AlgorithmTime ComplexitySpace ComplexityNotes
BFSO(V + E)O(V)Queue + visited set
DFSO(V + E)O(V)Stack/recursion + visited
DijkstraO((V + E) log V)O(V)With min-heap
Bellman-FordO(V × E)O(V)Handles negative weights
Floyd-WarshallO(V³)O(V²)All-pairs shortest path
Topological SortO(V + E)O(V)BFS/DFS based
Union-FindO(α(N)) ≈ O(1)O(N)With path compression
Kruskal’s (MST)O(E log E)O(V)Sorting edges dominates
Prim’s (MST)O((V + E) log V)O(V)With min-heap

α(N) is the inverse Ackermann function — practically constant for all realistic inputs (grows so slowly that for N = 10⁶⁰⁰, α(N) ≤ 5).


For a graph with V vertices and E edges:

OperationAdjacency MatrixAdjacency List
BFS/DFS TraversalO(V²)O(V + E)
Find Edge (u, v)O(1)O(degree(v))
All Neighbors of vO(V)O(degree(v))
Add VertexO(V²)O(1)
Add EdgeO(1)O(1)
Remove EdgeO(1)O(degree(v))
SpaceO(V²)O(V + E)

💡 Key Insight: For most interview problems (sparse graphs with E ≈ V), the adjacency list wins on time AND space. The matrix only makes sense for dense graphs where E ≈ V².


Sparse Graph (E ≈ V): Dense Graph (E ≈ V²):
Memory: O(V + E) ≈ O(V) Memory: O(V²)
Traversal: O(V + E) ≈ O(V) Traversal: O(V²)
→ Use Adjacency List → Matrix is acceptable

Real-world densities:

Graph TypeTypical DensityE ~Best Representation
Social networkVery sparseV × avg_degreeAdjacency List
Web graphSparseV × ~50 linksAdjacency List
Road networkSparseV × ~4 neighborsAdjacency List
Complete tournamentDenseV²/2Adjacency Matrix

+------------------+----------------+-------------------+
| Problem | Best Algorithm | Complexity |
+------------------+----------------+-------------------+
| Shortest path | BFS | O(V + E) |
| (unweighted) | | |
+------------------+----------------+-------------------+
| Shortest path | Dijkstra | O((V+E) log V) |
| (no neg weights) | | |
+------------------+----------------+-------------------+
| Shortest path | Bellman-Ford | O(V × E) |
| (neg weights) | | |
+------------------+----------------+-------------------+
| All-pairs | Floyd-Warshall | O(V³) |
+------------------+----------------+-------------------+
| Cycle detection | DFS | O(V + E) |
+------------------+----------------+-------------------+
| Topological sort | Kahn's BFS | O(V + E) |
+------------------+----------------+-------------------+
| Connected comps | DFS/BFS/UF | O(V + E) |
+------------------+----------------+-------------------+
| MST | Kruskal/Prim | O(E log E) |
+------------------+----------------+-------------------+

With a solid understanding of complexity, dive into Graph Traversal Algorithms — BFS and DFS.