Data Structures and Algorithms

Which is an appropriate way to store in memory a sparse graph, one with few edges compared with its number of vertices, such as a road network with about 1 million vertices and 3 million edges?

  1. AAn adjacency matrix: it can check whether two vertices are connected in O(1) and also uses the least memory
  2. BAdjacency lists: memory is proportional to the number of vertices plus the number of edges, and they suit following the edges out of a vertex one by one
  3. CAn adjacency matrix: its memory is proportional only to the number of edges
Show answer and explanation

Answer: B. Adjacency lists: memory is proportional to the number of vertices plus the number of edges, and they suit following the edges out of a vertex one by one

An adjacency matrix uses a V × V table for V vertices, so 1 million vertices need 10¹² entries, about 125 GB even at 1 bit per entry. Adjacency lists store only the neighbors of each vertex, so memory is O(V + E), only a few million entries in this example. An adjacency matrix has the advantage of checking for an edge in O(1) and suits dense graphs or graphs with few vertices. For processing that follows the edges out of each vertex in turn, such as breadth-first search and Dijkstra's algorithm, adjacency lists are more efficient.

  • A. Checking for an edge in O(1) is true, but the memory grows with the square of the number of vertices, which is very wasteful for a sparse graph.
  • B. Correct. Memory is only O(V + E), and they suit processing that walks through neighboring vertices.
  • C. The size of an adjacency matrix does not depend on the number of edges; it is the square of the number of vertices.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. In a graph whose edges have no weights, you want to find the smallest number of edges from a starting vertex to every other vertex. Which pair of search method and data structure is suitable?
  2. In an undirected graph, the neighbors of each vertex are A: B, C / B: A, D, E / C: A, F / D: B / E: B, F / F: C, E. A recursive depth-first search starts from vertex A. The neighbors are examined in the order listed, and as soon as an unvisited vertex is found, the search moves to it. In what order are the vertices visited?
  3. In an undirected graph, the edge weights (distances) are S−A: 4, S−B: 1, A−B: 2, A−C: 1, B−C: 5, C−T: 3 and A−T: 6. Which shows the shortest path from S to T found by Dijkstra's algorithm and its length?
  4. Which condition on the graph is required for Dijkstra's algorithm to find correct shortest paths?
  5. Tasks A to E have the ordering constraints “A before C”, “B before C”, “C before D”, “B before E” and “E before D”. Which order satisfies all the constraints (a result of topological sorting)?