Skip to the solution
EasyDSA13 min read

What is a graph, and how do you represent it?

921 views

The problem

Question presented to candidate: "What is a graph, and how would you store one in memory in Python? Walk me through the options and when you would pick each one."

What a strong answer should cover:

  • Vertices and edges; directed vs undirected; weighted vs unweighted; degree.
  • The three representations β€” edge list, adjacency list, adjacency matrix β€” with their space (O(E), O(V + E), O(VΒ²)) and edge-lookup costs.
  • Sparse vs dense: why the adjacency list is the default for interview problems.
  • Implicit graphs: a grid or a word puzzle is a graph you never build explicitly.
  • Python details: [[] for _ in range(n)] (not [[]] * n, which shares one list), dict/defaultdict(list) for string labels, set neighbours for O(1) edge checks.

Code / implementation expected: Optional β€” building an adjacency list from an edge list in a few lines of Python.

  • dsa
  • graph
  • adjacency-list

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonOne graph, three representations: edge list, adjacency list, matrix
PythonWeighted directed graph, sparse-graph space, implicit grid graph

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 7 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is the difference between a stack and a queue?

Continue