Python 1615.py
class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
all = defaultdict(set)
for i in roads:
a = i[0]
b = i[1]
all[a].add(b)
all[b].add(a)
best = 0
cities = sorted(all.keys())
for i in range(len(cities)):
for j in range(i+1, len(cities)):
x = cities[i]
y = cities[j]
sum = len(all[x]) + len(all[y])
if y in all[x]:
sum -= 1
if best < sum:
best = sum
return best
Difficulty
and has an acceptance rate of about 66% (200k+ submissions).
Typical patterns to solve this problem:
- Graph Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the maximal network rank for a set of cities connected by roads. The network rank of a pair of distinct cities is defined as the total number of roads that are incident to either city, counting a shared road only once. The algorithm builds adjacency information, iterates over every unordered pair of cities, evaluates their combined degree, adjusts for a direct connection, and tracks the highest rank encountered.
Construction of the adjacency map
The first logical block creates a dictionary where each city maps to the set of its neighboring cities.
all = defaultdict(set)
for i in roads:
a = i[0]
b = i[1]
all[a].add(b)
all[b].add(a)
By using a defaultdict of sets, duplicate entries are automatically eliminated, and the presence test for a direct road later becomes an O(1) operation. The loop processes each road exactly once, establishing a bidirectional relationship between the two endpoints.
Preparation for pairwise evaluation
Before examining city pairs, the code extracts the list of cities that actually appear in the adjacency map and sorts them.
best = 0
cities = sorted(all.keys())
Sorting is not required for correctness, but it guarantees a deterministic order of iteration, which can be helpful for reproducibility and debugging.
Pairwise rank calculation
The core of the algorithm consists of two nested loops that generate every unordered pair of distinct cities. For each pair, the sum of the degrees (the number of incident roads) is computed, and a correction is applied if the two cities share a direct road.
for i in range(len(cities)):
for j in range(i+1, len(cities)):
x = cities[i]
y = cities[j]
sum = len(all[x]) + len(all[y])
if y in all[x]:
sum -= 1
if best < sum:
best = sum
The inner if y in all[x] check efficiently determines whether the current pair is directly connected, allowing the algorithm to subtract the double-counted road exactly once. The conditional update of best preserves the maximum rank found so far.
Edge-case handling
The code naturally accommodates several edge conditions:
- When the input contains no roads, the adjacency map remains empty,
citiesbecomes an empty list, and the nested loops are never entered. The function returns the initial value ofbest, which is zero, correctly representing that no network rank exists. - If a city has no incident roads but appears in the
roadslist (which cannot happen because each road contributes two endpoints), the set for that city would be empty, and its degree would be zero. The pairwise logic still works because the sum of degrees correctly reflects the lack of connections. - Duplicate road entries are collapsed by the set structure, ensuring that the degree counts are accurate even if the input contains repeated road definitions.
- The algorithm gracefully handles the situation where all cities are fully connected (a complete graph). In that case, every pair shares a direct road, and the subtraction step guarantees that the rank does not exceed the total number of distinct roads.
Implicit performance optimizations
Several choices in the implementation contribute to efficient execution:
- Storing neighbors in a set provides constant-time membership tests (
y in all[x]) and prevents duplicate edges without extra processing. - The adjacency map is built in a single pass over the
roadslist, avoiding any need for secondary data structures. - By iterating only over the sorted list of keys, the algorithm limits its inner loop to actual cities that have at least one incident road, skipping isolated indices that would otherwise add unnecessary iterations.
- The use of integer variables (
best,sum) and direct length queries (len(all[x])) keeps the per-pair computation lightweight, allowing the double loop to run with minimal overhead.
Overall, the solution follows a clear, methodical approach to derive the maximal network rank, handling special input configurations and employing data structures that streamline both construction and query phases.
ELI5 - Simplified Explanation
Imagine a giant map of cities connected by long roads. The goal is to find two cities that have the most roads connected to them added together.
The code starts by creating a special list to keep track of which cities are joined by roads. It looks at every road on the map one by one. If a road goes between city A and city B, it makes a note in the list that city A is connected to city B and city B is connected to city A.
After drawing all the connections, the code searches for the best pair of cities. It picks two different cities and counts how many roads each one has. It adds those counts together to find the total number of roads for that pair. If those two cities share a road between each other, the code subtracts one because that single road shouldn't be counted twice.
The code keeps going through every single pair of cities on the map. It constantly compares the current total to the highest total found so far. Whenever it finds a pair with more roads than any previous pair, it updates the record to keep the bigger number. Once it finishes checking every combination of cities, it knows exactly what the highest possible number of connected roads is.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 205: Isomorphic Strings
- problem 905: Sort Array By Parity
- problem 922: Sort Array By Parity II
- problem 2423: Remove Letter To Equalize Frequency
- problem 18: 4Sum
- problem 80: Remove Duplicates from Sorted Array II
- problem 92: Reverse Linked List II
- problem 93: Restore IP Addresses
- problem 384: Shuffle an Array
- problem 1143: Longest Common Subsequence
- problem 32: Longest Valid Parentheses
- problem 149: Max Points on a Line
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality