DSA · Patterns, not puzzles

How do you represent a graph?

Easygraphsadjacency-listadjacency-matrixUpdated Oct 2026
Quiz this track

Short answer

An adjacency list maps each vertex to its neighbours and is efficient for sparse graphs. An adjacency matrix uses a V by V grid for O(1) edge checks and is better for dense graphs or matrix-style algorithms.

The representation affects both time and memory. An adjacency list uses O(V + E) space and lets you iterate over a vertex's neighbours efficiently. A matrix uses O(V^2) space regardless of edge count, but edge existence is a constant-time lookup.

js
const graph = new Map([
  ["A", ["B", "C"]],
  ["B", ["A", "D"]],
  ["C", ["A"]],
  ["D", ["B"]],
]);
The adjacency list stores only existing edges, which is ideal for sparse graphs.

Choosing a representation

  • Adjacency list: O(V + E) space, fast neighbour iteration, common for BFS and DFS
  • Adjacency matrix: O(V^2) space, O(1) edge lookup, useful for dense graphs
  • Edge list: O(E) space, convenient for Kruskal's algorithm
  • Weighted graphs store a weight alongside each neighbour
  • Directed graphs store only outgoing edges unless you also need reverse traversal
js
const weighted = new Map([
  ["A", [["B", 4], ["C", 1]]],
  ["B", [["A", 4], ["D", 2]]],
  ["C", [["A", 1], ["D", 5]]],
  ["D", [["B", 2], ["C", 5]]],
]);
A weighted adjacency list stores pairs of neighbour and edge weight.
For a grid, you often do not need an explicit graph. Treat each cell as a node and generate its neighbours from the four or eight directions.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1When would you choose an adjacency matrix over a list?
  2. 2How do you represent a weighted graph?
  3. 3How do you convert an edge list to an adjacency list?
  4. 4How do you handle a directed graph?

Say it in the interview

An adjacency list maps each vertex to its neighbours and uses O(V + E) space, which suits sparse graphs and traversals. An adjacency matrix is a V by V grid with O(1) edge checks but O(V^2) space, so it suits dense graphs. For weighted edges I store the weight with each neighbour, and I often start Kruskal from an edge list. On a grid I usually generate neighbours instead of building a graph.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.