KatInterview

Minimum Web Page Hop Distance

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbfsgraphshortest-path

Last updated

Find the shortest distance between two web pages in a directed link graph using breadth-first search.

You are analyzing a network of web documents where pages contain hyperlinks pointing to other pages. Navigation along these links can be modeled as traveling along directed edges in a graph.

Given an origin URL start_uri, a destination URL target_uri, and an adjacency list links mapping each page URI to a list of URIs it directly links to, determine the minimum number of hyperlink clicks needed to reach target_uri from start_uri.

Graph Properties & Rules

  • Traversing a link from page $A$ to page $B$ counts as $1$ click (a directed edge from $A$ to $B$).
  • If start_uri == target_uri, the answer is 0.
  • If target_uri is unreachable from start_uri, return -1.
  • The graph may contain cycles, disconnected components, self-referencing links, or pages with no outgoing links.
  • Some pages referenced in outgoing link lists may not appear as keys in the links dictionary; such pages have 0 outgoing links.

Constraints

  • $1 \le N \le 10,000$ total distinct URIs in the network.
  • URIs are non-empty strings.
  • Outgoing link lists may contain duplicate references or self-references.

Examples

Example 1

Input: shortest_click_distance('A', 'D', {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []})

Output: 2

Example 2

Input: shortest_click_distance('home', 'home', {'home': ['about']})

Output: 0

Example 3

Input: shortest_click_distance('A', 'D', {'A': ['B'], 'B': ['C'], 'C': ['B']})

Output: -1

Example 4

Input: shortest_click_distance('A', 'Z', {'A': ['B', 'C'], 'B': ['D'], 'C': [], 'D': []})

Output: -1

Hints

Hint 1

Since each hyperlink hop has an unweighted cost of 1, Breadth-First Search (BFS) is guaranteed to find the shortest path in terms of clicks.

Hint 2

Remember that pages might appear inside outgoing link arrays without being keys in the `links` dictionary. Use defensive retrieval like `.get(page, [])` to avoid missing key errors.

Hint 3

Keep track of visited pages with a set and mark nodes as visited when enqueuing them to avoid infinite loops caused by graph cycles.