🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Graph Representations — Adjacency Matrix vs Adjacency List — Complete Beginner Guide

Data Structures FoundationsGraph Representations — Adjacency Matrix vs Adjacency List🟢 Free Lesson

Graph Representations — Adjacency Matrix vs Adjacency List — Complete Beginner Guide

Learning Objectives

  • Build a graph with a matrix and a list
  • Compute space cost for both layouts
  • Compare neighbor iteration speed
  • Support weights in each design
  • Choose a representation from graph density

Two Storage Philosophies

Graph algorithms need neighbor access. Two standard layouts provide it.

LayoutIdea
Adjacency matrixGrid of cells where row meets column
Adjacency listMap from vertex to neighbor collection

Adjacency Matrix

A two-dimensional grid stores edge presence or weight. Cell row i and column j describes the edge from i to j.

For an undirected graph, the matrix is symmetric. For a directed graph, only one direction is set.

python
def build_matrix(n, edges, directed=False):
    matrix = [[0] * n for _ in range(n)]
    for a, b in edges:
        matrix[a][b] = 1
        if not directed:
            matrix[b][a] = 1
    return matrix


def has_edge(matrix, a, b):
    return matrix[a][b] == 1


n = 4
edges = [(0, 1), (1, 2), (2, 3)]
graph = build_matrix(n, edges)
print(has_edge(graph, 0, 1))  # True
print(has_edge(graph, 0, 3))  # False

Matrix Complexity

TaskCost
SpaceO of V squared
Check edge a to bO(1)
List neighbors of vO(V)
Add edgeO(1)
Remove edgeO(1)

Matrices shine when the graph is dense or when you repeatedly test arbitrary pairs.

Adjacency List

Each vertex stores a list or set of neighbors. Sparse graphs waste almost nothing.

python
def build_list(n, edges, directed=False):
    graph = [[] for _ in range(n)]
    for a, b in edges:
        graph[a].append(b)
        if not directed:
            graph[b].append(a)
    return graph


def neighbors(graph, v):
    return graph[v]


n = 4
edges = [(0, 1), (1, 2), (2, 3)]
graph = build_list(n, edges)
print(neighbors(graph, 1))  # 0 and 2

For weighted graphs, store pairs of neighbor and weight instead of bare ids.

python
# Weighted adjacency list entry style
# vertex 0 connects to vertex 1 with weight 4
weighted = {0: [(1, 4)], 1: [(0, 4)]}

List Complexity

TaskCost
SpaceO of V plus E
Check edge a to bO of degree of a, or O(1) with set
List neighbors of vO of degree of v
Add edgeO(1) append
Remove edgeO of degree of a

Side-by-Side Table

CriteriaMatrixList
Space dense graphEfficient enoughCan hold duplicates overhead
Space sparse graphWastes V squared cellsCompact
Edge existence queryO(1)O of degree unless set
Neighbor scanScans V slotsScans real neighbors only
BFS or DFS total timeO of V squaredO of V plus E
Simple to codeVeryVery
Edge weightsCell holds weightPair list holds weight

Density Decision Rule

Let density equal E divided by the maximum possible edges.

DensityPreferred Layout
High, near completeMatrix
Low, typical networksList
MixedList with optional set for fast queries
Tiny V under about one hundredEither often fine

Memory Math

For ten thousand vertices:

LayoutRough Cell Count
MatrixOne hundred million cells
List with ten edges eachOne hundred thousand entries

The matrix explodes while the list stays modest. For five hundred nearly complete vertices, the matrix is fine and scans stay simple.

Traversal Impact

BFS and DFS visit real edges once when using lists, giving O of V plus E total. Matrix neighbor loops always touch V columns per vertex even if most cells are empty, pushing total work toward V squared.

Representation Choice Drill

Walk a few size estimates before choosing a layout. One thousand vertices with average degree five means about five thousand directed entries, perfect for lists. Two hundred vertices fully connected means about forty thousand matrix cells, still fine and simpler for edge checks.

python
def space_estimate(v, e, dense_threshold=None):
    matrix_cells = v * v
    list_entries = 2 * e  # undirected counted both ways
    if dense_threshold is None:
        dense_threshold = matrix_cells / 2
    prefer_matrix = e >= dense_threshold
    return matrix_cells, list_entries, prefer_matrix


print(space_estimate(100, 4000))
print(space_estimate(1000, 5000))

Add a second question to every design: do you need O(1) arbitrary edge existence checks? If yes and memory allows, a matrix or a set of encoded pairs helps. If you only walk neighbors during BFS or DFS, a list wins.

Finish by rewriting one matrix BFS into list BFS and comparing visited loops. Seeing V squared collapse into V plus E makes the theory concrete.

Key Takeaways

💡

  • Adjacency matrices give O(1) edge checks and V squared space
  • Adjacency lists give O of V plus E traversals and V plus E space
  • Dense graphs favor matrices; sparse graphs favor lists
  • Weighted graphs store weights in cells or neighbor pairs
  • Most real-world social and map graphs stay sparse, so lists win

Practice Questions

  1. Compute matrix and list space for one million vertices with only two million edges.
  2. Why does scanning matrix neighbors hurt BFS even when few edges exist?
  3. Choose a representation for a road network of one hundred thousand intersections and justify.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement