DSA Notes
A thorough introduction to graphs — what a graph is, formal definitions, all types of graphs (directed, undirected, weighted, cyclic, DAG), real-world applications, graph terminology (vertex, edge, degree, path, cycle, connectivity), and the two fundamental representations (adjacency list and matrix).
What Is a Graph?
A graph is a non-linear data structure that models relationships between objects. It consists of:
- Vertices (nodes): The objects being modeled
- Edges: The relationships (connections) between vertices
Formally: G = (V, E) where V is a set of vertices and E is a set of edges.
Graphs are arguably the most powerful and widely applicable data structure in computer science. Every network — social, road, internet, biological — is a graph. Understanding graphs means understanding how the connected world works.
Graph Terminology
Vertex (Node)
A fundamental unit of a graph. Usually labeled with a number or name.
Edge
A connection between two vertices. An edge (u, v) connects vertex u and vertex v.
Adjacent Vertices (Neighbors)
Two vertices are adjacent if there is an edge directly connecting them.
| In graph with edges | {(A,B), (B,C), (A,C)} |
| A's neighbors | B, C |
| B's neighbors | A, C |
Degree
The degree of a vertex is the number of edges connected to it.
- Undirected graph: degree = number of edges
- Directed graph:
- In-degree: number of edges coming IN to the vertex
- Out-degree: number of edges going OUT from the vertex
Path
A sequence of vertices where each consecutive pair has an edge between them.
| Graph | A—B—C—D |
| Path from A to D: A | B → C → D |
| Path length | 3 (number of edges) |
Cycle
A path that starts and ends at the same vertex with no repeated edges.
Connected Graph
An undirected graph where there is a path between every pair of vertices.
Connected Component
A maximal connected subgraph. An isolated vertex is its own component.
Types of Graphs
1. Undirected Graph
Edges have no direction — if there is an edge between A and B, you can travel both ways.
2. Directed Graph (Digraph)
Edges have direction — an edge (A, B) means you can go from A to B but NOT necessarily from B to A.
| A | B → C |
| Edges: A | B, B→C, C→D, D→A (one-way) |
| Real world | Twitter follows (you follow someone; they might not follow back) |
3. Weighted Graph
Each edge has a numerical weight (cost, distance, time, etc.).
4. Unweighted Graph
All edges have equal weight (or weight 1). BFS finds shortest paths in unweighted graphs.
5. Cyclic Graph
Contains at least one cycle (path from a vertex back to itself).
6. Acyclic Graph
Contains no cycles.
7. DAG (Directed Acyclic Graph)
Directed graph with no cycles. Extremely important in computer science:
- Prerequisite structures (course A requires course B)
- Build systems (compile module X before module Y)
- Version control graphs
- Neural network architectures
8. Tree
A connected undirected graph with no cycles. A tree with n vertices has exactly n-1 edges.
9. Complete Graph (K_n)
Every vertex is connected to every other vertex. Has n(n-1)/2 edges for n vertices.
10. Bipartite Graph
Vertices can be divided into two disjoint sets such that every edge connects a vertex in one set to a vertex in the other. No edges within a set.
11. Sparse vs Dense Graph
- Sparse graph: Few edges relative to vertices. E ≈ O(V)
- Dense graph: Many edges relative to vertices. E ≈ O(V²)
This distinction determines whether adjacency list or matrix is more appropriate.
Graph Representation
Representation 1 — Adjacency List
Space: O(V + E) — ideal for sparse graphs
Representation 2 — Adjacency Matrix
Space: O(V²) — practical only for dense graphs
Comparison: List vs Matrix
| Feature | Adjacency List | Adjacency Matrix |
|---|---|---|
| Space | O(V + E) | O(V²) |
| Check if edge (u,v) exists | O(degree) | O(1) |
| Find all neighbors of u | O(degree) | O(V) |
| Add edge | O(1) | O(1) |
| Remove edge | O(degree) | O(1) |
| Best for | Sparse graphs | Dense graphs |
| Used in | BFS, DFS, Dijkstra | Floyd-Warshall |
Edge List Representation
Building Graphs from Input
Graph Properties
def graph_properties(graph):
"""Calculate basic graph properties."""
V = len(graph)
E = sum(len(neighbors) for neighbors in graph.values()) // 2 # Undirected
# Degree of each vertex
degrees = {v: len(neighbors) for v, neighbors in graph.items()}
max_degree = max(degrees.values())
avg_degree = sum(degrees.values()) / V
return {
'vertices': V,
'edges': E,
'max_degree': max_degree,
'avg_degree': avg_degree,
'density': 2 * E / (V * (V-1)) if V > 1 else 0
}Summary
Graphs model any network of relationships:
- Vertices = entities, Edges = relationships
- Undirected = bidirectional, Directed = one-way
- Weighted = edges have costs, Unweighted = edges equal
- Cyclic = has cycles, Acyclic = no cycles
- DAG = directed acyclic graph — extremely common in CS
Two representations:
- Adjacency List: O(V+E) space — use for sparse graphs (most real-world graphs)
- Adjacency Matrix: O(V²) space — use for dense graphs or when O(1) edge lookup is needed
*Next Lesson: Graph Representation*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Graph — Complete Introduction to the Most Powerful Data Structure.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, graphs, graph, introduction
Related Data Structures & Algorithms Topics