Adjacency List Representation in DSA Javascript - Time & Space Complexity
We want to understand how fast we can access and explore connections in a graph using adjacency lists.
How does the time to check neighbors grow as the graph gets bigger?
Analyze the time complexity of the following code snippet.
// Graph represented as adjacency list
const graph = {
0: [1, 2],
1: [0, 3],
2: [0],
3: [1]
};
// Function to print neighbors of a node
function printNeighbors(node) {
for (const neighbor of graph[node]) {
console.log(neighbor);
}
}
This code stores graph connections in lists and prints all neighbors of a given node.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the neighbors list of a node.
- How many times: Equal to the number of neighbors that node has.
As the graph grows, the time to print neighbors depends on how many neighbors the node has.
| Input Size (n = total nodes) | Approx. Operations (neighbors of node) |
|---|---|
| 10 | Depends on node degree, e.g., 2 neighbors |
| 100 | Depends on node degree, e.g., 5 neighbors |
| 1000 | Depends on node degree, e.g., 10 neighbors |
Pattern observation: Time grows with the number of neighbors, not total nodes.
Time Complexity: O(k) where k is the number of neighbors of the node.
This means the time depends only on how many connections the node has, not the whole graph size.
[X] Wrong: "Accessing neighbors always takes O(n) time where n is total nodes."
[OK] Correct: We only loop through the node's neighbors, which is usually much less than total nodes.
Knowing adjacency list time helps you explain graph traversal speed clearly and confidently in interviews.
"What if the graph was stored as an adjacency matrix instead? How would the time complexity to find neighbors change?"
Practice
Solution
Step 1: Understand adjacency list concept
An adjacency list stores each node with a list of its neighbors or connected nodes.Step 2: Compare with other graph representations
An adjacency matrix is a 2D array, not a list of neighbors. Other options describe different structures.Final Answer:
A list where each node stores its neighbors -> Option AQuick Check:
Adjacency list = neighbors list [OK]
- Confusing adjacency list with adjacency matrix
- Thinking it stores edges sorted by weight
- Assuming it lists nodes without connections only
Solution
Step 1: Identify suitable data structure for adjacency list
An adjacency list can be implemented using a Map to store nodes and their neighbors efficiently.Step 2: Check syntax correctness
new Map() creates an empty map. Arrays or objects can be used but Map is preferred for graph keys. Set is for unique values, not key-value pairs.Final Answer:
const graph = new Map(); -> Option BQuick Check:
Use Map() for adjacency list initialization [OK]
- Using Set which does not store key-value pairs
- Using empty array which is less clear for key-value
- Using empty object but Map is better for keys
console.log(graph.get('A'));?
const graph = new Map();
graph.set('A', ['B', 'C']);
graph.set('B', ['A', 'D']);
graph.set('C', ['A']);
graph.set('D', ['B']);Solution
Step 1: Locate the key 'A' in the adjacency list
The graph Map has key 'A' with value ['B', 'C'] representing neighbors.Step 2: Understand what graph.get('A') returns
It returns the array of neighbors for 'A', which is ['B', 'C'].Final Answer:
['B', 'C'] -> Option DQuick Check:
graph.get('A') = ['B', 'C'] [OK]
- Confusing neighbors of 'A' with neighbors of 'B'
- Expecting a string instead of array
- Mixing up keys and values in Map
const graph = new Map();
graph.set('A', ['B', 'C']);
// Add edge from A to D
graph.get('A').push('D');
console.log(graph.get('A'));Solution
Step 1: Check if graph.get('A') returns an array
graph.get('A') returns ['B', 'C'], an array, so push is valid.Step 2: Verify if push adds 'D' correctly
push('D') adds 'D' to the array, so neighbors become ['B', 'C', 'D'].Final Answer:
The code works correctly and adds 'D' to neighbors -> Option CQuick Check:
push on neighbors array works [OK]
- Assuming graph.get returns undefined if key exists
- Thinking push cannot modify array in Map
- Confusing push with set method
Solution
Step 1: Understand directed edges
Edges are X->Y, Y->Z, Z->X, so each node points only to its direct neighbors.Step 2: Match edges to adjacency list entries
'X' neighbors: ['Y'], 'Y' neighbors: ['Z'], 'Z' neighbors: ['X'] matches const graph = new Map([['X', ['Y']], ['Y', ['Z']], ['Z', ['X']]]); exactly.Final Answer:
const graph = new Map([['X', ['Y']], ['Y', ['Z']], ['Z', ['X']]]); -> Option AQuick Check:
Directed edges match adjacency list neighbors [OK]
- Including neighbors that don't have edges from the node
- Mixing up direction of edges
- Adding extra neighbors not in edges
Ready to prove it?
Pass the test and this pattern moves unknown
