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 (standard urllib.parse.urljoin semantics).
  • Exact hostname scope: Keep a resolved URL if and only if its parsed hostname equals the parsed hostname of start_url (ignoring http vs https scheme differences, while rejecting subdomains, external domains, and non-HTTP links such as mailto:). 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_url is a valid http:// or https:// URL with a non-empty hostname.
  • 0 <= len(links) <= 5 * 10^3, and total outgoing links across reachable same-host pages is at most 5 * 10^4.
  • URL strings have length at most 200.

Step-by-step walkthrough

  1. Understand the goal and URL rules

    Starting at start_url, we want to discover every reachable page sharing the same hostname as start_url, visiting pages wave by wave using breadth-first search (BFS). In our function, outgoing page hyperlinks are represented by links, a dictionary mapping each page URL to its list of raw outgoing link strings.

    Four key details govern how links behave:

    1. 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).
    2. Links can be relative paths: on https://shop.dev/catalog/shoes.html, "../about.html" resolves to https://shop.dev/about.html, and "/cart" resolves to https://shop.dev/cart (Example 2).
    3. Only the hostname must match, not http vs https: starting at https://portal.net/login, http://portal.net/status has the same hostname (portal.net) and is crawled (Example 3).
    4. Missing dictionary keys mean zero outgoing links: a valid same-host URL absent from links is still visited and returned, contributing [] outgoing links.
  2. 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, then Wave 1, then Wave 2) using a FIFO queue (first-in, first-out waiting line): we always pop the oldest waiting URL from the front with deque.popleft(), inspect its links, and push newly discovered URLs onto the back with deque.append().

  3. 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 standard urllib.parse handles all of them cleanly:

    1. urljoin(current_url, raw_link) resolves raw_link relative to the page it was found on (current_url, not start_url!).
    2. urlparse(next_url).hostname extracts just the lowercase hostname (dropping http:// vs https://, ports, and paths, and returning None for mailto:).
    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.net
    

    Notice why string shortcuts like "portal.net" in next_url or next_url.startswith(...) are buggy: "portal.net" in "https://sub.portal.net/admin" is True, and "http://portal.net/status".startswith("https://portal.net") is False!

    next_url = urljoin(current_url, raw_link)
    if urlparse(next_url).hostname != target_host:
        continue
    
  4. Avoid revisiting pages by marking at enqueue time

    Websites are full of navigation menus where every page links back to /home and /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 visited set — 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 we queue.append(next_url) guarantees every reachable URL enters queue — and visit_order — at most once.

  5. Write the BFS crawler

    We wrap links.get(url, []) in a tiny fetch_links helper and use collections.deque so popleft() runs in O(1) time (unlike list.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_order
    
  6. Trace Example 2 step by step

    start_url = "https://shop.dev/catalog/index.html" (target_host = "shop.dev"). Shortening https://shop.dev to S:

    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'].

  7. 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"):

  1. Start with target_host = "portal.net", visited = {"https://portal.net/login"}, and queue = ["https://portal.net/login"].
  2. Pop https://portal.net/login and record it: http://portal.net/status has hostname portal.net even over http (mark & enqueue); https://sub.portal.net/admin has hostname sub.portal.net (skip); mailto:help@portal.net has hostname None (skip).
  3. Pop http://portal.net/status: https://portal.net/login is already in visited (skip); https://portal.net/ping matches portal.net and is new (mark & enqueue).
  4. 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 V reachable 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 the E outgoing links we run urljoin, urlparse, and a hash-set lookup in visited, each scanning at most U characters.
  • Space: O(V * U), or O(V) URLs. visited, queue, and visit_order each hold at most the V reachable same-host URLs because off-host links are discarded immediately without being stored.

Edge cases

  • Start page absent from links: fetch_links returns [] via links.get(url, []), so crawl cleanly returns [start_url].
  • Self-links, duplicate links on one page, and cycles (A -> B -> A): visited contains start_url initially 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 against start_url.
  • http vs https on the same hostname: urlparse(url).hostname compares 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, and mailto:help@portal.net (hostname is None) 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 in visit_order, contributing zero outgoing links (Example 2).

Common mistakes

  • Skipping urljoin for relative links: urlparse("/cart").hostname is None, causing every relative link in Example 2 to be dropped.
  • Calling urljoin(start_url, raw_link) instead of urljoin(current_url, raw_link): resolves subdirectory links relative to the start page's folder instead of the current page's folder.
  • Comparing urlparse(url).netloc instead of .hostname: netloc retains uppercase characters, :port suffixes, and user@ credentials, whereas .hostname normalizes the host to lowercase and strips ports.
  • Using substring or startswith checks for host filtering: "portal.net" in url accepts "https://sub.portal.net/admin" and startswith("https://portal.net") rejects "http://portal.net/status".
  • Marking visited on pop instead of on enqueue: lets a popular page get pushed onto queue dozens of times before it is first popped, wasting memory and causing duplicate visits unless re-checked on pop.
  • Using a list for visited or queue.pop(0): url in visited_list and list.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 build next_level = [] across each wave instead of a single deque. It visits URLs in the exact same BFS order while making it effortless to track hop depth (for example, stopping at max_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 visited of 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 #fragment anchors, lowercase the scheme and host, drop default ports (:80 for HTTP, :443 for HTTPS), and sort query parameters. At web scale (billions of URLs), store visited in 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 V same-host pages and E inspected links of length up to U. 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 by V network 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 asyncio tasks or a ThreadPoolExecutor) pulling URLs from a shared queue so dozens of slow network requests overlap in flight. Protect the if 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 an in_flight counter of active fetches: workers should exit only when both the queue is empty and in_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.txt directives, 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 transient 5xx errors, max_pages and max_depth limits against infinite URL traps, and Content-Type checks so binary files are skipped before HTML parsing.

Follow-up questions

Similar questions

More Nooks interview questions

All 2 Nooks questions →