KatInterview

Collect Every Reachable Page on a Single Host

Trees & GraphsModel answer
MediumModel answerTrees & Graphsgraph-traversalbfsurl-normalization

Last updated

Write a function that explores a website from one starting URL, following only links on the same hostname, and returns each distinct page once while coping with link cycles.

Problem

You are given a starting URL and a helper get_links(url) -> list[str] that returns every hyperlink found on the page at url. Write a Python function that explores the site and returns every distinct page reachable from the start without leaving the starting hostname.

Rules

  • The crawl begins at one input URL.
  • Only follow a link when its hostname is identical to the hostname of the starting URL.
  • A page must never be fetched twice.
  • Pages may link to each other in loops (A links to B, B links back to A), and your code must terminate anyway.
  • Keep going until no unseen same-host links remain.

You may use either breadth-first or depth-first traversal.

What to cover

  1. Implement the crawler.
  2. Explain how you canonicalize URLs so that different spellings of the same page are not visited repeatedly. Consider relative links, fragments, default ports, letter case, empty paths and non-web schemes such as mailto:.
  3. State which behaviors are ambiguous and which you would ask the interviewer about (for example, whether www.example.com and example.com are the same site).
  4. Give the time and space complexity, and describe how the function behaves when get_links fails or returns junk.

Hints

Hint 1

Treat the site as a directed graph whose nodes are pages and whose edges are the links returned by get_links. Cycles mean you need a visited set.

Hint 2

Decide carefully when to add a URL to the visited set. If you do it when you take a URL off the queue, a popular page can be queued many times.

Hint 3

Resolve every link against the page it appeared on with urljoin, then canonicalize it (lowercase scheme and host, remove the fragment, drop default ports, use / for an empty path) before comparing hostnames or checking the visited set.