KatInterview

Minimum Hops Between Two Tasks in a Dependency Graph

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsgraphbfsshortest-path

Last updated

Find the fewest directed edges from a start node to a goal node in an acyclic graph, returning 0 for identical nodes and -1 when unreachable; tests BFS on unit-weight graphs.

Minimum Hops in a One-Way Network

A system has n stations numbered 0 through n - 1. Connections between them are one-way: each entry [a, b] in links means you can travel from station a to station b, but not from b back to a. The network contains no cycles and no connection from a station to itself.

You start at station start and want to reach station goal. Return the minimum number of connections you must use to get there.

Function Signature

def min_hops(n: int, links: list[list[int]], start: int, goal: int) -> int:

Rules

  • A connection [a, b] may only be used in the direction a to b.
  • If start == goal, the answer is 0, even if that station has no connections.
  • If there is no way to reach goal from start following connections in their direction, return -1.
  • The same connection may appear several times in links; duplicates do not affect the answer.
  • Return a single integer.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(links) <= 2 * 10^5
  • 0 <= a, b, start, goal < n for every [a, b] in links
  • The graph has no directed cycles and no self-loops.

Examples

Example 1

Input: min_hops(6, [[0, 1], [1, 2], [2, 5], [0, 3], [3, 5], [1, 4]], 0, 5)

Output: 2

Example 2

Input: min_hops(6, [[0, 1], [1, 2], [2, 5], [0, 3], [3, 5], [1, 4]], 3, 2)

Output: -1

Example 3

Input: min_hops(3, [[0, 1]], 2, 2)

Output: 0

Hints

Hint 1

Every connection costs exactly one hop, so you are looking for a shortest path in an unweighted graph.

Hint 2

Build an adjacency list that stores only the a -> b direction, then explore outward from start level by level using a queue.

Hint 3

Mark a station as visited when you add it to the queue, record its hop count then, and stop as soon as goal is discovered. Handle start == goal before anything else.