Adjacency List Representation in DSA Python - Time & Space Complexity
We want to understand how fast we can build and use an adjacency list for a graph.
How does the time needed grow as the graph gets bigger?
Analyze the time complexity of the following code snippet.
class Graph:
def __init__(self, vertices):
self.V = vertices
self.adj = [[] for _ in range(vertices)]
def add_edge(self, u, v):
self.adj[u].append(v)
self.adj[v].append(u) # For undirected graph
This code creates an adjacency list for a graph and adds edges between nodes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an edge involves appending to two lists.
- How many times: Once per edge added.
Each edge addition takes constant time, but total time grows with number of edges.
| Input Size (Edges) | Approx. Operations |
|---|---|
| 10 | 20 appends (2 per edge) |
| 100 | 200 appends |
| 1000 | 2000 appends |
Pattern observation: Operations grow linearly with the number of edges.
Time Complexity: O(V + E)
This means building the adjacency list takes time proportional to the number of vertices plus the number of edges.
[X] Wrong: "Adding edges takes O(V) time each because we have to check all vertices."
[OK] Correct: We directly add edges to the lists without scanning all vertices, so each edge addition is constant time.
Understanding adjacency lists helps you work efficiently with graphs, a common topic in interviews and real projects.
"What if the graph was directed and we only added one direction per edge? How would the time complexity change?"
Practice
Solution
Step 1: Understand adjacency list concept
An adjacency list stores each node with a list of nodes it connects to directly.Step 2: Compare options with definition
Only A list where each node stores its connected neighbors correctly describes this structure as neighbors stored per node.Final Answer:
A list where each node stores its connected neighbors -> Option DQuick Check:
Adjacency list = neighbors per node [OK]
- Confusing adjacency list with adjacency matrix
- Thinking it stores distances instead of neighbors
- Assuming it lists nodes without connections
Solution
Step 1: Understand adjacency list initialization
An adjacency list is usually a dictionary with keys as nodes and values as lists of neighbors.Step 2: Check each option
graph = {0: [], 1: [], 2: []} correctly creates a dict with empty lists for each node. graph = [[], [], []] is a list of lists but lacks node keys. graph = {0: None, 1: None, 2: None} uses None instead of lists. graph = [0, 1, 2] is just a list of nodes, not adjacency lists.Final Answer:
graph = {0: [], 1: [], 2: []} -> Option AQuick Check:
Dict with empty lists = adjacency list init [OK]
- Using None instead of empty lists for neighbors
- Using list without node keys
- Confusing adjacency list with simple node list
graph = {0: [1, 2], 1: [2], 2: [0, 3], 3: []}
print(graph[2])Solution
Step 1: Identify the adjacency list for node 2
In the dictionary, key 2 maps to the list [0, 3].Step 2: Print the value for key 2
Printing graph[2] outputs [0, 3].Final Answer:
[0, 3] -> Option BQuick Check:
graph[2] = [0, 3] [OK]
- Confusing keys and values
- Printing wrong node's neighbors
- Misreading list contents
graph = {0: [1], 1: [2], 2: [0]}
graph[1].append(3)
print(graph)Solution
Step 1: Check if node 1 exists in graph
Node 1 is a key in graph with value [2], so graph[1] is a list.Step 2: Append 3 to graph[1]
Appending 3 to the list [2] is valid and updates graph[1] to [2, 3].Final Answer:
No error, code runs correctly -> Option CQuick Check:
Appending to list in dict value works [OK]
- Thinking node 3 must exist as key before adding
- Confusing append on list vs dict
- Expecting error when adding new neighbor
graph = {0: [1, 2], 1: [2], 2: [0], 3: [2]}Which node(s) have no outgoing edges?
Solution
Step 1: Check neighbors list for each node
Node 0 connects to [1, 2], node 1 to [2], node 2 to [0], node 3 to [2].Step 2: Identify nodes with empty neighbor lists
Node 3 has neighbors [2], so it has outgoing edges. No node has an empty list, so none have no outgoing edges.Final Answer:
None, all have outgoing edges -> Option AQuick Check:
All adjacency lists non-empty = no node without edges [OK]
- Assuming node 3 has no edges because it appears last
- Confusing incoming edges with outgoing edges
- Ignoring non-empty lists
Ready to prove it?
Pass the test and this pattern moves unknown
