๐Ÿ•ธ๏ธ Graph

Nitin SinghNitin Singh
4 min read

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

OperationAdjacency ListAdjacency Matrix
Add VertexO(1)O(Vยฒ)
Add EdgeO(1)O(1)
Check if Edge ExistsO(V)O(1)
Traverse All Vertices/EdgesO(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.

๐Ÿ’ก
Trade-off: Choose based on the graphโ€™s density and the operations you need.

๐Ÿ“˜ LeetCode Practice Problems

ProblemDifficultyLeetCode#
Clone GraphMediumLeetCode#133
Course ScheduleMediumLeetCode#207
Number of IslandsMediumLeetCode#200
Graph Valid TreeMediumLeetCode#261
Reconstruct ItineraryHardLeetCode#332
Word LadderHardLeetCode#127
Network Delay TimeMediumLeetCode#743
Find Eventual Safe StatesMediumLeetCode#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! ๐Ÿ’ป๐ŸŒณ

0
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.