Maximal Network Rank - Problem

There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.

The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.

The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.

Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.

Input & Output

Example 1 — Basic Network
$ Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
Output: 4
💡 Note: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
Example 2 — Simple Network
$ Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
Output: 5
💡 Note: There are 5 roads that are connected to either 1 or 2. Since 1 and 2 are not directly connected, we don't subtract anything.
Example 3 — No Roads
$ Input: n = 8, roads = []
Output: 0
💡 Note: The maximal network rank is 0 since there are no roads.

Constraints

  • 2 ≤ n ≤ 100
  • 0 ≤ roads.length ≤ n × (n-1) / 2
  • roads[i].length == 2
  • 0 ≤ ai, bi ≤ n-1
  • ai ≠ bi
  • Each pair of cities has at most one road connecting them

Visualization

Tap to expand
Maximal Network Rank Problem0123Roads: [0,1], [0,3], [1,2], [1,3]Network RankCities 0 & 1:2 + 3 - 1 = 4Maximum4Network rank = total roads connected to either city (count shared road once)
Understanding the Visualization
1
Input
Cities and roads connecting them
2
Calculate
For each pair: sum degrees, subtract if direct connection
3
Output
Maximum network rank found
Key Takeaway
🎯 Key Insight: Pre-calculate degrees for O(1) lookup, then check all pairs efficiently
Asked in
Google 12 Facebook 8 Microsoft 6 Amazon 4
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen