Shortest Hop Count Through a Flaky Web Graph
Trees & GraphsModel answerLast updated
Crawl a website graph from a start URL to an exit page using BFS, retrying transient 5xx failures a limited number of times, and return the minimum hop count or -1.
Escaping a Web Maze Over Unreliable HTTP
A set of web pages forms a maze. Each page lists links to other pages, and exactly one kind of page is special: an exit page. You can only discover a page's links and whether it is an exit by requesting it through a provided client.
Implement:
def findShortestPath(startUrl: str, httpClient) -> int:
...
Client behavior
httpClient.get(url) returns a response with:
status(int): the HTTP status codelinks(list of str): the URLs this page points toisExit(bool): whether this page is the exit
How to treat each status:
| Status | Meaning | What you do |
|---|---|---|
200 | Success | Use links and isExit |
4xx | Permanent client error | Never retry; this page is a dead end |
5xx | Transient server error | Retry the same URL, up to 3 retries; if all fail, treat the page as a dead end |
Task
Return the minimum number of link traversals needed to get from startUrl to a page whose isExit is true, moving only through pages that can be fetched successfully. Return -1 if no exit can be reached.
Retries are not part of the distance. If startUrl itself is the exit, the answer is 0.
Requirements
- Use breadth-first search so the first exit you find is the closest one.
- Keep a visited set so cycles do not cause infinite loops.
- Each URL should be fetched at most once (not counting its retries).
Edge cases to handle
- The maze contains cycles, self-links, or duplicate links.
- A URL keeps returning
500past the retry limit. startUrlis the exit.- The start page itself fails.
What to explain
Describe your approach, state the time and space complexity, and write the code. Be explicit about any interpretation you chose (for example, what "3 retries" means), and be ready to discuss how you would extend the solution for rate limiting, latency-weighted paths, or a huge graph.
Hints
Hint 1
Every move between pages costs the same, so think about which classic traversal gives fewest-edge paths. You only learn a page's neighbors by fetching it, so the graph is discovered lazily.
Hint 2
Where should a retry happen? Consider what goes wrong with the queue's distance ordering if a failed URL is pushed back to the end of the queue. A small helper that loops over attempts avoids the problem.
Hint 3
Mark a URL as visited when you enqueue it, not when you dequeue it, so duplicates never enter the queue. Only trust `links` and `isExit` from a 200 response.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract first
Before coding, I would state my interpretations out loud:
- What is counted. The answer is the number of hops (link traversals) on the shortest path. If the start is the exit, the answer is
0. Retries are transport noise and do not add to the distance. If the interviewer wants requests along the path instead, it is hops + 1, a one-line change. - "Retry up to 3 times." I read this as one initial attempt plus 3 retries, so at most 4 attempts per URL. I would keep it as a named constant.
- Status handling. A
4xxor any unexpected status means the page is dead immediately. A5xxmeans retry, and if every attempt fails the page is dead. Only a200gives trustworthylinksandisExit.
Approach
All edges cost one hop, so BFS yields the shortest path. Each URL is a node and its links are outgoing edges. The graph is discovered lazily because edges are only revealed by fetching.
The key design decision is where retries live. Retry inline, in a small loop around get, before deciding the node's fate. Do not push a failed URL back onto the queue.
Re-enqueueing a failed URL is a real bug: that URL has distance d, but by the time it is retried the queue already holds nodes at distance d+1. The queue is no longer ordered by distance, so a node could be assigned a longer distance than it deserves, and a farther exit could be returned. Inline retries keep the queue monotone.
Mark URLs visited at enqueue time. This guarantees each URL is fetched once (plus retries) and keeps the queue at O(V) size. A URL that exhausted its retries stays in visited, which matches "giving up on that path."
Why it is correct
- Nodes are dequeued in non-decreasing distance order. A node gets its distance the first time it is discovered, from a node of minimal distance, so that distance is the shortest one in the graph of reachable, non-dead pages.
isExitis checked after fetching a node on dequeue, so the first exit found has minimal distance.- A dead node contributes no edges, which is right because its links cannot be learned.
- Each URL enters the queue at most once and costs at most 4 requests, and
visitedcuts cycles, so the algorithm terminates.
Complexity
- Time: O(V + E) graph work and at most 4V HTTP requests, where V is the number of reachable URLs and E the number of links. Network latency dominates in practice.
- Space: O(V) for the visited set and queue.
Code
from collections import deque
from typing import Optional
MAX_RETRIES = 3 # retries after the first attempt -> up to 4 attempts
def _fetch(url: str, http_client) -> Optional[object]:
"""Return a 200 response, or None if the URL is unusable."""
for _ in range(1 + MAX_RETRIES):
try:
resp = http_client.get(url)
except Exception:
continue # treat transport errors as transient
if resp.status == 200:
return resp
if 500 <= resp.status < 600:
continue # transient: retry
return None # 4xx / unexpected: permanent
return None # retries exhausted
def findShortestPath(startUrl: str, httpClient) -> int:
if not startUrl:
return -1
queue = deque([(startUrl, 0)])
visited = {startUrl}
while queue:
url, dist = queue.popleft()
resp = _fetch(url, httpClient)
if resp is None:
continue # dead node, no edges
if resp.isExit:
return dist
for nxt in resp.links or []:
if nxt not in visited:
visited.add(nxt)
queue.append((nxt, dist + 1))
return -1
Note that the exit check must happen on dequeue, after the fetch, because isExit is only known once the page has been retrieved. An "early exit on discovery" shortcut does not apply.
Edge cases
- Start is the exit: return
0. - Start fails (4xx, or 5xx on every attempt): return
-1. - Cycles, self-links, duplicate links: filtered by
visited. - 5xx then 200: succeeds on retry and is processed normally.
isExit=Trueon a non-200 response: ignored, since the body is untrusted.- Exit reachable only through a permanently failing node:
-1. linksisNoneor empty: treated as a leaf.
Common mistakes
- Pushing failed URLs back to the queue, which breaks BFS ordering.
- Marking visited on dequeue, which allows duplicate queue entries and repeated fetches.
- Counting retries as distance.
- Retrying 4xx responses or trusting data from error responses.
- Off-by-one on "3 retries" without stating the interpretation.
Follow-ups worth discussing
Rate limit (for example 10 requests per second). Wrap get in a token bucket so every attempt, retries included, consumes a token. Add exponential backoff with jitter between 5xx retries and honor Retry-After if present. To use the budget fully, fetch each BFS level concurrently with a bounded worker pool, processing levels in lockstep so shortest-path semantics hold.
Minimize total latency instead of hops. Edge costs are no longer uniform, so use Dijkstra with a min-heap keyed on accumulated latency. The cost belongs to the fetched node (including time lost to failed attempts) and is only known after fetching. Finalize nodes when popped and stop when the exit is popped. Latencies are non-negative, so Dijkstra applies, but they are noisy, so discuss averaging or timeout caps.
Very large graphs. Normalize URLs (case, trailing slash, query order, fragments) to avoid counting one page many times. Store 64-bit hashes instead of strings, or use a Bloom or cuckoo filter if a small false-positive rate is acceptable (it can cause a real node to be skipped, so the answer may become approximate). Beyond one machine, partition the frontier by URL hash across workers.