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 INPUT City Network Graph 0 1 2 3 n = 4 roads = [[0,1],[0,3],[1,2],[1,3]] deg:2 deg:3 deg:1 deg:2 ALGORITHM STEPS 1 Calculate Degrees Count edges for each city City: 0 1 2 3 Degree: 2 3 1 2 2 Check All Pairs Iterate (i,j) where i < j 3 Compute Rank rank = deg[i] + deg[j] If connected: rank - 1 4 Track Maximum Update maxRank each pair Best Pair: (0,1) 2 + 3 - 1 = 4 (connected) FINAL RESULT Optimal Pair Highlighted 0 1 2 3 shared Output 4 Maximal Network Rank Cities 0 and 1: OK Key Insight: Network rank of pair (i,j) = degree[i] + degree[j] - (1 if directly connected, else 0). Using an adjacency set for O(1) connection lookup, we achieve O(V^2 + E) time complexity. TutorialsPoint - Maximal Network Rank | Optimized - Degree Calculation + Direct Connection Check
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