๐ธ๏ธ Graph


Introduction
Graphs are incredibly powerful data structures that allow us to model complex relationships between entities. From social networks and recommendation engines to routing maps and dependency resolution, graphs are everywhere.
๐ What Is a Graph?
A graph is a non-linear data structure that consists of:
Vertices (nodes): The fundamental units or points.
Edges: Connections between pairs of vertices.
Graphs can be:
Directed vs. Undirected
โ Directed edges have direction (e.g., A โ B), whereas undirected edges don't (A โ B).Weighted vs. Unweighted
โ Weighted graphs have costs or weights associated with edges.Cyclic vs. Acyclic
โ Cyclic graphs contain cycles, while acyclic ones do not.Connected vs. Disconnected
โ A connected graph has a path between every pair of vertices.
๐งฎ Representing a Graph in Code
1. Adjacency Matrix (2D Array)
int[][] graph = {
{0, 1, 0},
{1, 0, 1},
{0, 1, 0}
};
Time to check edge existence: O(1)
Space: O(Vยฒ)
2. Adjacency List (Array of Lists)
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
graph.get(0).add(1);
graph.get(1).add(2);
Time to traverse: O(V + E)
Space: O(V + E)
๐ Common Graph Traversal Techniques
1. Breadth-First Search (BFS)
- Explores neighbors level by level using a queue.
Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[n];
queue.add(start);
visited[start] = true;
while (!queue.isEmpty()) {
int node = queue.poll();
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
2. Depth-First Search (DFS)
- Goes deep along each path using recursion or a stack.
void dfs(int node, boolean[] visited, List<List<Integer>> graph) {
visited[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) dfs(neighbor, visited, graph);
}
}
โ๏ธ Common Operations & Time Complexities
Operation | Adjacency List | Adjacency Matrix |
Add Vertex | O(1) | O(Vยฒ) |
Add Edge | O(1) | O(1) |
Check if Edge Exists | O(V) | O(1) |
Traverse All Vertices/Edges | O(V + E) | O(Vยฒ) |
๐ง Real-World Analogy
Think of a graph as a city map:
Intersections = Vertices
Roads = Edges
One-way streets = Directed Edges
Tolls = Weights
This is how navigation systems, airline networks, and web crawlers operate!
๐งต Memory Layout
๐ธ Adjacency Matrix
Suitable for dense graphs (many connections).
Requires a 2D matrix of size VรV.
Simpler to implement but memory-heavy.
๐น Adjacency List
Suitable for sparse graphs (few connections).
Efficient memory usage.
Uses lists for each node to store neighbors.
๐ LeetCode Practice Problems
Problem | Difficulty | LeetCode# |
Clone Graph | Medium | LeetCode#133 |
Course Schedule | Medium | LeetCode#207 |
Number of Islands | Medium | LeetCode#200 |
Graph Valid Tree | Medium | LeetCode#261 |
Reconstruct Itinerary | Hard | LeetCode#332 |
Word Ladder | Hard | LeetCode#127 |
Network Delay Time | Medium | LeetCode#743 |
Find Eventual Safe States | Medium | LeetCode#802 |
๐ฏ Tips for Interview Prep
Understand when to use BFS vs. DFS.
Practice topological sorting (for DAGs).
Be clear on how to detect cycles in both directed and undirected graphs.
Learn Union-Find for connected components.
Try drawing out graphs during problem-solving to better visualize paths and states.
๐ Wrapping Up
Graphs unlock a powerful way to represent and navigate complex relationships and structures. Once you understand how to traverse and build them efficiently, a whole new category of problems becomes solvable.
๐งฑ Stay tuned for the next post on Union-Find โ A Disjoint Set Structure for Connectivity Problems.
๐ Enjoying the Series?
This blog is part of my DSA series โ โLevel Up Your Programming with Nitinโ, where I break down core data structures and algorithms with clear explanations, real-world analogies, Java code snippets, and curated LeetCode problems.
You can explore the entire series anytime here:
๐ DS Interview Prep Series
If you find it helpful, feel free to share with peers, bookmark it for revision, or leave a โค๏ธ to support the effort.
๐ Follow my blog on Hashnode: ns717.hashnode.dev
๐ผ Connect with me on LinkedIn: Nitin Singh
Thanks for reading, and happy coding! ๐ป๐ณ
Subscribe to my newsletter
Read articles from Nitin Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nitin Singh
Nitin Singh
I'm a passionate Software Engineer with over 12 years of experience working with leading MNCs and big tech companies. I specialize in Java, microservices, system design, data structures, problem solving, and distributed systems. Through this blog, I share my learnings, real-world engineering challenges, and insights into building scalable, maintainable backend systems. Whether itโs Java internals, cloud-native architecture, or system design patterns, my goal is to help engineers grow through practical, experience-backed content.