KatInterview

Shortest Hop Count Through a Flaky Web Graph

Trees & GraphsModel answer
HardModel answerTrees & Graphsbfsgraph-traversalretry-logic

Last 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 code
  • links (list of str): the URLs this page points to
  • isExit (bool): whether this page is the exit

How to treat each status:

StatusMeaningWhat you do
200SuccessUse links and isExit
4xxPermanent client errorNever retry; this page is a dead end
5xxTransient server errorRetry 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 500 past the retry limit.
  • startUrl is 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.