Graphs
Graph Fundamentals
Master Graph representation: vertices, edges, directed/undirected types, and Adjacency List vs Matrix implementations.
Last Updated: August 2, 2026
•
15 min read
1. Introduction
What is a Graph?
A Graph is a non-linear data structure consisting of a finite set of Vertices (or Nodes) and a set of Edges connecting these vertices. Mathematically,G = (V, E).
Why study them?
Many real-world systems are networks of relationships. Graphs are used to model social networks, transportation routes, web page link maps, and dependency hierarchies. Mastering graph structures is essential to solve pathfinding, cycle detection, and scheduling algorithms.Where is it Used?
2. Mental Model: Flight Connections Map
Imagine looking at an airport display:
3. Graph Representations
There are two primary methods to store a graph in code:
1. Adjacency Matrix
A 2D array of sizeV × V, where matrix[i][j] is 1 (or the edge weight) if there is an edge from vertex i to j, and 0 otherwise.
O(V²)O(1) time to check if an edge exists between two vertices.E \ll V²), since most entries are 0.2. Adjacency List
An array of lists of sizeV, where list[i] contains all the neighboring vertices of vertex i.
O(V + E)i and j takes O(degree(i)) time.4. Visual Comparison
Given 3 vertices [0, 1, 2] with edges (0-1) and (1-2):
Adjacency representations:
5. Real-World Examples
6. Interview Perspective
How Interviewers Ask This Topic
Interviewers test representation selection:10^12 elements, leading to a compilation out-of-memory crash.E \approx V², or when we need to perform constant-time edge exist checks matrix[u][v].Common Mistakes
Warning: 1. Directed Edge Duality: Accidentally adding directed edges in both directions inside directed graph helpers, creating unintended cycle paths.
> 2. 1-Based Indexing Crashes: Backing lists by size-V arrays while node inputs utilize 1-based indices (e.g. vertex numbers1toV). This will cause an Index Out of Bounds exception. Always subtract 1 or size arrays toV + 1.
7. Summary
G=(V,E).O(V²) space. Best for dense graphs.O(V + E) space. Best for sparse graphs.8. Quiz
Question 1: What is the maximum number of edges in a simple directed graph with V vertices?
Answer:V(V - 1) edges (assuming no self-loops).
Question 2: What is the time complexity to check if there is an edge between vertices U and V in an Adjacency Matrix?
Answer:O(1) time, since we directly query matrix[u][v].
Question 3: If a graph has V vertices and E edges, what is the space complexity of its Adjacency List representation?
Answer:O(V + E) space.
Question 4: True or False: In a tree, the number of edges is always exactly V - 1.
Answer: True. A tree is a connected acyclic undirected graph, which always contains exactlyV - 1 edges.