From 08963764ef7e1432eed9a4d65160290b31b01f0c Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Fri, 27 Jun 2025 00:20: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=2015,521%=20Here's=20an=20optimized=20v?= =?UTF-8?q?ersion=20of=20your=20code.=20Your=20profiling=20result=20shows?= =?UTF-8?q?=20the=20code=20is=20dominated=20by=20the=20repeated=20check=20?= =?UTF-8?q?of=20whether=20any=20edge=20references=20a=20node=E2=80=99s=20i?= =?UTF-8?q?d=20as=20"source".=20This=20is=20**O(N*M)**=20where=20N=20=3D?= =?UTF-8?q?=20nodes,=20M=20=3D=20edges.=20We=20can=20**precompute**=20the?= =?UTF-8?q?=20set=20of=20all=20edge=20"source"=20ids=20so=20the=20inner=20?= =?UTF-8?q?check=20is=20O(1)=20instead=20of=20O(M).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Here’s the faster rewrite (comments preserved). ### Summary of speedup. - The inner check is **O(1)** per node, not O(#edges) - The total runtime is **O(N + M)**, not **O(N*M)** - Memory: proportional to #edges (edge_sources set) **Behavior and return values are unchanged.** --- src/dsa/nodes.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/dsa/nodes.py b/src/dsa/nodes.py index 521d24e..65f8de8 100644 --- a/src/dsa/nodes.py +++ b/src/dsa/nodes.py @@ -5,7 +5,9 @@ # 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) + # Build a set of all edge source ids for fast lookup + edge_sources = {e["source"] for e in edges} + return next((n for n in nodes if n["id"] not in edge_sources), None) # Function to find all leaf nodes (nodes with no outgoing edges)