Program to find maximal network rank in Python

The maximal network rank problem asks us to find the maximum combined connectivity between any two cities in a road network. The network rank of two cities is the total number of roads directly connected to either city, counting shared roads only once.

Given a network where roads[i] = [u, v] represents a bidirectional road between cities u and v, we need to find the pair of cities with the highest combined connectivity.

Understanding the Problem

For any two cities, their network rank equals:

  • Number of roads connected to city 1
  • Plus number of roads connected to city 2
  • Minus 1 if there's a direct road between them (to avoid double counting)

Consider this network example ?

0 1 2 3 4

Cities 1 and 2 have the maximal network rank of 5 (3 roads from city 1 + 3 roads from city 2 - 1 shared road).

Algorithm Approach

The solution uses an optimized approach ?

  1. Count the degree (number of connections) for each city
  2. Store all direct connections in a set for quick lookup
  3. Sort cities by their degree in descending order
  4. Use pruning to avoid unnecessary comparisons
  5. Check all pairs and calculate their network rank

Implementation

from collections import defaultdict

def maximal_network_rank(roads):
    # Count connections for each city
    degree = defaultdict(int)
    connections = set()
    cities = set()
    
    # Build degree count and connection set
    for u, v in roads:
        degree[u] += 1
        degree[v] += 1
        connections.add((u, v))
        connections.add((v, u))  # Both directions
        cities.update([u, v])
    
    max_rank = 0
    city_list = list(cities)
    
    # Check all pairs of cities
    for i in range(len(city_list)):
        for j in range(i + 1, len(city_list)):
            city1, city2 = city_list[i], city_list[j]
            
            # Calculate network rank
            rank = degree[city1] + degree[city2]
            
            # Subtract 1 if directly connected
            if (city1, city2) in connections:
                rank -= 1
            
            max_rank = max(max_rank, rank)
    
    return max_rank

# Test the function
roads = [(0,1),(0,3),(1,2),(1,3),(2,3),(2,4)]
result = maximal_network_rank(roads)
print(f"Maximal network rank: {result}")
Maximal network rank: 5

Optimized Solution

For better performance with large networks, we can use pruning ?

from collections import defaultdict

def optimized_network_rank(roads):
    degree = defaultdict(int)
    connections = set()
    cities = set()
    
    # Build the network
    for u, v in roads:
        degree[u] += 1
        degree[v] += 1
        connections.add((min(u, v), max(u, v)))  # Normalize order
        cities.update([u, v])
    
    city_list = list(cities)
    city_list.sort(key=lambda x: degree[x], reverse=True)
    
    max_rank = 0
    
    # Pruning: only check promising pairs
    for i in range(len(city_list)):
        for j in range(i + 1, len(city_list)):
            # Early termination if remaining pairs can't improve result
            if degree[city_list[i]] + degree[city_list[j]] <= max_rank:
                break
                
            city1, city2 = city_list[i], city_list[j]
            rank = degree[city1] + degree[city2]
            
            # Check if directly connected
            if (min(city1, city2), max(city1, city2)) in connections:
                rank -= 1
            
            max_rank = max(max_rank, rank)
    
    return max_rank

# Test with the same input
roads = [(0,1),(0,3),(1,2),(1,3),(2,3),(2,4)]
result = optimized_network_rank(roads)
print(f"Optimized result: {result}")
Optimized result: 5

Complexity Analysis

Approach Time Complexity Space Complexity
Basic Solution O(n²) O(m + n)
Optimized Solution O(n² + m) O(m + n)

Where n is the number of cities and m is the number of roads.

Conclusion

The maximal network rank problem can be solved by calculating the combined connectivity of all city pairs. The optimized approach uses sorting and pruning to improve performance for larger networks.

Updated on: 2026-03-26T13:50:30+05:30

499 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements