Sub topic 5
Degree, in-degree, and out-degree
This chapter assumes you can read Python dictionaries and sets, and that you know simple big-O notation. It also assumes you know what vertices and edges are, and that you have seen the dictionary-of-dictionaries adjacency list from earlier chapters. Here you will count the edges at a vertex, and you will see how that count changes when edges have direction or weight.
What degree measures
The degree of a vertex is the number of edge ends that touch it. In a simple undirected graph, this is the number of neighbors. Degree is the first number to compute about a vertex, because it tells you how connected that vertex is.
- A vertex with degree 0 is isolated. It exists but has no edges.
- A vertex with degree 1 is a leaf (also called a pendant vertex).
- The vertex with the highest degree is often called a hub.
Degree is a local property. You compute it by looking only at one vertex and its edges, not at the whole graph.
Degree in undirected graphs
An undirected edge is stored in both directions in our adjacency list. So the degree of u is the size of the inner dictionary graph[u], with one exception: a self-loop, an edge from a vertex to itself. By convention a self-loop adds 2 to the degree, because both ends of the edge touch the same vertex. The inner dictionary stores a self-loop as one key, so the code must add the extra count.
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
def degree(graph, u):
return sum(2 if v == u else 1 for v in graph[u])
g = {}
for a, b in [("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]:
add_edge(g, a, b)
print({u: degree(g, u) for u in g}) # {'A': 2, 'B': 2, 'C': 3, 'D': 1}
print(sum(degree(g, u) for u in g)) # 8Vertex C is the hub with degree 3, and D is a leaf. The graph has 4 edges, and the degrees add up to 8.
The handshake lemma
That result is not an accident. In any undirected graph, the sum of all degrees equals twice the number of edges:
sum of deg(v) over all v = 2 × |E|
Each edge has two ends, and each end adds 1 to some vertex's degree. This is called the handshake lemma, because each handshake involves two hands. Two consequences are useful:
- The sum of degrees is always even, so the number of odd-degree vertices is always even.
- You can check your code. If the degree sum is not twice your edge count, something is wrong, such as a missing reverse edge.
Degree in directed graphs
In a directed graph, an edge has a tail (where it starts) and a head (where it ends). One number is no longer enough, so we split degree in two:
- The out-degree of
uis the number of edges that leaveu. - The in-degree of
uis the number of edges that arrive atu.
The total degree of a vertex is in-degree plus out-degree. A self-loop counts once toward in-degree and once toward out-degree.
Consider this graph with four edges: A→B, C→B, B→D and A→D.
Here A has out-degree 2 and in-degree 0. B has in-degree 2 and out-degree 1. D has in-degree 2 and out-degree 0.
Sources and sinks
Two special cases appear often:
- A source has in-degree 0. Nothing points to it. In the graph above, A and C are sources.
- A sink has out-degree 0. It points to nothing. D is a sink.
Sources and sinks matter later. A directed acyclic graph always has at least one of each, and ordering tasks by their dependencies starts from the sources.
Computing both degrees
Out-degree is cheap with an adjacency list: it is the size of graph[u]. In-degree is not. The list stores outgoing edges only, so finding who points at u means checking every vertex.
def out_degree(graph, u):
return len(graph[u])
def in_degree(graph, u):
return sum(1 for v in graph if u in graph[v])
def all_in_degrees(graph):
counts = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
counts[v] += 1
return counts
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
d = {}
for a, b in [("A", "B"), ("C", "B"), ("B", "D"), ("A", "D")]:
add_edge(d, a, b, directed=True)
print({u: out_degree(d, u) for u in d}) # {'A': 2, 'B': 1, 'C': 1, 'D': 0}
print(all_in_degrees(d)) # {'A': 0, 'B': 2, 'C': 0, 'D': 2}
print(in_degree(d, "B")) # 2The two in-degree functions differ in cost:
| Function | Work done | Time |
|---|---|---|
| `in_degree(graph, u)` | One membership test per vertex | O(V) |
| `all_in_degrees(graph)` | One increment per edge | O(V + E) |
Calling in_degree for every vertex costs O(V²), which is worse than one pass. If you need in-degrees for many vertices, use all_in_degrees. If you need them constantly while the graph changes, store a second adjacency list of reversed edges.
The directed handshake rule
Every directed edge has exactly one tail and one head, so:
sum of in-degrees = sum of out-degrees = |E|
In the example, the in-degrees are 0, 2, 0, 2 and the out-degrees are 2, 1, 1, 0. Both sums are 4, which matches the 4 edges. This is a quick check that your edges went into the dictionary correctly.
Degree in weighted graphs
Weights do not change degree. Degree counts edges and ignores their values. If A has edges to B (weight 4) and C (weight 1), its degree is 2.
Many applications want the sum of the weights instead. This is called the weighted degree, or strength. In a road network, the degree of a town is the number of roads leaving it, and the strength is the total length of those roads.
def strength(graph, u):
return sum(graph[u].values())
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(len(weighted["A"])) # 2
print(strength(weighted, "A")) # 5This simple version counts a self-loop's weight once. Decide whether that is what you want before you use it on graphs with self-loops. For a directed weighted graph you can define in-strength and out-strength the same way.
Degree from an adjacency matrix
An adjacency matrix gives both directed degrees by summing. Row i holds the outgoing edges of vertex i, and column i holds the incoming ones.
vertices = ["A", "B", "C", "D"]
matrix = [
[0, 1, 0, 1], # A -> B, A -> D
[0, 0, 0, 1], # B -> D
[0, 1, 0, 0], # C -> B
[0, 0, 0, 0], # D has no outgoing edges
]
out_deg = [sum(row) for row in matrix]
in_deg = [sum(col) for col in zip(*matrix)]
print(dict(zip(vertices, out_deg))) # {'A': 2, 'B': 1, 'C': 1, 'D': 0}
print(dict(zip(vertices, in_deg))) # {'A': 0, 'B': 2, 'C': 0, 'D': 2}Here the roles reverse. Both degrees cost O(V) for a single vertex, because you scan one row or one column. With the list, out-degree is O(1) and in-degree is O(V) per vertex.
Edge cases and common errors
- Missing vertices.
graph[u]raisesKeyErrorifuwas never added. Theadd_edgefunction avoids this for edge endpoints by callingsetdefault(v, {}). A vertex with no edges still needs an entry, or it will vanish fromfor u in graphloops and degree reports. - Self-loops. Count them as 2 in undirected degree. Using
len(graph[u])alone gives 1. - Multi-edges. Two parallel edges between the same pair count twice in degree. A dictionary of dictionaries keeps one value per neighbor, so a second
add_edgecall overwrites the first. If you need parallel edges, store a list of weights or edge objects per neighbor. - Mixing directed and undirected edges. An undirected edge is two directed edges. If you use
directed=Falseon a graph you meant to be directed, every in-degree equals the matching out-degree, which hides the mistake. - Reading in-degree from the wrong place.
len(graph[u])is out-degree in a directed graph. Using it as the total degree undercounts every vertex that receives edges.
Summary table
| Graph type | Quantity | Adjacency list cost | Matrix cost |
|---|---|---|---|
| Undirected | Degree | O(1) | O(V) |
| Directed | Out-degree | O(1) | O(V) |
| Directed | In-degree | O(V) per vertex, O(V + E) for all | O(V) |
| Weighted | Strength | O(degree) | O(V) |
Exercise
A directed graph has 5 vertices and the edges A→B, A→C, B→C, D→C and C→E. Find the in-degree and out-degree of every vertex, list the sources and sinks, and check your answer against the directed handshake rule.
Show answer
Out-degrees: A=2, B=1, C=1, D=1, E=0. In-degrees: A=0, B=1, C=3, D=0, E=1. Sources (in-degree 0) are A and D. The only sink (out-degree 0) is E. The out-degrees sum to 5 and the in-degrees sum to 5, which equals the 5 edges, so the answer passes the check.
Exercise
An undirected graph has 6 vertices with degrees 3, 3, 2, 2, 2 and 1. Is this possible, and how many edges does it have?
Show answer
The degrees sum to 13, which is odd. The handshake lemma says the sum must equal 2 × |E|, which is always even, so no such graph exists. It also has three odd-degree vertices, but the number of odd-degree vertices must be even.