#1615
Maximal Network Rank
MediumGraph TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
The optimal approach uses a hash map to count the degree of each city and then calculates the network rank in a single pass through the cities. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Create an array to count the degree of each city.
- 2Step 2: Populate the degree array by iterating through the roads.
- 3Step 3: For each pair of cities, calculate the network rank using the degree array and adjust for shared roads.
solution.py18 lines
1# Full working Python code
2n = 4
3roads = [[0,1],[0,3],[1,2],[1,3]]
4
5def maxNetworkRank(n, roads):
6 degree = [0] * n
7 for a, b in roads:
8 degree[a] += 1
9 degree[b] += 1
10 max_rank = 0
11 for i in range(n):
12 for j in range(i + 1, n):
13 count = (i, j) in roads or (j, i) in roads
14 rank = degree[i] + degree[j] - (1 if count else 0)
15 max_rank = max(max_rank, rank)
16 return max_rank
17
18print(maxNetworkRank(n, roads))ℹ
Complexity note: The time complexity is O(n + m) where n is the number of cities and m is the number of roads. We traverse the roads once to build the degree array and then check each pair of cities. The space complexity is O(n) for the degree array.
- 1Understanding how to calculate degrees of nodes is crucial for optimizing graph problems.
- 2Recognizing that shared connections need to be adjusted in the final rank calculation is key.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.