An adjacency list is more memory efficient for sparse graphs because it stores only existing edges. Adjacency matrix uses space for all possible edges regardless of presence.
const vertices = 3; const matrix = Array(vertices).fill(null).map(() => Array(vertices).fill(0)); matrix[0][1] = 1; matrix[1][2] = 1; matrix[2][0] = 1; console.log(matrix);
The matrix rows represent source vertices and columns represent destination vertices. Setting matrix[0][1] = 1 means edge from 0 to 1.
const vertices = 3; const adjList = Array(vertices).fill([]); adjList[0].push(1); console.log(adjList);
Using fill([]) assigns the same array reference to all positions, so pushing to one affects all lists.
Social networks are usually sparse graphs. Adjacency lists save memory by storing only actual connections.
const adjList = Array(4).fill(null).map(() => []); adjList[0].push(1); adjList[0].push(2); adjList[1].push(2); adjList[2].push(3); console.log(adjList);
Each array index holds neighbors of that vertex. Vertex 0 has neighbors 1 and 2, vertex 1 has neighbor 2, vertex 2 has neighbor 3, vertex 3 has none.
