Directed vs Undirected
- Directed: Edge A→B ≠ B→A (dependencies, web pages)
- Undirected: Edge A-B means both A→B and B→A (roads, friends)
- Weighted: Edges have costs (GPS, network routing)
- DAG: Directed Acyclic Graph (topological sort)
Representations (choose wisely)
- Adjacency List: vector<vector<int>> — sparse graphs O(V+E)
- Adjacency Matrix: int[][] — dense graphs, O(1) edge lookup
- Edge List: vector<pair> — sorting-based algorithms (Kruskal)
- Most interview problems → adjacency list
Efficiently groups elements into sets and checks if two elements are in the same set. O(α(n)) ≈ O(1) amortized with path compression + union by rank.
Select BFS or DFS to explore the same 7-node graph from node A. BFS uses a queue (frontier = purple, level-by-level). DFS uses a stack (dive deep first, backtrack). Notice how BFS finds shortest paths while DFS may take longer routes first.
🧠 Under the Hood
Graphs are stored as adjacency lists for interview problems because most real graphs are sparse (E ≪ V²). An adjacency matrix wastes O(V²) memory storing zeros. Both representations give the same asymptotic BFS/DFS results, but list traversal is faster in practice for sparse graphs.