diff --git a/src/dsa/nodes.py b/src/dsa/nodes.py index 521d24e..239e468 100644 --- a/src/dsa/nodes.py +++ b/src/dsa/nodes.py @@ -90,18 +90,21 @@ def sort_chat_inputs_first(self, vertices_layers: list[list[str]]) -> list[list[ def find_node_with_highest_degree( nodes: list[str], connections: dict[str, list[str]] ) -> str: + # Precompute incoming degree for all nodes + incoming_degree = dict.fromkeys(nodes, 0) + for targets in connections.values(): + for target in targets: + if target in incoming_degree: + incoming_degree[target] += 1 + max_degree = -1 max_degree_node = None for node in nodes: - degree = 0 - # Count outgoing connections - degree += len(connections.get(node, [])) - - # Count incoming connections - for src, targets in connections.items(): - if node in targets: - degree += 1 + # Outgoing connections/degree + out_degree = len(connections.get(node, [])) + # Total degree is outgoing + incoming + degree = out_degree + incoming_degree[node] if degree > max_degree: max_degree = degree