Trace Path to Terminal Node or Cycle Entry
Trees & GraphsAuto-graded · 28 test casesLast updated
Determine the final visited node when following single-successor directed edges until reaching a dead end or a previously visited node.
You are given a directed network where every node has at most one outgoing connection. The network structure is provided via two lists of equal length, from_ids and to_ids, where from_ids[i] points to to_ids[i].
Starting from start_node_id, traverse the network step by step following the outgoing edges:
- Mark the initial node
start_node_idas visited. - If the current node has no outgoing connection (it does not exist in
from_ids), traversal stops. The current node is returned. - If the current node points to a node that has already been marked as visited, traversal stops immediately before taking that step. The current node is returned.
- Otherwise, move to the target node, mark it as visited, and continue.
Return the ID of the last node visited when traversal stops.
Constraints
1 <= start_node_id < 5000len(from_ids) == len(to_ids)and0 <= len(from_ids) <= 4999- All IDs in
from_idsandto_idssatisfy1 <= id < 5000. - All elements in
from_idsare unique (each node has at most one outgoing edge). from_ids[i] != to_ids[i]for alli(no self-loops).
Examples
Example 1
Input: compute(2, [1, 7, 3, 4, 2, 6, 9], [3, 3, 4, 6, 6, 9, 5])
Output: 5
Example 2
Input: compute(1, [1, 2, 3], [2, 3, 1])
Output: 3
Example 3
Input: compute(7, [7, 4, 5, 6], [4, 5, 6, 4])
Output: 6
Hints
Hint 1
Since each node has at most one outgoing edge, traversal is entirely deterministic.
Hint 2
Use a dictionary mapping each `from_ids[i]` to `to_ids[i]` for $O(1)$ successor lookups.
Hint 3
Keep track of visited nodes using a set, starting with `start_node_id`. If the next step points to a node already in the set, stop and return the node you are currently on.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because each node has at most one outgoing edge, the graph is functional. Traversal follows a single path without branching.
- Preprocess Edges: Construct a hash map
nxtmapping eachfrom_ids[i]toto_ids[i]. This enables $O(1)$ lookup for the successor of any node. - Track Visited Nodes: Maintain a set
seencontaining all nodes visited on the current path, initialized with{start_node_id}. - Traverse: Starting at
cur = start_node_id:- Check if
curhas an outgoing edge innxt. If not, returncur. - Identify
target = nxt[cur]. Iftargetis already inseen, returning to it would form a cycle. Stop and returncur. - If
targetis unvisited, addtargettoseen, setcur = target, and repeat.
- Check if
Complexity Analysis
- Time Complexity: $O(N)$, where $N$ is the length of
from_ids. Creating the dictionary takes $O(N)$ time. The traversal steps through each visited node at most once, performing $O(1)$ hash table and set operations per step. - Space Complexity: $O(N)$ auxiliary space to store the mapping
nxtand the setseen.
from typing import List
def compute(start_node_id: int, from_ids: List[int], to_ids: List[int]) -> int:
nxt = dict(zip(from_ids, to_ids))
seen = {start_node_id}
cur = start_node_id
while cur in nxt:
target = nxt[cur]
if target in seen:
return cur
seen.add(target)
cur = target
return cur