Graphs · Pattern 14 of 14

Degree counting: answers without a search

Some questions only need how many edges touch each node. Count in-degrees (or check two edges) and the answer falls out with no BFS or DFS at all.

2 variations · 2 problems

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The centre of a star, or the node every edge touches
  • Nodes that nothing points to (or that point to nothing)
  • A DAG question that looks like it needs reachability

The template

Degree Counting
// the centre of a star is in every edge, so it is in the first two
int findCenter(int[][] edges) {
    int a = edges[0][0], b = edges[0][1];
    return a == edges[1][0] || a == edges[1][1] ? a : b;
}

// in a DAG, nodes with in-degree 0 can't be reached from anything else, and they reach everything
int[] findSmallestSetOfVertices(int n, int[][] edges) {
    boolean[] hasIn = new boolean[n];
    for (int[] e : edges) hasIn[e[1]] = true;
    List<Integer> res = new ArrayList<>();
    for (int i = 0; i < n; i++) if (!hasIn[i]) res.add(i);
    return res.stream().mapToInt(Integer::intValue).toArray();
}

The variations

  1. 1The node in every edge

    A star's centre touches every edge, so it is the node the first two edges share. In general, the centre is the node with degree n − 1.

  2. 2Nodes nothing points to

    In a DAG, a node with in-degree 0 can only be reached by starting there, and every other node is reachable from some such node. So the in-degree-0 nodes are exactly the smallest starting set.

Mistakes to avoid

  • Building an adjacency list and running BFS when a count is all you need.
  • Applying the in-degree 0 rule to a graph with cycles: a cycle with no edges coming in has no in-degree-0 node, yet it still needs a start. The rule needs a DAG.
Back to Graphs →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.