Minimum Web Page Hop Distance
Trees & GraphsAuto-graded · 22 test casesLast 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 is0. - If
target_uriis unreachable fromstart_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
linksdictionary; 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks for the minimum path length between two nodes in an unweighted directed graph. Breadth-First Search (BFS) is optimal for this task because it explores nodes in increasing order of their distance from the start node. The first time we encounter target_uri, the path taken is guaranteed to be a shortest path.
- Base Case Check: If
start_uri == target_uri, zero clicks are required, so return0immediately. - Queue & Visited Tracking: Use a double-ended queue (
collections.deque) initialized with(start_uri, 0). Maintain a hash setvisitedinitialized withstart_urito track visited pages and prevent endless looping on graph cycles. - Traversal: Pop the front item
(page, distance)from the queue. Retrieve its outgoing links vialinks.get(page, [])to handle leaf pages safely without raisingKeyError. - Early Exit Optimization: Check if any outgoing link matches
target_uriduring neighbor exploration. If found, returndistance + 1right away. Otherwise, mark unvisited neighbors as visited and append them to the queue withdistance + 1. - Termination: If the queue becomes empty and
target_urihas not been found, return-1.
Complexity Analysis
- Time Complexity: $\mathcal{O}(V + E)$, where $V$ is the number of reachable pages and $E$ is the total number of outgoing links among reachable pages. Every node is enqueued at most once and each edge is examined once.
- Space Complexity: $\mathcal{O}(V)$ to maintain the
queueand thevisitedset.
Python Source Code
from collections import deque
from typing import Dict, List
def shortest_click_distance(start_uri: str, target_uri: str, links: Dict[str, List[str]]) -> int:
if start_uri == target_uri:
return 0
queue = deque([(start_uri, 0)])
visited = {start_uri}
while queue:
page, distance = queue.popleft()
for neighbor in links.get(page, []):
if neighbor == target_uri:
return distance + 1
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, distance + 1))
return -1