</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Graph Degrees and Centrality

What is this?

The "degree" of a dot is simply how many lines touch it โ€” how many friends a person has, how many roads meet at a junction. It's the easiest measure of how important or well-connected something is. The surprising lesson here is that you often don't need any fancy exploration at all: many "find the most popular node" or "find the special node everyone points to" questions are answered by just counting the lines, one quick pass and you're done.

flowchart TD A["Walk through every connection once"] --> B["Add one to the count of each endpoint"] B --> C["Now you have a degree for every node"] C --> D["Read the answer straight off the counts"]

๐Ÿ’ก Fun fact: Google's original PageRank is a souped-up version of degree counting. Instead of just tallying how many links point to a page, it weighs each incoming link by how important the linking page itself is โ€” so a single link from a famous site can outweigh thousands from obscure ones. Degree was the seed of a company worth trillions.

๐Ÿ”“ The 2 problems in this chapter are free. Sign in with Google or Microsoft to start solving.


The one-line idea: before you reach for BFS or DFS, ask whether a node's degree โ€” how many edges touch it โ€” already answers the question. A surprising number of "find the special / most-connected node" problems are pure counting: one pass over the edges builds a degree array, and the answer falls out in O(V + E) with no traversal at all.


1. What degree & centrality really mean

The degree of a node is the number of edges incident to it โ€” the simplest possible measure of "how connected" or "how important" that node is. In a directed graph it splits in two:

Directed vs undirected degree: in-degree(b)=2, out-degree(b)=1; degree(b)=1, degree(c)=2

  • In-degree counts arrows pointing in; out-degree counts arrows pointing out. Their roles are not interchangeable โ€” mixing them is the classic bug.
  • Undirected degree is a single count: edges touching the node.

Degree is the cheapest centrality measure โ€” a node's raw connectivity. Its richer cousins answer subtler "importance" questions and cost more to compute (conceptually, you don't need them for this chapter):

  • Betweenness centrality โ€” how many shortest paths run through a node (a bridge / chokepoint).
  • Closeness centrality โ€” how short the node's average distance to everyone else is (a fast broadcaster).
  • PageRank โ€” importance weighted by the importance of who points to you (recursive degree).

This chapter stays on the ground floor โ€” degree โ€” because it alone cracks a whole family of problems.


2. Where you'll actually meet this

Degree counting is a real, everyday analysis primitive:

  • Distributed systems. Hub / leader detection (the node everyone acknowledges that defers to none = in-degree n-1, out-degree 0); load hotspots (the shard or broker with the most connections is the one to split first).
  • Networking. Critical routers โ€” high-degree nodes whose failure fragments the network; pairs of routers whose combined link count bounds a failure domain.
  • Social & recommendation graphs. Influencer detection (high in-degree = many followers), universally-followed accounts, highest-reach co-promotion pairs.
  • Dependency & build graphs. A foundational module is a degree sink โ€” everything imports it, it imports nothing.

If a problem says find the node everyone points to, the most-connected vertex, the busiest pair, the trusted root โ€” reach for degrees before traversal.


3. The degrees toolkit (patterns to recognise)

  1. Build a degree array in one edge pass. For each edge (a, b), bump the relevant counter(s). Directed: out[a] += 1, in[b] += 1. Undirected: deg[a] += 1, deg[b] += 1. One O(E) sweep, done.
  2. The in-minus-out trick. When the special node is defined by both a high in-degree and a zero out-degree, fold them into a single signed score: degree[b] += 1, degree[a] -= 1 per edge aโ†’b. One number, one comparison.
  3. Adjacency set for "are these two connected?" Store each undirected edge as a frozenset({a, b}) (or a sorted tuple). Membership is O(1) and memory scales with edges, not nยฒ โ€” essential when a pair's answer depends on whether they share an edge.
  4. Degree as an O(V + E) pre-pass. Compute degrees once, then run the cheap logic on top โ€” an O(nยฒ) pair sweep or an O(V) scan for the special node. The expensive-looking part becomes pure arithmetic over precomputed counts.

4. A 30-second worked example (count degrees)

Undirected graph, who's most connected?

Counting degrees in one edge pass: edges 0-1,1-2,1-3,2-4 give final deg [1,3,2,1,1]; node 1 is the hub with degree 3

One pass over four edges, no traversal โ€” the most-connected node reads straight off the array. That counting reflex powers every problem below.


5. Problems in this chapter

โ–ถ Find the Town Judge

Find the one node everyone points to that points to nobody (a trusted root / elected leader). Fold each edge into a signed score degree = in โˆ’ out; the unique node ending at exactly n-1 is the answer.
Pattern: signed in-minus-out degree. Target: O(V + E), O(V).

โ–ถ Maximal Network Rank

Find the pair of nodes whose combined edge count is highest (the busiest two-router slice). Precompute degrees + an adjacency set, then sweep all pairs: deg(a) + deg(b), minus 1 if they share an edge.
Pattern: degree precompute + pairwise sweep with shared-edge correction. Target: O(E + nยฒ), O(n + E).


6. Common pitfalls ๐Ÿšซ

  • Mixing in-degree and out-degree. In a directed problem, "trusts" vs "is trusted" are opposite counters. Swapping them silently returns the wrong node โ€” keep their roles straight (or use the signed trick where the sign encodes direction).
  • Forgetting the shared-edge subtraction. When a pair's score combines two degrees, an edge between them was counted twice. Miss the โˆ’1 and connected pairs are over-ranked.
  • Assuming highest-degree wins. For pair problems, two top-degree nodes that are directly connected lose 1; a lower-degree unconnected pair can beat them. Always check the shared edge.
  • Reaching for BFS/DFS. If the answer is a degree signature, traversal is wasted work โ€” count edges instead.
  • Off-by-one / indexing. 1-based labels (1โ€ฆn) vs 0-based (0โ€ฆn-1), and the n-1 in-degree threshold, are where these problems are quietly won or lost.

7. Key takeaways

  1. Degree first, traversal later. Many "special / most-connected node" questions are answered by counting edges in O(V + E) โ€” no BFS/DFS needed.
  2. One edge pass builds every degree. Directed โ†’ separate in/out (or a signed score); undirected โ†’ one count per endpoint.
  3. The in-minus-out trick packs "high in-degree and zero out-degree" into a single number and a single comparison.
  4. An adjacency set answers "connected?" in O(1) with edge-sized memory โ€” the key to pair problems with a shared-edge correction.
  5. Degree is the simplest centrality; betweenness, closeness, and PageRank are its richer cousins โ€” good to name, unneeded here. Interviewers lean on this family because it rewards spotting counting over traversal.

Maximal Network Rank

Core idea: The "rank" of a pair of nodes is just the count of edges touching either of them: deg(a) + deg(b). But if a and b are directly connected, that shared edge got counted twice โ€” once in deg(a), once in deg(b) โ€” so subtract 1. Precompute every node's degree in one edge pass, store the edges in a set for O(1) "are these two connected?", then sweep all pairs picking the maximum. No edge re-counting per pair.


1. The problem, in a fresh setting

You operate a backbone of n routers, labelled 0โ€ฆn-1, joined by bidirectional links: links[i] = [a, b] is a cable between routers a and b (at most one cable per pair). To plan a redundant failover pair, you want the two routers whose combined link count is highest โ€” the busiest two-router slice of the network.

The rank of a pair (a, b) is the number of distinct links attached to either router. A link that runs directly between a and b is one cable, so it counts once, not twice. The maximal network rank is the largest pair-rank over all pairs.

Given n and links, return the maximal network rank.

n links Degrees Best pair Rank
4 [[0,1],[0,2],[1,2],[1,3]] [2,3,2,1] (0,1) connected 4
5 [[0,1],[0,3],[1,2],[2,3],[2,4]] [2,2,3,2,1] (2,3) connected 4
6 [[0,1],[1,2],[3,4],[3,5]] [1,2,1,2,1,1] (1,3) not conn. 4

(For (0,1) in row 1: deg(0)+deg(1) = 2+3 = 5, minus 1 shared link โ†’ 4.)


Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.