Skip to main content

πŸ—ΊοΈ Graphs

One-line summary: Nodes connected by edges β€” BFS for shortest path, DFS for connectivity/cycle, topological sort for dependencies, Union-Find for dynamic connectivity.


Enhanced Visualization​

Enhanced Graph Algorithms Visualization Interactive demonstration of BFS, DFS, and Dijkstra's algorithm with path finding and performance analysis

Graph Traversal Overview Graph Traversal GIF

Core Graph Concepts​

The enhanced animation above demonstrates three fundamental graph algorithms:

πŸ”΅ Breadth-First Search (BFS)​

  • Strategy: Explores nodes level by level using a queue
  • Path: A β†’ B β†’ C β†’ F (shortest in unweighted graphs)
  • Time: O(V + E) | Space: O(V)
  • Use Cases: Shortest path, social networks, web crawling

🟣 Depth-First Search (DFS)​

  • Strategy: Explores as far as possible using recursion/stack
  • Path: A β†’ D β†’ E β†’ F (explores deeply first)
  • Time: O(V + E) | Space: O(V)
  • Use Cases: Topological sorting, cycle detection, connectivity

🟑 Dijkstra's Algorithm​

  • Strategy: Uses priority queue for weighted shortest paths
  • Path: A β†’ B β†’ E β†’ F (Distance: 7 - optimal weighted path)
  • Time: O((V + E) log V) | Space: O(V)
  • Use Cases: GPS navigation, network routing, flight planning

Graph Fundamentals​

G = (V, E). Types: directed, undirected, weighted, DAG.

Representations:

  • Adjacency List: Map<node, neighbors[]> β€” O(V+E) space β€” preferred.
  • Adjacency Matrix: matrix[u][v] β€” O(VΒ²) β€” dense graphs.

Also covers: BFS pattern, DFS pattern, topological sort, Union-Find, Dijkstra, Bellman-Ford.


Time & Space Complexity​

AlgorithmTimeSpace
BFS / DFSO(V + E)O(V)
Dijkstra (min-heap)O((V+E) log V)O(V)
Topological Sort (Kahn)O(V + E)O(V)
Union-Find (with compression)O(Ξ±(n)) per opO(n)

Common Patterns​

BFS (Shortest Path)​

function bfs(graph, start) {
const visited = new Set([start]),
queue = [start];
while (queue.length) {
const node = queue.shift();
for (const nb of graph.get(node) || [])
if (!visited.has(nb)) {
visited.add(nb);
queue.push(nb);
}
}
}

DFS (Connected Components)​

function dfs(graph, node, visited = new Set()) {
visited.add(node);
for (const nb of graph.get(node) || []) if (!visited.has(nb)) dfs(graph, nb, visited);
}

Topological Sort (Kahn's BFS)​

function topoSort(n, edges) {
const inDeg = new Array(n).fill(0),
adj = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
adj[b].push(a);
inDeg[a]++;
}
const queue = [],
order = [];
for (let i = 0; i < n; i++) if (!inDeg[i]) queue.push(i);
while (queue.length) {
const node = queue.shift();
order.push(node);
for (const nb of adj[node]) if (--inDeg[nb] === 0) queue.push(nb);
}
return order.length === n ? order : []; // empty = cycle
}

Union-Find​

const parent = Array.from({ length: n }, (_, i) => i);
function find(x) {
return parent[x] === x ? x : (parent[x] = find(parent[x]));
}
function union(x, y) {
parent[find(x)] = find(y);
}

Pitfalls​

  • Forgetting to mark visited before enqueuing (BFS) β€” causes duplicates
  • Cycle detection: in undirected graph pass parent to DFS to avoid false positives
  • Topological sort only valid on DAG β€” if cycle exists, output length < n

Practice Problems​

ProblemDifficultySolution
LC 200 β€” Number of IslandsMedium
LC 207 β€” Course ScheduleMedium
LC 210 β€” Course Schedule IIMedium
LC 323 β€” Number of Connected ComponentsMedium
LC 127 β€” Word LadderHard
LC 743 β€” Network Delay Time (Dijkstra)Medium
LC 684 β€” Redundant Connection (Union-Find)Medium
CC β€” Grid Escape (GRIDECP)Medium
CC β€” Dijkstra (DIJKST)Hard
LC 1584 β€” Min Cost to Connect All PointsMedium
LC 787 β€” Cheapest Flights Within K StopsMedium
LC 133 β€” Clone GraphMedium
LC 695 β€” Max Area of IslandMedium
LC 130 β€” Surrounded RegionsMedium
LC 417 β€” Pacific Atlantic Water FlowMedium
LC 547 β€” Number of ProvincesMedium
LC 1020 β€” Number of EnclavesMedium
LC 1905 β€” Count Sub IslandsMedium
LC 797 β€” All Paths From Source to TargetMedium
LC 785 β€” Is Graph Bipartite?Medium
LC 886 β€” Possible BipartitionMedium
LC 399 β€” Evaluate DivisionMedium
LC 1319 β€” Number of Operations to Make Network ConnectedMedium
LC 1466 β€” Reorder Routes to Make All Paths Lead to ZeroMedium
LC 1557 β€” Minimum Number of Vertices to Reach All NodesMedium
CC β€” Chef and Graph Queries (CHEFGRAPH)Hard
CC β€” Roads and Libraries (ROADS)Medium
CC β€” Shortest Path (SHORTPATH)Medium

← Back to Home Β· Β© sparshjaswal