An adjacency list is more memory efficient for sparse graphs because it stores only existing edges. An adjacency matrix uses memory proportional to the square of vertices regardless of edges.
int[][] matrix = new int[3][3]; matrix[0][1] = 1; matrix[1][2] = 1; matrix[2][0] = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); }
The adjacency matrix has 1 at positions where edges exist: (0,1), (1,2), and (2,0). All other positions are 0.
List<Integer>[] adjList = new ArrayList[3]; adjList[0].add(1); adjList[1].add(2); adjList[2].add(0);
The array adjList is created but each element is null. You must initialize each element with new ArrayList<>() before adding.
With millions of users, the graph is very sparse since each user connects to only a small fraction of all users. Adjacency list saves memory and is efficient.
Adjacency matrix memory is proportional to vertices squared (1000*1000=1,000,000). Adjacency list memory is proportional to edges (1500).
