Space complexity of adjacency lists

74 Views Asked by At

Can anyone explain to me why the space complexity of adjacency lists is Theta(m + n)?

Example graph:

a: b, c, d

b : e

c : d, e

d : empty

e : a

So here n = 5, m = 7.

Even crazier: The professor told us about a space complexity of Theta(m * log_2(n))

Let's look at Theta(m + n) ... there are constants c1 and c2 satisfying c1 * (m + n) <= space_complexity_of_this <= c2 * (m + n) ... but what if we have |E| = n choose 2 (maximum number of edges), then our space complexity would be something like n * (n - 1) and that doesn't fit c2.

1

There are 1 best solutions below

0
Lior Kogan On

I assume you refer to a simple graph.

Using the common notation - the graph contains n vertices and m edges, you can easily see that for storing the adjacency list you'll need θ(m+n) memory.

but what if we have |E| = n choose 2

So what? m = n(n-1)/2 but still, you'll need θ(m+n) memory.

The professor told us about a space complexity of Theta(m * log2(n))

If you'll index your nodes 0 .. n-1, you can use ceil(log2(n)) bits to store the index of each node, and hence, you'll need 2*ceil(log2(n)) bits to store each edge, or θ(m * log2(n)) bits for storing all the edges (you don't need to store the nodes, just use a count as a prefix for each neighbors list).