Fewest-Hop Route Through Flaky Page Fetches
Trees & GraphsAuto-graded · 21 test casesLast updated
Run BFS on a link graph to find the lexicographically smallest fewest-hop route, where some pages fail a set number of times before their links load.
Fewest-Hop Route Through Flaky Page Fetches
A crawler wants the shortest sequence of link clicks from an origin page to a destination page. Fetching a page's outgoing links over the network can fail temporarily, so the crawler retries. To keep runs deterministic, the network is modeled with two dictionaries.
Model
links_map[url]is the list of URLs that pageurllinks to once its links load successfully. Ifurlis not a key, the page has no outgoing links. A list may contain duplicates, and it may contain the page itself.failed_attempts[url]is the number of consecutive failed fetches ofurlbefore the first successful one. Ifurlis not a key, it is0. A negative value is treated as0.- The crawler may make at most
1 + retry_limitfetch attempts per page. A negativeretry_limitis treated as0, so there is always one attempt. - A fetch of
urltherefore succeeds exactly whenfailed_attempts[url] <= retry_limit. If it does not succeed, the page is treated as having no outgoing links.
Task
Implement find_fewest_hops_route(origin, destination, links_map, failed_attempts, retry_limit=3).
Return the route as a list of URLs that starts with origin and ends with destination, following these rules:
- Fewest hops. The route must use the minimum possible number of clicks (edges).
- Tie-break. If several routes share that minimum length, return the lexicographically smallest one. Compare the routes as lists of strings, element by element from the start, using ordinary string comparison.
- Failed pages. A page whose fetch does not succeed (see the model) is a dead end. The route may not continue through it, but the destination may still be reached by another route.
- Each page fetched once. Each page's links are looked up at most once during the whole search, so cycles must not cause repeated work or infinite loops. The destination's own links are never needed.
- Trivial case. If
origin == destination, return[origin]. - No route. If the destination cannot be reached, return
[].
Constraints
- At most 10,000 distinct URLs are reachable from
origin. - Each URL is a string of at most 256 characters.
retry_limitand the values infailed_attemptsare integers, and either may be negative (treated as0).- Link lists may contain duplicates and self-links.
originanddestinationmay be absent fromlinks_map.
Examples
Example 1
Input: find_fewest_hops_route('snowflake.com/home', 'snowflake.com/careers', {'snowflake.com/home': ['snowflake.com/docs', 'snowflake.com/about'], 'snowflake.com/docs': ['snowflake.com/careers'], 'snowflake.com/about': ['snowflake.com/careers']}, {}, 3)
Output: ['snowflake.com/home', 'snowflake.com/about', 'snowflake.com/careers']
Example 2
Input: find_fewest_hops_route('a.com', 'b.com', {'a.com': ['b.com']}, {'a.com': 2}, 2)
Output: ['a.com', 'b.com']
Example 3
Input: find_fewest_hops_route('a', 'a', {'a': ['b']}, {}, 3)
Output: ['a']
Hints
Hint 1
Every click costs the same, so a breadth-first search gives the minimum number of hops. Decide first whether a page's links are available at all, using the failure count and the retry limit.
Hint 2
To get the lexicographically smallest route among the shortest, deduplicate and sort each page's links before queueing them. Then pages leave the queue in order of their routes.
Hint 3
Mark a URL as seen when you put it in the queue, not when you take it out. That guarantees each page is expanded once, and the first discovery of a URL comes via its best route. You can stop as soon as the destination is discovered.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every click has the same cost, so breadth-first search finds the route with the fewest hops. Three details make the result exact.
- Availability of links. A page's fetch succeeds exactly when its failure count (clamped to at least 0) is at most
retry_limit(clamped to at least 0). Otherwise the page contributes no links and acts as a dead end. - Sorted expansion. Before queueing a page's neighbors, remove duplicates and sort them. Each queue entry stores the full route taken so far. Within one BFS level, routes then leave the queue in lexicographic order.
- Mark on enqueue. A URL is added to the
seenset when it is queued, not when it is dequeued. No URL is queued twice, so no page is expanded twice, and cycles and self-links are harmless.
The search returns as soon as the destination is discovered, so the destination's links are never fetched. If the origin equals the destination, it returns [origin] immediately.
Why it is correct
- Fewest hops. BFS dequeues pages in non-decreasing distance. A URL is first discovered from a page at distance
d - 1, so its stored route has lengthd, which is the minimum. - Lexicographically smallest. By induction on levels, the pages of each level are dequeued in lexicographic order of their routes. Level 0 is trivially ordered. Assume level
d - 1is ordered. Children of an earlier route are queued before children of a later one, and the children of a single page are queued in sorted order. All routes at a level have the same length, so comparing two routes is decided by their parent prefix, or by the last element when the prefixes are equal. Leveldis therefore ordered too. A URL is first discovered from the earliest parent in that order, so its stored route is the smallest of its shortest routes, and that includes the destination. - Failed pages. A page that cannot be fetched simply yields no neighbors. If the destination is only reachable through such pages, the queue empties and
[]is returned. - Termination. Each URL is queued at most once and the reachable set is finite.
Complexity
Let V be the number of reachable URLs, E the number of links examined, and L the length of the answer.
- Time:
O(V + E log k), wherekis the largest out-degree because of the sort, plus up toO(V * L)for copying routes. This is fine forV <= 10,000. - Space:
O(V * L)for stored routes andO(V)for the sets. Storing a parent pointer per URL and rebuilding the route at the end reduces this toO(V).
Reference solution
from collections import deque
from typing import Dict, List
def find_fewest_hops_route(origin: str, destination: str, links_map: Dict[str, List[str]], failed_attempts: Dict[str, int], retry_limit: int = 3) -> List[str]:
if origin == destination:
return [origin]
allowed_retries = max(0, retry_limit)
expanded = set()
seen = {origin}
queue = deque([(origin, [origin])])
while queue:
page, route = queue.popleft()
if page in expanded:
continue
expanded.add(page)
failures = max(0, failed_attempts.get(page, 0))
if failures > allowed_retries:
outgoing = []
else:
outgoing = links_map.get(page, [])
for nxt in sorted(set(outgoing)):
if nxt in seen:
continue
new_route = route + [nxt]
if nxt == destination:
return new_route
seen.add(nxt)
queue.append((nxt, new_route))
return []