Skip to content
DeepForgeby svx
All problems
EasyGraph Algorithmsgraph-008

Graph Density

Problem

Compute the density of an undirected simple graph with n nodes: density = 2 * m / (n * (n - 1)), where m is the number of edges.

Assume edges are unique and contain no self-loops. Return 0.0 when n is less than 2.

Hint

A complete graph has n * (n - 1) / 2 edges, so its density is 1.

Test cases

case 1
in: [4,[[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]]]
expected: 1
case 2
in: [4,[[0,1],[1,2]]]
expected: 0.3333333333333333
case 3
in: [1,[]]
expected: 0
case 4
in: [3,[[0,1],[1,2],[0,2]]]
expected: 1
Starter codePython
def graph_density(n, edges):
    # Your code here
    pass

4 test cases · run your code against them in the editor