Maximal Network Rank
Medium
Topics
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
Input: n = 4, edges = [[0,1],[0,3],[1,2],[1,3]] Output: 4
Example 2
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
- Count the degree of every city in one pass over the roads.
- Record adjacency in a set of ordered pairs, inserting both
(a,b)and(b,a), or in ann × nboolean matrix. - For every pair
i < j, takedeg(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 4Complexity
- Time — O(n²): the pair scan is
n(n-1)/2iterations with O(1) work each. Building the degree table costs O(E), and sinceE <= n(n-1)/2that 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 × nboolean 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)withi < jwhile 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 <= 100there 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 bestimport java.util.*;
class Solution {
public int maximalNetworkRank(int n, int[][] edges) {
int[] deg = new int[n];
Set<Integer> conn = new HashSet<>();
for (int[] e : edges) {
deg[e[0]]++;
deg[e[1]]++;
conn.add(e[0] * n + e[1]);
conn.add(e[1] * n + e[0]);
}
int best = 0;
for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) {
int rank = deg[i] + deg[j] - (conn.contains(i * n + j) ? 1 : 0);
if (rank > best) best = rank;
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maximalNetworkRank(int n, vector<vector<int>>& edges) {
vector<int> deg(n, 0);
unordered_set<int> conn;
for (auto& e : edges) {
deg[e[0]]++;
deg[e[1]]++;
conn.insert(e[0] * n + e[1]);
conn.insert(e[1] * n + e[0]);
}
int best = 0;
for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) {
int rank = deg[i] + deg[j] - (conn.count(i * n + j) ? 1 : 0);
if (rank > best) best = rank;
}
return best;
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/ var maximalNetworkRank = function(n, edges) {
const deg = new Array(n).fill(0);
const conn = new Set();
for (const [a, b] of edges) {
deg[a]++;
deg[b]++;
conn.add(a * n + b);
conn.add(b * n + a);
}
let best = 0;
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
const rank = deg[i] + deg[j] - (conn.has(i * n + j) ? 1 : 0);
if (rank > best) best = rank;
}
return best;
};