LeetCode 1615: Maximal Network Rank I'm posting a solution for LeetCode's &quot;Maximal Network Rank&quot;. If you'd like to review, please do so. Thank you!
Problem
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.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.
The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.
Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.
class Solution:
    def maximalNetworkRank(self, n: int, roads: List[List[int]]) -&gt; int:
        indegrees = collections.defaultdict(list)
        for i in range(n):
            for a, b in roads:
                if i == a:
                    indegrees[i].append(f'{i}-{b}')
                    indegrees[i].append(f'{b}-{i}')
                if i == b:
                    indegrees[i].append(f'{i}-{a}')
                    indegrees[i].append(f'{a}-{i}')

        max_net = 0
        for i in range(n):
            for j in range(n):
                if f'{i}-{j}' or f'{j}-{i}' in indegrees[i]:
                    net = len(set(indegrees[i] + indegrees[j])) // 2
                    max_net = max(max_net, net)

        return max_net
Avoid converting data structures to string unnecessarily
Just store tuples of values in indegrees instead of strings:
if i == a:
    indegrees[i].append((i, b))
    indegrees[i].append((b, i))

Iterate over the keys in indegrees directly
In this piece of code:
for i in range(n):
    for j in range(n):
        if f'{i}-{j}' or f'{j}-{i}' in indegrees[i]:
            ...

What you are basically saying is: for every possible pair of integers, check if it's in indegrees, and if so, do something with it. That's very inefficient if there only few elements in indegrees. Why not just iterate over the keys of indegrees instead? You can do it with strings, but then you have to parse each key back into two values, if you store tuples instead it becomes really simple:
for i, j in indegrees:
    ...