Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Data Structures
Data Structuresmedium

Adjacency list vs adjacency matrix — when to use which?

Tags
#graph#adjacency-list#adjacency-matrix#complexity
Back to categoryPractice quiz

Answer

A matrix uses O(V^2) memory and gives O(1) edge checks, so it’s good for dense graphs. A list uses O(V+E) memory and is better for sparse graphs and iterating neighbors.

Advanced answer

Deep dive

The choice is mostly about density and the operations you care about.

Adjacency list:

  • Memory: O(V + E)
  • Iterate neighbors of u: O(deg(u))
  • Check edge (u, v): O(deg(u)) unless you store a set per node

Adjacency matrix:

  • Memory: O(V^2)
  • Iterate neighbors of u: O(V) (scan the row)
  • Check edge (u, v): O(1)

When to choose which

  • Sparse graphs (E much smaller than V^2): adjacency list.
  • Dense graphs, or you do tons of edge-existence queries: matrix.
  • Algorithms:
  • BFS/DFS/Dijkstra: list is usually best.
  • Floyd–Warshall / transitive closure: matrix is natural (often optimized with bitsets).

Examples

// Adjacency list
const adj: number[][] = Array.from({ length: n }, () => [])
adj[u].push(v)

// Adjacency matrix
const mat: boolean[][] = Array.from({ length: n }, () => Array(n).fill(false))
mat[u][v] = true

Related questions

Data Structures
Adjacency list vs adjacency matrix: when do you choose each?
#graph#adjacency-list#adjacency-matrix
Data Structures
Building a heap from an array: why can it be O(n), not O(n log n)?
#heap#heapify#complexity
Algorithms
Common pitfalls
  • A matrix becomes impossible fast: V=50k means 2.5B cells.
  • For directed graphs you must store direction correctly (u->v != v->u).
  • For weighted graphs, store weights (list: pairs; matrix: numbers/Infinity).
Heap sort: what are its time complexity, space complexity, and stability?
#heapsort#sorting#complexity
Algorithms
Bitmask DP (subset DP): what is it and what is a typical complexity?
#dp#bitmask#subset
Algorithms
Sliding window: what is it and when is it better than nested loops?
#sliding-window#two-pointers#complexity