From b635298ea37f92dc332c508a321d4aa01207509e Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Fri, 27 Jun 2025 02:00:28 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20function=20`f?= =?UTF-8?q?ind=5Flast=5Fnode`=20by=2016,012%=20Here=E2=80=99s=20a=20rewrit?= =?UTF-8?q?ten,=20**optimized**=20version=20of=20the=20given=20program.=20?= =?UTF-8?q?The=20original=20code=20is=20**O(n=C2=B7m)**,=20where=20`n`=20i?= =?UTF-8?q?s=20the=20number=20of=20nodes=20and=20`m`=20is=20the=20number?= =?UTF-8?q?=20of=20edges,=20because=20for=20each=20node,=20it=20checks=20a?= =?UTF-8?q?ll=20edges.=20We=20can=20make=20it=20**O(n=20+=20m)**=20by=20fi?= =?UTF-8?q?rst=20collecting=20all=20nodes=20that=20are=20referenced=20as?= =?UTF-8?q?=20`"source"`=20in=20any=20edge.=20Then,=20the=20last=20node=20?= =?UTF-8?q?is=20any=20node=20whose=20`"id"`=20is=20**not**=20in=20this=20s?= =?UTF-8?q?et.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Key improvement:** - Turns the repeated search of all edges per node into a set lookup, which is O(1) per node. - This reduces complexity from O(n·m) to O(n + m). - The result is identical to your original code. --- src/dsa/nodes.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/dsa/nodes.py b/src/dsa/nodes.py index 521d24e..77d01e2 100644 --- a/src/dsa/nodes.py +++ b/src/dsa/nodes.py @@ -5,7 +5,10 @@ # derived from https://github.com/langflow-ai/langflow/pull/5261 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) + # Create a set of all node ids that are used as source in edges + source_ids = {e["source"] for e in edges} + # Return the first node whose id is not in the set of source_ids + return next((n for n in nodes if n["id"] not in source_ids), None) # Function to find all leaf nodes (nodes with no outgoing edges)