Graphs: Adjacency List

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

A graph consists of nodes and edges. A node-based adjacency representation stores the list of neighbors for each node. Sparse graphs therefore require $O(n + m)$ space.

An n x n matrix is $O(n^{2})$ and quick for dense graphs, allowing edge queries in $O(1)$.

In Java: Map> or List>.

Diagram

A grid as a graph: Number of Islands [1].

Where used

Social networks, microservice dependencies, roadmaps, knowledge graphs, build dependency graphs. Adjacency lists dominate in memory for sparse graphs.

Depth

In the neighbor list representation, each node stores a collection of directly reachable targets. The memory requirement is proportional to the number of nodes plus edges, making it particularly suitable for sparsely populated graphs.

Enumerating all neighbors costs proportional to the degree of the node. However, checking for a specific edge can be linear in degree if the neighbor collection does not have an additional hash or search structure.

In undirected graphs, a logical edge is often stored in both directions. Loops and parallel edges require a conscious modeling decision, as they influence degree calculation and algorithms.

Difficulty levels

  1. Build neighbor collections from a set of edges.
  2. Analyze space and query costs based on node degree.
  3. Correctly account for duplicate storage of undirected edges.

Pitfalls

The number of stored entries for undirected edges is usually twice the logical edge count. A missing target set for isolated nodes causes them to disappear from the graph model.


Sources

University approvals: 0
Tasks
Question 1

Why does the storage of an adjacency matrix grow faster than that of a list for sparse graphs?

Question 2

What do the costs of enumerating all neighbors of a node depend on?

Question 3

Insert an undirected edge into an adjacency list.

Hint

You can obtain an internal neighbor list with graph.get(vertex). New neighbors are added using their method add(value).

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy