Skip to main content
General

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

Sachin AhujaSachin Ahuja
11 months ago
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)

Sign in to join the discussion.
Lakshay Desai
Lakshay Desai10 months ago(edited)

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

Lakshay Desai
Lakshay Desai10 months ago

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 Verma
Tanya Verma10 months ago

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 Thakur
Yash Thakur11 months ago

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

Urvashi Gill
Urvashi Gill11 months ago

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

Urvi Iyer
Urvi Iyer11 months ago

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