Maximal Network Rank

Medium

Topics
GraphArray

There are n cities and some undirected roads given as edges. The network rank of two different cities is the total number of roads directly connected to either city; a road connecting both counts only once. Return the maximum network rank over all pairs of cities.

Example 1

0123
the best pair
The rank of a pair is the number of edges touching either node. The subtlety is that an edge joining the two nodes themselves would be counted twice, so it is subtracted once. The shaded pair ranks 4.
Nodes are drawn on a circle; an edge list says nothing about layout, only about connections.
Input:  n = 4, edges = [[0,1],[0,3],[1,2],[1,3]]
Output: 4

Example 2

01234
the best pair
Input:  n = 5, edges = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
Output: 5

Constraints

  • 2 <= n <= 100
  • No repeated roads and no self-loops.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The rank of a pair is deg(i) + deg(j), minus one if the two cities are joined, since that road would otherwise be counted from both ends. Degrees are computed once up front, so the only per-pair work left is a single adjacency test.

With n <= 100 there are at most 4,950 pairs. Scanning all of them is not a fallback, it is the intended solution — and worth saying out loud, because the instinct to find something cleverer is what produces wrong answers here.

Approach

  1. Count the degree of every city in one pass over the roads.
  2. Record adjacency in a set of ordered pairs, inserting both (a,b) and (b,a), or in an n × n boolean matrix.
  3. For every pair i < j, take deg(i) + deg(j) and subtract one when the pair is adjacent. Keep the maximum.

Dry Run

n = 4   edges = [[0,1],[0,2],[1,2],[2,3]]

degrees  [2, 2, 3, 1]

  pair   deg sum   shared road   rank
  (0,1)     4          yes         3
  (0,2)     5          yes         4
  (0,3)     3          no          3
  (1,2)     5          yes         4
  (1,3)     3          no          3
  (2,3)     4          yes         3

answer 4

Complexity

  • Time — O(n²): the pair scan is n(n-1)/2 iterations with O(1) work each. Building the degree table costs O(E), and since E <= n(n-1)/2 that is absorbed.
  • Space — O(n + E): the degree array is O(n) and the adjacency set is O(E), which in the dense case is O(n²). An n × n boolean matrix is the same order and has a better constant than a hash set of tuples.

Common Pitfalls

  • Taking the two highest degrees and stopping. In the dry run above those are 3 and 2, giving 5, but cities 2 and 0 share a road so the real best is 4. The shortcut is wrong whenever the two highest-degree cities happen to be connected, which is common in dense graphs.
  • Forgetting the subtraction entirely, which inflates every adjacent pair by one.
  • Storing adjacency as (a,b) only. Half the lookups then miss, because the pair loop always probes (i,j) with i < j while the edge list has no such order. Insert both directions, or normalise each pair before inserting.
  • Using the edge list for the adjacency test instead of a set, which makes each of the 4,950 pair checks a linear scan.
  • Reaching for a cleverer algorithm. At n <= 100 there is nothing to optimise, and the complexity to state is O(n²), not something smaller.

Full Solution — all languages

class Solution:
    def maximalNetworkRank(self, n, edges):
        deg = [0] * n
        conn = set()
        for a, b in edges:
            deg[a] += 1
            deg[b] += 1
            conn.add((a, b))
            conn.add((b, a))
        best = 0
        for i in range(n):
            for j in range(i + 1, n):
                rank = deg[i] + deg[j] - (1 if (i, j) in conn else 0)
                if rank > best:
                    best = rank
        return best
SensAI
Beta
Tap the mic to stop voice mode