Relational Models: Graphs

A Graph is a non-linear data structure consisting of Vertices (Nodes) and Edges (Connections between nodes). Graphs are the most versatile data structure, capable of modeling everything from social networks and maps to dependency trees and recommendation engines.


1. Key Classifications


2. Representations in Memory

Choosing the right representation depends on the Densitity of the graph (the ratio of edges to vertices).

I. Adjacency Matrix

A 2D array where matrix[i][j] = 1 if an edge exists between node $i$ and node $j$.

II. Adjacency List

An array of lists, where list[i] contains all neighbors of node $i$.


3. Fundamental Traversals

I. Breadth-First Search (BFS)

Explores level-by-level using a Queue.

II. Depth-First Search (DFS)

Explores as deep as possible along each branch before backtracking using a Stack (or Recursion).


4. Complexity Summary

Operation Adjacency List Adjacency Matrix
Space O(V + E) O(V²)
Add Vertex O(1) O(V²)
Add Edge O(1) O(1)
Check Edge O(V) O(1)
Traversal O(V + E) O(V²)

Interview Pro-Tips: Topological Sort

A frequent Graph interview question: "How do you determine the order of tasks that have dependencies?"


Technical Summary

  1. Vertices/Edges: The atoms of connectivity.
  2. Density: Determines whether to use a Matrix or a List.
  3. DAG: The foundation of modern task scheduling and CI/CD pipelines.
  4. BFS/DFS: The two ways to navigate the relationship web.