Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions src/algorithms/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,38 @@ 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)
"""Find the terminal (sink) node in a directed flow graph.

A sink node is one with zero outgoing edges — it only receives connections
and never acts as a source. In a DAG representing a pipeline or workflow,
this is the final step.

The function iterates through ``nodes`` in order and checks each node's
``"id"`` against every edge's ``"source"`` field. The first node whose id
does not match any edge source is returned immediately (short-circuit).

Parameters
----------
nodes : list[dict]
Each dict must contain an ``"id"`` key that uniquely identifies the node.
edges : list[dict]
Each dict must contain a ``"source"`` key indicating the origin node id
of that directed edge.

Returns
-------
dict or None
The first sink node found, or ``None`` if every node has at least one
outgoing edge (e.g. the graph contains a cycle with no exit point).

Notes
-----
- Only the *first* sink encountered (in ``nodes`` iteration order) is
returned. Use ``find_leaf_nodes`` to collect *all* sinks.
- The check is O(|nodes| * |edges|) because it scans edges for each node.
"""
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]:
Expand Down