diff --git a/src/algorithms/graph.py b/src/algorithms/graph.py index e944b2d..b653c58 100644 --- a/src/algorithms/graph.py +++ b/src/algorithms/graph.py @@ -47,7 +47,14 @@ def find_shortest_path(self, start: str, end: str) -> list[str]: def find_last_node(nodes, edges): """This function receives a flow and returns the last node.""" - return next((n for n in nodes if all(e["source"] != n["id"] for e in edges)), None) + # If edges is empty the original implementation effectively returns the + # first node; preserve that behavior. + if not edges: + return next(iter(nodes), None) + + # Build a set of sources to avoid repeated iteration over edges + sources = {e["source"] for e in edges} + return next((n for n in nodes if n["id"] not in sources), None) def find_leaf_nodes(nodes: list[dict], edges: list[dict]) -> list[dict]: