AlgoTales · Roadmap

Degree

Beginner · 6 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The degree of a dot in a graph is how many lines touch it. A high degree means a busy hub such as a popular user or a central station, and a degree of zero means a dot that is not connected to anything.

Practical use cases

  • Web app: Most connected users. A community site wants a "Top connectors" badge. Counting the lines on each user, meaning how many friends they have, gives each one a degree and the highest ones get the badge. A simple count per user is all that is needed, not a complicated search. The count can be kept up to date as friendships change.
  • Web app: Orphan pages and hub pages. A CMS tracks which pages link to which. Pages with zero incoming links are orphans that nobody can reach from the menu, and pages with very many links are hubs. Counting degrees on the link graph gives the SEO team both lists in one pass.
  • System: Network hubs and build order. Network planners look for the busiest router, whose failure would hurt most. Build tools count how many things each module depends on, and start with modules that have none. Hubs and loners are both easy to find once you have the counts.

The story: Who Has the Most Friends?

At Aarav's birthday party, Mrs. Sharma wanted to hand out a "Most Popular" sticker. She did not ask anyone to vote. She asked Mira to draw a line between every two kids who were friends and then count the lines at each kid.

Aarav had three lines, Zoya two, Kabir two, Mira two, and the new boy Rohan only one. "Three lines! Aarav is the most connected," said Mira. Rohan blushed, but Mrs. Sharma saw the chance: "Let us introduce Rohan to some people!"

Mira then noticed a funny thing. She added all the numbers up: 3 + 2 + 2 + 2 + 1 = 10. But she had drawn only 5 lines. "Ten is double five!" she cried. Teacher explained: every line has two ends, so it gets counted once at each kid.

That count of lines at a vertex is called its degree. When arrows exist, we count arrows going out (out-degree) and arrows coming in (in-degree) separately.

How to spot this problem, and where you need it

You want to know which items are most connected, least connected, or not connected at all, and you want a simple number for each.

Signs you need it

  • The feature talks about "most popular", "busiest", "influencer", "hub" or "no links at all".
  • You run a heavy query to count each user's friends again and again.
  • The task says "find the node with the maximum degree" or "which node has no edges".

Where to use it in a project

  • Social features such as ranking influencers or finding users with no connections.
  • Site and dependency audits that look for hub pages, orphan pages or modules with no dependencies.

The solution

For an undirected graph, the degree of a dot is the number of lines at that dot, which is simply the length of its neighbour list. For a directed graph, count lines coming in (in-degree) and lines going out (out-degree) separately. Loop over all dots once, store the counts, and then pick the biggest, the smallest or the zeros.

Payoff: Before: a count query per user on every page load. After: counts kept per dot, so ranking 100,000 users is one pass.

Explain it like I am 8

Look at one dot in a drawing and count how many lines are stuck to it. That number is its degree. A dot with many lines is like the child with many friends. A dot with zero lines is a child sitting alone.

How it works, step by step

  1. Pick a vertex.
  2. Count the edges that touch it. That count is its degree (for an undirected graph).
  3. For directed graphs count separately: arrows out (out-degree) and arrows in (in-degree).
  4. Shortcut with a list: in an adjacency list, the degree is simply the length of that vertex's list.
  5. Sanity check: the sum of all degrees is always exactly twice the number of edges.

The code in four languages

PHP

<?php
// Degrees from an edge list (undirected): every edge adds 1 to BOTH ends.
$edges = [['A','B'], ['A','C'], ['A','D'], ['B','C'], ['D','E']];
$degree = [];
foreach ($edges as [$a, $b]) {
    $degree[$a] = ($degree[$a] ?? 0) + 1;
    $degree[$b] = ($degree[$b] ?? 0) + 1;
}
ksort($degree);
foreach ($degree as $v => $d) echo "$v has degree $d\n";
echo 'Sum of degrees = ' . array_sum($degree) . ', edges = ' . count($edges) . "\n";

// Directed: out-degree counts the giver, in-degree counts the receiver.
$arrows = [['A','B'], ['A','C'], ['C','B'], ['D','A']];
$in = []; $out = [];
foreach ($arrows as [$from, $to]) {
    $out[$from] = ($out[$from] ?? 0) + 1;
    $in[$to] = ($in[$to] ?? 0) + 1;
}
echo 'B in-degree: ' . $in['B'] . ', A out-degree: ' . $out['A'] . "\n";

JavaScript

// Degrees from an edge list (undirected): every edge adds 1 to BOTH ends.
const edges = [['A','B'], ['A','C'], ['A','D'], ['B','C'], ['D','E']];
const degree = {};
for (const [a, b] of edges) {
  degree[a] = (degree[a] || 0) + 1;
  degree[b] = (degree[b] || 0) + 1;
}
for (const v of Object.keys(degree).sort()) console.log(v + ' has degree ' + degree[v]);
const sum = Object.values(degree).reduce((s, d) => s + d, 0);
console.log('Sum of degrees = ' + sum + ', edges = ' + edges.length);

// Directed: out-degree counts the giver, in-degree counts the receiver.
const arrows = [['A','B'], ['A','C'], ['C','B'], ['D','A']];
const inDeg = {}, outDeg = {};
for (const [from, to] of arrows) {
  outDeg[from] = (outDeg[from] || 0) + 1;
  inDeg[to] = (inDeg[to] || 0) + 1;
}
console.log('B in-degree: ' + inDeg['B'] + ', A out-degree: ' + outDeg['A']);

Java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Degrees from an edge list (undirected): every edge adds 1 to BOTH ends.
        String[][] edges = {{"A", "B"}, {"A", "C"}, {"A", "D"}, {"B", "C"}, {"D", "E"}};
        Map<String, Integer> degree = new TreeMap<>();   // TreeMap keeps the names sorted
        for (String[] e : edges) {
            degree.merge(e[0], 1, Integer::sum);
            degree.merge(e[1], 1, Integer::sum);
        }
        int sum = 0;
        for (var entry : degree.entrySet()) {
            System.out.println(entry.getKey() + " has degree " + entry.getValue());
            sum += entry.getValue();
        }
        System.out.println("Sum of degrees = " + sum + ", edges = " + edges.length);

        // Directed: out-degree counts the giver, in-degree counts the receiver.
        String[][] arrows = {{"A", "B"}, {"A", "C"}, {"C", "B"}, {"D", "A"}};
        Map<String, Integer> in = new HashMap<>();
        Map<String, Integer> out = new HashMap<>();
        for (String[] arrow : arrows) {
            out.merge(arrow[0], 1, Integer::sum);
            in.merge(arrow[1], 1, Integer::sum);
        }
        System.out.println("B in-degree: " + in.get("B") + ", A out-degree: " + out.get("A"));
    }
}

Go

package main

import (
	"fmt"
	"sort"
)

func main() {
	// Degrees from an edge list (undirected): every edge adds 1 to BOTH ends.
	edges := [][2]string{{"A", "B"}, {"A", "C"}, {"A", "D"}, {"B", "C"}, {"D", "E"}}
	degree := map[string]int{}
	for _, e := range edges {
		degree[e[0]]++ // a missing key starts at 0, so ++ just works
		degree[e[1]]++
	}
	names := make([]string, 0, len(degree))
	for v := range degree {
		names = append(names, v)
	}
	sort.Strings(names) // map order is random in Go, so sort the names
	sum := 0
	for _, v := range names {
		fmt.Println(v, "has degree", degree[v])
		sum += degree[v]
	}
	fmt.Printf("Sum of degrees = %d, edges = %d\n", sum, len(edges))

	// Directed: out-degree counts the giver, in-degree counts the receiver.
	arrows := [][2]string{{"A", "B"}, {"A", "C"}, {"C", "B"}, {"D", "A"}}
	in, out := map[string]int{}, map[string]int{}
	for _, arrow := range arrows {
		out[arrow[0]]++
		in[arrow[1]]++
	}
	fmt.Printf("B in-degree: %d, A out-degree: %d\n", in["B"], out["A"])
}

Time: O(V + E) · Extra space: O(V). One pass over the edges counts every degree. With an adjacency list, one vertex's degree is just the list length, O(1).

Watch out for

  • Counting an undirected edge only at one end, which makes the degree sum come out wrong.
  • Mixing up in-degree and out-degree in a directed graph.
  • Counting a self-loop (a vertex joined to itself) once. By convention it adds 2 to the degree.

Quick check

  1. A vertex has 4 lines touching it. Its degree is…
    • 2
    • 4
    • 3
  2. A graph has 6 edges. What is the sum of all degrees?
    • 6
    • 3
    • 12
  3. In a follower graph (arrows point from follower to followed), which degree tells the number of followers?
    • In-degree
    • Out-degree
    • Neither