KatInterview

Trace Path to Terminal Node or Cycle Entry

Trees & GraphsAuto-graded · 28 test cases
EasyAuto-gradedTrees & Graphstrees-graphsarrayshash-table

Last 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:

  1. Mark the initial node start_node_id as visited.
  2. If the current node has no outgoing connection (it does not exist in from_ids), traversal stops. The current node is returned.
  3. 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.
  4. 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 < 5000
  • len(from_ids) == len(to_ids) and 0 <= len(from_ids) <= 4999
  • All IDs in from_ids and to_ids satisfy 1 <= id < 5000.
  • All elements in from_ids are unique (each node has at most one outgoing edge).
  • from_ids[i] != to_ids[i] for all i (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.