Leetcode #1615: Maximal Network Rank
In this guide, we solve Leetcode #1615 Maximal Network Rank in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Graph
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
Output: 4
Explanation: 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.
Python Solution
class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
g = [[0] * n for _ in range(n)]
cnt = [0] * n
for a, b in roads:
g[a][b] = g[b][a] = 1
cnt[a] += 1
cnt[b] += 1
return max(cnt[a] + cnt[b] - g[a][b] for a in range(n) for b in range(a + 1, n))
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.