Same-Host Web Crawler Using Breadth-First Search
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given an initial page start_url and an adjacency mapping links, write a crawler that discovers every web page reachable from start_url on the same hostname, traversing pages wave by wave with breadth-first search (BFS).
Here links[page_url] lists the raw outgoing hyperlink strings found on page_url (any URL absent from links has zero outgoing hyperlinks). Return all reachable same-hostname URLs in exact BFS visitation order, starting with start_url.
Your crawler must enforce these rules:
- Relative URL resolution: Raw hyperlinks may be full URLs (
"https://...","http://..."), protocol-relative ("//host/..."), root-relative ("/cart"), or path-relative ("shoes.html","../about.html"). Resolve each link relative to the page URL on which it was found (standardurllib.parse.urljoinsemantics). - Exact hostname scope: Keep a resolved URL if and only if its parsed hostname equals the parsed hostname of
start_url(ignoringhttpvshttpsscheme differences, while rejecting subdomains, external domains, and non-HTTP links such asmailto:). Never fetch outgoing links from off-host URLs. - Single visit per URL: Pages may contain duplicate links, self-links, and navigation cycles; enqueue and output each resolved URL string at most once, preserving discovery order.
def crawl(start_url: str, links: Dict[str, List[str]]) -> List[str]:
Examples
Example 1
Input:
start_url = "https://docs.io/home"
links = {
"https://docs.io/home": [
"https://docs.io/api",
"https://blog.org/news",
"https://docs.io/guide",
"https://docs.io/api"
],
"https://docs.io/api": ["https://docs.io/ref", "https://docs.io/home"],
"https://docs.io/guide": ["https://docs.io/faq"],
"https://docs.io/ref": [],
"https://docs.io/faq": []
}
Output: [
"https://docs.io/home",
"https://docs.io/api",
"https://docs.io/guide",
"https://docs.io/ref",
"https://docs.io/faq"
]
Explanation: From /home, /api and /guide are one hop away (blog.org is skipped as an external host, and the repeated /api link is ignored). BFS visits /api and /guide before visiting their children /ref and /faq.
Example 2
Input:
start_url = "https://shop.dev/catalog/index.html"
links = {
"https://shop.dev/catalog/index.html": [
"shoes.html",
"/cart",
"https://cdn.dev/img.png",
"shoes.html"
],
"https://shop.dev/catalog/shoes.html": ["../about.html", "/cart"],
"https://shop.dev/cart": []
}
Output: [
"https://shop.dev/catalog/index.html",
"https://shop.dev/catalog/shoes.html",
"https://shop.dev/cart",
"https://shop.dev/about.html"
]
Explanation: On /catalog/index.html, "shoes.html" resolves to https://shop.dev/catalog/shoes.html and "/cart" resolves to https://shop.dev/cart. On /catalog/shoes.html, "../about.html" climbs one directory to https://shop.dev/about.html, which has no key in links and therefore contributes zero outgoing links.
Example 3
Input:
start_url = "https://portal.net/login"
links = {
"https://portal.net/login": [
"http://portal.net/status",
"https://sub.portal.net/admin",
"mailto:help@portal.net"
],
"http://portal.net/status": ["https://portal.net/login", "https://portal.net/ping"],
"https://portal.net/ping": []
}
Output: [
"https://portal.net/login",
"http://portal.net/status",
"https://portal.net/ping"
]
Explanation: http://portal.net/status shares the hostname portal.net despite switching from https to http, so it is visited and leads to /ping. Both sub.portal.net and mailto: have different hostnames and are ignored.
Constraints
start_urlis a validhttp://orhttps://URL with a non-empty hostname.0 <= len(links) <= 5 * 10^3, and total outgoing links across reachable same-host pages is at most5 * 10^4.- URL strings have length at most
200.
Step-by-step walkthrough
Understand the goal and URL rules
Starting at
start_url, we want to discover every reachable page sharing the same hostname asstart_url, visiting pages wave by wave using breadth-first search (BFS). In our function, outgoing page hyperlinks are represented bylinks, a dictionary mapping each page URL to its list of raw outgoing link strings.Four key details govern how links behave:
- Return pages in BFS visitation order beginning with
start_url(start_url, then pages 1 hop away, then 2 hops away, in link appearance order). - Links can be relative paths: on
https://shop.dev/catalog/shoes.html,"../about.html"resolves tohttps://shop.dev/about.html, and"/cart"resolves tohttps://shop.dev/cart(Example 2). - Only the hostname must match, not
httpvshttps: starting athttps://portal.net/login,http://portal.net/statushas the same hostname (portal.net) and is crawled (Example 3). - Missing dictionary keys mean zero outgoing links: a valid same-host URL absent from
linksis still visited and returned, contributing[]outgoing links.
- Return pages in BFS visitation order beginning with
Model web pages as a directed graph
Treat each URL as a node and each hyperlink on that page as a one-way arrow pointing to another URL:
Wave 0: [https://docs.io/home] / | \ Wave 1: [/api] [/guide] [https://blog.org/news] <-- external host (skip!) | | Wave 2: [/ref] [/faq]Breadth-first search explores this graph in concentric waves (
Wave 0, thenWave 1, thenWave 2) using a FIFO queue (first-in, first-out waiting line): we always pop the oldest waiting URL from the front withdeque.popleft(), inspect its links, and push newly discovered URLs onto the back withdeque.append().Resolve relative links and extract the hostname safely
Raw HTML links come in many shapes — full URLs, root-relative paths (
/cart), directory-relative paths (shoes.html,../about.html), or non-HTTP links (mailto:help@portal.net). Python's standardurllib.parsehandles all of them cleanly:urljoin(current_url, raw_link)resolvesraw_linkrelative to the page it was found on (current_url, notstart_url!).urlparse(next_url).hostnameextracts just the lowercase hostname (droppinghttp://vshttps://, ports, and paths, and returningNoneformailto:).
current_url raw_link urljoin result .hostname ---------------------------------- ------------------------- --------------------------------- ------------- https://shop.dev/catalog/index.html shoes.html https://shop.dev/catalog/shoes.html shop.dev https://shop.dev/catalog/index.html /cart https://shop.dev/cart shop.dev https://shop.dev/catalog/shoes.html ../about.html https://shop.dev/about.html shop.dev https://portal.net/login http://portal.net/status http://portal.net/status portal.net https://portal.net/login https://sub.portal.net/admin https://sub.portal.net/admin sub.portal.netNotice why string shortcuts like
"portal.net" in next_urlornext_url.startswith(...)are buggy:"portal.net" in "https://sub.portal.net/admin"isTrue, and"http://portal.net/status".startswith("https://portal.net")isFalse!next_url = urljoin(current_url, raw_link) if urlparse(next_url).hostname != target_host: continueAvoid revisiting pages by marking at enqueue time
Websites are full of navigation menus where every page links back to
/homeand/cart, plus pages that repeat the same link twice. Without tracking seen URLs, the crawler loops forever.When should a URL be added to the
visitedset — when we pop it from the queue, or when we push (enqueue) it?Suppose /index.html and /shoes.html both link to /cart: Mark on POP (bad): pop /index.html -> push /shoes.html, /cart pop /shoes.html -> /cart not popped yet -> push /cart AGAIN! (duplicate in queue) Mark on ENQUEUE (good): start with visited = {start_url}, queue = [start_url] pop /index.html -> see /cart -> add /cart to visited AND push /cart pop /shoes.html -> see /cart -> /cart already in visited -> skip immediately!Marking
visited.add(next_url)at the exact moment wequeue.append(next_url)guarantees every reachable URL entersqueue— andvisit_order— at most once.Write the BFS crawler
We wrap
links.get(url, [])in a tinyfetch_linkshelper and usecollections.dequesopopleft()runs in O(1) time (unlikelist.pop(0), which shifts every remaining element in O(n) time).def fetch_links(url: str, links: Dict[str, List[str]]) -> List[str]: """Return outgoing hyperlinks on `url`; pages absent from `links` have none.""" return links.get(url, []) def crawl(start_url: str, links: Dict[str, List[str]]) -> List[str]: # Extract only the hostname (e.g. "a.com"), ignoring http vs https scheme. target_host = urlparse(start_url).hostname # visited: set of full URL strings already scheduled, e.g. {"https://a.com/x"}. visited: Set[str] = {start_url} # queue: FIFO deque of URLs waiting to be crawled level by level. queue = deque([start_url]) # visit_order: crawled URLs in exact breadth-first visitation order. visit_order: List[str] = [] while queue: current_url = queue.popleft() visit_order.append(current_url) for raw_link in fetch_links(current_url, links): # Resolve relative links ("/about", "team.html", "../index.html") against current_url. next_url = urljoin(current_url, raw_link) # Skip external domains, subdomains, or non-web links (like mailto: -> hostname None). if urlparse(next_url).hostname != target_host: continue if next_url in visited: continue # Mark visited BEFORE enqueuing so duplicate links never enter the queue twice. visited.add(next_url) queue.append(next_url) return visit_orderTrace Example 2 step by step
start_url = "https://shop.dev/catalog/index.html"(target_host = "shop.dev"). Shorteninghttps://shop.devtoS:Popped page Raw link Resolved URL Action Queue after step -------------------- ----------------------- ---------------------- ------------------ --------------------------------- S/catalog/index.html shoes.html S/catalog/shoes.html new -> mark & push [S/catalog/shoes.html] /cart S/cart new -> mark & push [S/catalog/shoes.html, S/cart] https://cdn.dev/img.png cdn.dev/img.png wrong host -> skip [S/catalog/shoes.html, S/cart] shoes.html S/catalog/shoes.html in visited -> skip [S/catalog/shoes.html, S/cart] S/catalog/shoes.html ../about.html S/about.html new -> mark & push [S/cart, S/about.html] /cart S/cart in visited -> skip [S/cart, S/about.html] S/cart (no links) - - [S/about.html] S/about.html (absent -> []) - - []Final
visit_order:['https://shop.dev/catalog/index.html', 'https://shop.dev/catalog/shoes.html', 'https://shop.dev/cart', 'https://shop.dev/about.html'].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque from urllib.parse import urljoin, urlparse def fetch_links(url: str, links: Dict[str, List[str]]) -> List[str]: """Return outgoing hyperlinks on `url`; pages absent from `links` have none.""" return links.get(url, []) def crawl(start_url: str, links: Dict[str, List[str]]) -> List[str]: # Extract only the hostname (e.g. "a.com"), ignoring http vs https scheme. target_host = urlparse(start_url).hostname # visited: set of full URL strings already scheduled, e.g. {"https://a.com/x"}. visited: Set[str] = {start_url} # queue: FIFO deque of URLs waiting to be crawled level by level. queue = deque([start_url]) # visit_order: crawled URLs in exact breadth-first visitation order. visit_order: List[str] = [] while queue: current_url = queue.popleft() visit_order.append(current_url) for raw_link in fetch_links(current_url, links): # Resolve relative links ("/about", "team.html", "../index.html") against current_url. next_url = urljoin(current_url, raw_link) # Skip external domains, subdomains, or non-web links (like mailto: -> hostname None). if urlparse(next_url).hostname != target_host: continue if next_url in visited: continue # Mark visited BEFORE enqueuing so duplicate links never enter the queue twice. visited.add(next_url) queue.append(next_url) return visit_order✅ Submit now — all tests should pass.
Intuition & how it works
Imagine exploring every room inside one office building starting from the main lobby, where each room has doors leading both to other rooms in your building and to neighboring buildings across the street. To explore outward in waves by distance from the lobby — a strategy called breadth-first search (BFS) (visiting all nodes 1 step away before any node 2 steps away, and so on) — you carry a clipboard with two lists: a FIFO queue (a first-in, first-out waiting line where the earliest room added is inspected next) and a visited checklist of rooms already scheduled. Every time you open a room, you resolve where each door leads, ignore doors into other buildings, and for any same-building room not yet on your checklist, immediately check it off and add it to the back of the waiting line.
A naive traversal without a visited set gets trapped in an infinite loop as soon as two pages link to each other (home -> api -> home). Likewise, naive string checks on URLs break down on real links: relative paths like "/cart" or "../about.html" have no domain written in them until resolved against the current page, scheme differences (http vs https, the protocol part before ://) still belong to the same hostname (the domain name like portal.net), and substring checks like "portal.net" in url get fooled by subdomains or look-alike domains such as https://sub.portal.net/admin.
Walk through Example 3 (start_url = "https://portal.net/login"):
- Start with
target_host = "portal.net",visited = {"https://portal.net/login"}, andqueue = ["https://portal.net/login"]. - Pop
https://portal.net/loginand record it:http://portal.net/statushas hostnameportal.neteven overhttp(mark & enqueue);https://sub.portal.net/adminhas hostnamesub.portal.net(skip);mailto:help@portal.nethas hostnameNone(skip). - Pop
http://portal.net/status:https://portal.net/loginis already invisited(skip);https://portal.net/pingmatchesportal.netand is new (mark & enqueue). - Pop
https://portal.net/ping: no outgoing links remain, queue is empty, returning["https://portal.net/login", "http://portal.net/status", "https://portal.net/ping"].
Complexity
Let V be the number of reachable same-host pages visited, E be the total number of outgoing links across those V pages, and U be the maximum character length of a URL.
- Time: O((V + E) * U), or O(V + E) treating URL string length as bounded. We pop and inspect each of the
Vreachable same-host pages once from a deque (a double-ended queue supporting O(1) pops from the front and appends at the back), and for each of theEoutgoing links we runurljoin,urlparse, and a hash-set lookup invisited, each scanning at mostUcharacters. - Space: O(V * U), or O(V) URLs.
visited,queue, andvisit_ordereach hold at most theVreachable same-host URLs because off-host links are discarded immediately without being stored.
Edge cases
- Start page absent from
links:fetch_linksreturns[]vialinks.get(url, []), socrawlcleanly returns[start_url]. - Self-links, duplicate links on one page, and cycles (
A -> B -> A):visitedcontainsstart_urlinitially and records every link upon enqueue, preventing any duplicate visits. - Relative links inside subdirectories:
urljoin("https://shop.dev/catalog/shoes.html", "../about.html")resolves against the current page's directory to"https://shop.dev/about.html", not againststart_url. httpvshttpson the same hostname:urlparse(url).hostnamecompares only"portal.net", so cross-scheme links on the same host are included (Example 3).- Subdomains, look-alike domains, and
mailto:links:sub.portal.net,portal.net.evil.org, andmailto:help@portal.net(hostnameisNone) all differ from"portal.net"and are ignored. - Same-host page reachable only through an external host: never reached because external pages are never enqueued or inspected.
- Linked same-host page missing from
links: still visited and returned invisit_order, contributing zero outgoing links (Example 2).
Common mistakes
- Skipping
urljoinfor relative links:urlparse("/cart").hostnameisNone, causing every relative link in Example 2 to be dropped. - Calling
urljoin(start_url, raw_link)instead ofurljoin(current_url, raw_link): resolves subdirectory links relative to the start page's folder instead of the current page's folder. - Comparing
urlparse(url).netlocinstead of.hostname:netlocretains uppercase characters,:portsuffixes, anduser@credentials, whereas.hostnamenormalizes the host to lowercase and strips ports. - Using substring or
startswithchecks for host filtering:"portal.net" in urlaccepts"https://sub.portal.net/admin"andstartswith("https://portal.net")rejects"http://portal.net/status". - Marking
visitedon pop instead of on enqueue: lets a popular page get pushed ontoqueuedozens of times before it is first popped, wasting memory and causing duplicate visits unless re-checked on pop. - Using a
listforvisitedorqueue.pop(0):url in visited_listandlist.pop(0)each cost O(V) time instead of O(1), degrading the crawl to O(V^2 + V * E).
Alternative approaches
- Level-by-level list swap: maintain
current_level = [start_url]and buildnext_level = []across each wave instead of a singledeque. It visits URLs in the exact same BFS order while making it effortless to track hop depth (for example, stopping atmax_depth = 3). - Depth-first search (DFS) with an explicit stack: pops from the back (
stack.pop()) instead of the front. While DFS finds the exact same set of reachable same-host pages, it violates the requirement to use breadth-first traversal and fails the sample order checks.
Follow-up questions
- How do you prevent duplicate page fetches when distinct URL strings point to the same resource? Keep a hash set
visitedof seen URLs and insert each URL before enqueuing so every membership check runs in O(1) average time. In production, normalize URLs first so equivalent addresses match: strip#fragmentanchors, lowercase the scheme and host, drop default ports (:80for HTTP,:443for HTTPS), and sort query parameters. At web scale (billions of URLs), storevisitedin a distributed key-value store or use a Bloom filter (a compact bit-array sketch that never misses a seen URL and only rarely skips a new URL due to a false positive). - What are the in-memory time and space bounds, and what becomes the bottleneck over a real network? In memory, the graph traversal takes O((V + E) * U) time and O(V * U) space for
Vsame-host pages andEinspected links of length up toU. Over a live network, CPU work on the queue and hash set takes microseconds while each HTTP fetch takes tens to hundreds of milliseconds of network latency. Total wall-clock time is therefore dominated byVnetwork round-trips unless multiple pages are fetched concurrently. - How would you parallelize link fetching with worker threads or async tasks without race conditions? Run a fixed pool of workers (such as
asynciotasks or aThreadPoolExecutor) pulling URLs from a shared queue so dozens of slow network requests overlap in flight. Protect theif next_url not in visited: visited.add(next_url)check-and-insert with a lock (or keep deduplication on a single event-loop thread) so two workers never enqueue the same URL twice. Also maintain anin_flightcounter of active fetches: workers should exit only when both the queue is empty andin_flight == 0, since an active fetch can still enqueue new URLs. - What production guardrails are essential before crawling live external servers? Fetch and respect the target domain's
robots.txtdirectives, and enforce politeness throttling (such as a minimum delay or concurrency cap per host) to avoid overloading origin servers. Add per-request timeouts, bounded retries with exponential backoff (doubling wait time after each failed attempt) on transient5xxerrors,max_pagesandmax_depthlimits against infinite URL traps, andContent-Typechecks so binary files are skipped before HTML parsing.
Follow-up questions
- How do you prevent duplicate page fetches when distinct URL strings point to the same resource?
- What are the in-memory time and space bounds, and what becomes the bottleneck over a real network?
- How would you parallelize link fetching with worker threads or async tasks without race conditions?
- What production guardrails are essential before crawling live external servers?
Similar questions
- Throttling and Scheduling a Distributed Web Crawler
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One