Maximal Network Rank - Problem

Imagine you're a city infrastructure analyst tasked with evaluating road network connectivity between cities. You have n cities connected by bidirectional roads, and you need to find the maximal network rank - a measure of how well-connected any pair of cities can be.

The network rank of two different cities is calculated as:

  • Count all roads directly connected to the first city
  • Count all roads directly connected to the second city
  • Add these counts together
  • Important: If there's a direct road between these two cities, count it only once (not twice)

Your goal is to find the maximum possible network rank among all pairs of different cities.

Input: An integer n (number of cities) and a 2D array roads where roads[i] = [ai, bi] represents a bidirectional road between cities ai and bi.

Output: Return the maximal network rank as an integer.

Input & Output

example_1.py โ€” Python
$ 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. Note that the road between 0 and 1 is only counted once.
example_2.py โ€” Python
$ 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 cities 1 or 2.
example_3.py โ€” Python
$ Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
โ€บ Output: 5
๐Ÿ’ก Note: The network rank of 2 and 5 is 5. Note that all the cities do not have to be connected.

Constraints

  • 2 โ‰ค n โ‰ค 100
  • 0 โ‰ค roads.length โ‰ค n * (n-1) / 2
  • roads[i].length == 2
  • 0 โ‰ค ai, bi โ‰ค n-1
  • ai != bi
  • Each road connects two different cities
  • There are no repeated roads

Visualization

Tap to expand
0123Network Rank Analysis:City 0: degree = 2 | City 1: degree = 2 | City 2: degree = 2 | City 3: degree = 2Pair (0,1): 2 + 2 - 1 (direct) = 3Pair (2,3): 2 + 2 - 1 (direct) = 3Maximum Network Rank = 3
Understanding the Visualization
1
Build Network
Create the road network between cities
2
Count Connections
For each city, count how many roads it has
3
Check Pairs
For each pair, add their road counts
4
Avoid Double Counting
If cities are directly connected, subtract 1
5
Find Maximum
Track the highest network rank found
Key Takeaway
๐ŸŽฏ Key Insight: We only need to store degree counts and check direct connections - no need for complex graph traversal!
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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