Collect Every Reachable Page on a Single Host
Trees & GraphsModel answerLast 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
- Implement the crawler.
- 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:. - State which behaviors are ambiguous and which you would ask the interviewer about (for example, whether
www.example.comandexample.comare the same site). - Give the time and space complexity, and describe how the function behaves when
get_linksfails 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The site is an implicit directed graph: pages are nodes, and get_links(url) lists a node's outgoing edges. We cannot see the whole graph up front, and it may contain cycles, so this is a standard graph search with a visited set.
- Canonicalize the start URL and remember its hostname.
- Keep a
seenset and a frontier (a queue for BFS, a stack for DFS). - Take a URL from the frontier and fetch its links. For each link:
- resolve it against the current page, since it may be relative;
- canonicalize it;
- discard it if the scheme is not http(s), the hostname differs, or it is already in
seen; - otherwise add it to
seenand to the frontier.
- Stop when the frontier is empty.
Mark on enqueue
The most common mistake is recording a URL as seen only when it is dequeued. A page linked from fifty places would then be pushed fifty times, inflating the queue and risking repeat fetches. Adding it to seen at the moment it enters the frontier guarantees each URL is queued, and therefore fetched, once.
Why BFS
BFS and DFS are equally correct here. BFS is the usual pick because it explores pages nearest the seed first, which makes a later depth limit or page cap natural, and it avoids Python's recursion limit that a recursive DFS would hit on long link chains. Switching to DFS only requires popping from the right end of the container instead of the left.
URL canonicalization
The goal is to map every spelling of one page onto one string.
- Resolve relative links with
urljoin(current_page, href). This covers/about,../x,?page=2and//host/path. - Lowercase scheme and host, which are case-insensitive. Leave the path alone, since paths are case-sensitive.
- Remove the fragment (
#section); it never changes the document the server returns. - Drop default ports (
:80for http,:443for https). - Use
/for an empty path, sohttps://a.comequalshttps://a.com/. - Skip other schemes such as
mailto:,javascript:,tel:andftp:.
Some normalizations are risky and worth raising rather than applying silently:
- Stripping trailing slashes from non-root paths (
/docsand/docs/can differ). - Sorting query parameters or removing tracking parameters like
utm_*. - Treating http and https as the same page.
- Treating
www.and the bare domain as one host.
The requirement says the hostname must match, so the code uses an exact comparison. Asking about www is a good clarifying question.
Code
get_links is passed in so the function can be tested against a fake link graph.
from collections import deque
from urllib.parse import urljoin, urlsplit, urlunsplit
DEFAULT_PORTS = {"http": 80, "https": 443}
def normalize(url, base=None):
"""Canonical absolute http(s) URL, or None if it should be skipped."""
try:
if base is not None:
url = urljoin(base, url.strip())
parts = urlsplit(url.strip())
scheme = parts.scheme.lower()
if scheme not in DEFAULT_PORTS:
return None
host = parts.hostname # lowercased by urllib
if not host:
return None
port = parts.port # ValueError on a bad port
except ValueError:
return None
netloc = f"[{host}]" if ":" in host else host # IPv6 literal
if port is not None and port != DEFAULT_PORTS[scheme]:
netloc = f"{netloc}:{port}"
path = parts.path or "/"
return urlunsplit((scheme, netloc, path, parts.query, ""))
def crawl(start_url, get_links):
start = normalize(start_url)
if start is None:
return []
target_host = urlsplit(start).hostname
seen = {start}
order = [start]
queue = deque([start])
while queue:
url = queue.popleft()
try:
links = get_links(url) or []
except Exception:
continue # one bad page must not stop the crawl
for href in links:
if not isinstance(href, str):
continue
nxt = normalize(href, base=url)
if nxt is None or nxt in seen:
continue
if urlsplit(nxt).hostname != target_host:
continue
seen.add(nxt) # mark on enqueue
order.append(nxt)
queue.append(nxt)
return order
Correctness
- Completeness: by induction on path length. The seed is enqueued; any enqueued page is eventually dequeued, and each of its same-host neighbors is either enqueued then or was enqueued before.
- No repeats, guaranteed termination: a URL enters the queue only if it is absent from
seen, and is added toseenat the same moment. Each canonical URL is fetched at most once, so cycles cannot loop forever, provided the reachable set is finite. - Host restriction: the hostname check happens before enqueueing, so off-site pages are never fetched.
Complexity
Let V be the reachable same-host pages, E the total links returned, and L the maximum URL length.
- Time: O(V + E·L). Each page is fetched once, and each link is resolved, normalized and hashed once. In practice the V network calls dominate.
- Space: O(V·L) for the seen set, result list and queue.
Edge cases
- A seed with no links, or one whose fetch fails, yields just the seed.
- Self-links and cycles are absorbed by
seen. HTTP://Example.com:80/#topandhttp://example.com/collapse to one entry.- Protocol-relative links such as
//cdn.other.com/xresolve properly and are then rejected by the host check. - Malformed URLs or invalid ports are skipped rather than raising.
- If
get_linksraises or returnsNone, treat it as no links. - Sites that generate endless URLs (calendars, session IDs) call for a
max_pagesor depth cap in production.
Common mistakes
- Marking visited at dequeue time.
- Comparing raw strings without resolving relative links or stripping fragments.
- Lowercasing the whole URL, which corrupts case-sensitive paths.
- Using substring or
endswithchecks on the host, which wrongly acceptsevil-example.com. - Recursing in DFS and hitting the recursion limit.
Likely follow-ups
- Parallelize fetching with a thread pool or asyncio, protecting
seenwith a lock or using a single coordinator. - Add politeness: per-host rate limits, robots.txt, retries with backoff.
- Include subdomains by comparing registered domains.
- Scale to many machines by sharding URLs by host hash and using a distributed visited set or Bloom filter.