KatInterview

Same-Host Link Crawler: Sequential and Concurrent Versions

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbfsgraph-traversalconcurrency

Last updated

Crawl every page reachable from a seed URL on the same host, ignoring URL fragments, first with one thread and then with a thread-safe parallel design.

Crawl a Site from a Seed Page

You are given a seed address startUrl (for example "http://news.example.com/a/index.html") and an object HtmlParser exposing one method, getUrls(url). That method fetches the page at url and returns every absolute URL linked from it. Treat it as a black box that may be slow, like a network call.

Starting from startUrl, follow links and collect every distinct page you can reach, obeying these rules.

Rules

  1. Stay on one host. Only visit pages whose hostname equals the hostname of startUrl. The hostname is the text after the scheme (http:// or https://) up to the next /.
  2. Drop fragments. A URL may end with a fragment such as #section2. Remove the # and everything after it before you check whether a page was seen, and before you put it in the result. So http://a.com/x#p1 and http://a.com/x#p2 are the same page, http://a.com/x.
  3. Nothing else is normalized. Do not touch trailing slashes, default ports, letter case, query-parameter order, and so on. Only the fragment is removed.

Part A: Single thread

Write a crawler that runs on one thread and returns all visited URLs (fragments removed) that satisfy the host rule.

Part B: Multiple threads

Now speed it up with several threads.

  • Many threads may call getUrls at the same time.
  • The solution must be thread-safe and must never fetch the same cleaned URL twice.

Output

All distinct cleaned URLs reachable from startUrl on the same host (order does not matter).

Notes

  • The link graph can contain cycles and self-links.
  • Every URL returned by getUrls is absolute.

Explain your approach, state the complexity, and give code for both parts. Be ready to discuss how you would terminate the concurrent version and what could go wrong.

Hints

Hint 1

Model pages as graph nodes and links as directed edges. Cycles mean you need a visited set, and a queue (BFS) or stack (DFS) for the frontier.

Hint 2

Clean the URL first: cut at the first '#'. Only then extract the hostname (otherwise a URL like 'http://a.com#top' gives a wrong host), check membership in visited, and store it.

Hint 3

Add a URL to visited at the moment you schedule it, not when you later pop it. That is what guarantees one fetch per cleaned URL.

Hint 4

For threads, getUrls is the slow part. Let workers only fetch and return links, while a single coordinator thread owns visited and decides what to submit next. That removes the need for locks and makes termination simply 'no pending fetches'.