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,setneighbours for O(1) edge checks.
Code / implementation expected: Optional β building an adjacency list from an edge list in a few lines of Python.