Skip to main content
General

Graph representation: adjacency list vs matrix - when to use which

Sachin Ahuja
9/20/2025
404

Quick decision guide:

Adjacency List:

  • Sparse graphs (few edges)
  • When you need to iterate over neighbors
  • Most interview problems
  • Space: O(V + E)

Adjacency Matrix:

  • Dense graphs (many edges)
  • When you need O(1) edge existence check
  • Floyd-Warshall algorithm
  • Space: O(V²)

Interview tip: Unless the problem specifically requires a matrix (like grid problems), always use an adjacency list. It's more space-efficient and interviewers expect it.

For Python: defaultdict(list) is your best friend.

graph = defaultdict(list)
for u, v in edges:
    graph[u].append(v)

graphadjacency-listtutorialdsa

Comments (6)

Markdown supported · Ctrl+Enter to submit
Lakshay Desai10/11/2025(edited)

Cool breakdown! I often get confused in interviews about when to initialize data structures. Any tips on that?

Lakshay Desai10/11/2025

I've always defaulted to adjacency lists for most graph problems. How does the performance hit from using lists compare to matrices when doing multiple edge existence checks?

Tanya Verma10/9/2025

I like that you mentioned interview expectations. I've had interviews where my interviewer insisted on lists even when it seemed like a matrix would be more efficient. 😅

Yash Thakur9/25/2025

Does using a matrix ever make sense in competitive programming, given its space cost?

Urvashi Gill9/23/2025

Hey Sachin, any thoughts on using adjacency sets for graphs? I find them handy sometimes.

Urvi Iyer9/23/2025

I love the tip about defaultdict(list)! Also, do you think adjacency lists work well for weighted graphs?