Graphs - Introduction

November 19, 2025
#graph #data-structures #vertices #edges #graph-theory #algorithms #interviewing

Introduction

A graph is a non-linear data structure consisting of vertices (nodes) connected by edges. Unlike trees, graphs can have cycles, multiple paths between nodes, and connections in any direction. Graphs model relationships and networks, making them fundamental to solving real-world problems in social networks, maps, computer networks, and more.

Graphs are one of the most versatile and powerful data structures in computer science. By the end of this tutorial, you’ll understand graph terminology, types of graphs, representation methods, and when to use them.

Review Binary Trees, Arrays, and Hash Tables first if needed.

What is a graph?

A graph G = (V, E) consists of:

  • V: Set of vertices (nodes)
  • E: Set of edges (connections between vertices)

Example graph:

    A --- B
    |     |
    |     |
    C --- D
  • Vertices: {A, B, C, D}
  • Edges: {(A,B), (A,C), (B,D), (C,D)}

Graph terminology

Basic terms:

  • Vertex (Node): A point in the graph
  • Edge: A connection between two vertices
  • Adjacent vertices: Vertices connected by an edge
  • Degree: Number of edges connected to a vertex
  • Path: Sequence of vertices connected by edges
  • Cycle: Path that starts and ends at the same vertex
  • Connected graph: Path exists between every pair of vertices

Types of graphs:

1. Directed vs Undirected

Undirected: Edges have no direction (bidirectional)

A --- B  (can go both ways)

Directed (Digraph): Edges have direction (one-way)

A --> B  (can only go A to B)

2. Weighted vs Unweighted

Weighted: Edges have values (costs, distances)

A --5-- B

Unweighted: All edges are equal

A --- B

3. Cyclic vs Acyclic

Cyclic: Contains at least one cycle

A --- B
|     |
C --- D  (A-B-D-C-A is a cycle)

Acyclic: No cycles (DAG = Directed Acyclic Graph)

A --> B
|     |
v     v
C --> D  (no cycles)

4. Dense vs Sparse

  • Dense: Many edges (close to V²)
  • Sparse: Few edges (close to V)

Why use graphs?

Choose graphs when:

  1. You need to model relationships between entities
  2. You’re finding shortest paths (navigation, routing)
  3. You’re analyzing social networks (friends, followers)
  4. You’re solving network flow problems
  5. You need dependency resolution (task scheduling)
  6. You’re detecting cycles or connectivity
  7. You’re working with maps, routes, or networks

Avoid graphs when:

Real-world applications

Graphs are used everywhere:

  • Social networks: Facebook friends, Twitter followers
  • Maps & GPS: Road networks, shortest routes
  • Web: Page rank, link analysis, web crawling
  • Computer networks: Routing, topology
  • Recommendation systems: “People who bought X also bought Y”
  • Dependency management: Package managers (npm, pip)
  • Biology: Protein interactions, gene networks
  • Compilers: Call graphs, data flow analysis

Graph representation

1. Adjacency Matrix

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

Vertices: A, B, C, D (indices 0, 1, 2, 3)

    A --- B
    |     |
    C --- D

Matrix:
    A  B  C  D
A [[0, 1, 1, 0],
B  [1, 0, 0, 1],
C  [1, 0, 0, 1],
D  [0, 1, 1, 0]]

Pros: O(1) edge lookup, simple for dense graphs Cons: O(V²) space, inefficient for sparse graphs

2. Adjacency List

An array/hash map where each vertex maps to a list of its neighbors.

    A --- B
    |     |
    C --- D

List:
A: [B, C]
B: [A, D]
C: [A, D]
D: [B, C]

Pros: O(V + E) space, efficient for sparse graphs Cons: O(degree) edge lookup

Graph implementation

Adjacency List (most common)

Weighted graph implementation

Graph algorithms preview

Common graph algorithms (covered in separate tutorials):

  • Breadth-First Search (BFS): Level-order traversal, shortest path in unweighted graphs
  • Depth-First Search (DFS): Explore as deep as possible, detect cycles
  • Dijkstra’s Algorithm: Shortest path in weighted graphs
  • Bellman-Ford: Shortest path with negative weights
  • Floyd-Warshall: All-pairs shortest paths
  • Prim’s/Kruskal’s: Minimum spanning tree
  • Topological Sort: Ordering of directed acyclic graph
  • Tarjan’s/Kosaraju’s: Strongly connected components

Complexity analysis

Operation Adjacency Matrix Adjacency List
Add vertex O(V²) (resize) O(1)
Add edge O(1) O(1)
Remove vertex O(V²) O(V + E)
Remove edge O(1) O(E)
Check if edge exists O(1) O(degree)
Get all neighbors O(V) O(degree)
Space O(V²) O(V + E)

Common pitfalls

  • Not handling directed vs undirected: Know which you need
  • Memory issues with dense graphs: Use adjacency matrix
  • Inefficient sparse graph representation: Use adjacency list
  • Not detecting cycles: Can cause infinite loops in traversal
  • Forgetting to mark visited nodes: Leads to infinite loops
  • Not considering disconnected graphs: Not all graphs are connected

When to prefer other data structures

Practice problems

  1. Clone a graph
  2. Detect if a cycle exists in an undirected graph
  3. Detect if a cycle exists in a directed graph
  4. Count the number of connected components
  5. Find if a path exists between two vertices
  6. Determine if a graph is bipartite
  7. Find all paths between two vertices
  8. Implement graph coloring
  9. Check if a graph is a tree
  10. Find the number of islands (2D grid graph)
  11. Course schedule problem (detect cycle in directed graph)
  12. Alien dictionary (topological sort)
  13. Network delay time (weighted graph)
  14. Minimum height trees
  15. Reconstruct itinerary (Eulerian path)

Complexity summary

  • Space:
    • Adjacency Matrix: O(V²)
    • Adjacency List: O(V + E)
  • Time: Varies by algorithm (BFS/DFS: O(V + E))

Graphs are the most versatile data structure for modeling relationships. Master graphs and you’ll be able to solve a vast array of real-world problems from social networks to navigation systems.

Thanks for visiting
We are actively updating content to this site. Thanks for visiting! Please bookmark this page and visit again soon.
Sponsor