Pages and links form a graph, not a tree, so this is a graph traversal with a visited set. Start from the URL, keep a Set of URLs already seen, and for every page take its links, add the unseen ones to the set and to the queue. The set handles circular links and pages reached by several paths, so each page is fetched once: O(V + E) work for V pages and E links. await getAllLinks(url) covers both a plain return and a promise. A sequential loop is correct but slow, since each request waits for the one before it. Pages of the same depth are independent, so fetch a level with Promise.all, or better, run a pool with a concurrency limit so a large site doesn't get hundreds of requests at once. Add each URL to the set when you discover it, not when its fetch returns, or parallel requests fetch the same page twice.
Given an API getAllLinks(url) that returns all the links on a page, write a function that returns all descendant links (child URLs of child URLs, etc.). Handle edge cases: circular dependencies, getAllLinks returning a promise, async efficiency, and time complexity.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
One array serves as the queue and the result: an index walks along it while new links are appended. A link is added only if it isn't in seen, so a cycle (a → b → a) ends and a page linked from several places is fetched once. The start page is in seen from the beginning, so a link back to it isn't reported as a descendant. Time is O(V + E): one fetch per page and one set lookup per link. The last check shows the cost of awaiting inside the loop: 7 pages at 10 ms each take 70 ms.
// Breadth-first search. `seen` stops cycles and repeat fetches; `order` is both the queue and// the result. `await` works whether getAllLinks returns an array or a promise of one.async function getDescendantLinks(start, getAllLinks) {const seen = new Set([start]);const order = [start];for (let i = 0; i < order.length; i++) {for (const link of await getAllLinks(order[i])) {if (!seen.has(link)) {seen.add(link);order.push(link);}}}return order.slice(1); // every page reachable from start, without start itself}
passes 6 checks run on every build, against the native method where there is one
- finds children of children, each once
- a cycle ends, and the start page isn't its own descendant
- the same link twice on a page, and on two pages
- a page with no links
- works when getAllLinks returns a promise
- the weakness: one request at a time, 7 pages take 70 ms
All pages of the current level are requested together with Promise.all, and their links form the next level. seen is updated synchronously between levels, so a page linked from two pages of the same level is still fetched once. The crawl now takes one round trip per level of depth: 40 ms for the same site. Two gaps remain, shown by the last checks: a level with 50 pages starts 50 requests at once, and one failed page rejects the whole crawl.
// Fetch a whole level at once. Pages of the same depth don't depend on each other, so their// requests run in parallel; `seen` is updated between levels, so nothing is fetched twice.async function getDescendantLinks(start, getAllLinks) {const seen = new Set([start]);const found = [];let level = [start];while (level.length) {const pages = await Promise.all(level.map((url) => getAllLinks(url)));level = [];for (const links of pages) {for (const link of links) {if (!seen.has(link)) {seen.add(link);level.push(link);}}}found.push(...level);}return found;}
passes 9 checks run on every build, against the native method where there is one
- finds children of children, each once
- a cycle ends, and the start page isn't its own descendant
- the same link twice on a page, and on two pages
- a page with no links
- works when getAllLinks returns a promise
- a level is fetched in parallel: 4 levels take 40 ms
- two pages of one level linking to the same child: fetched once
- the weakness: a wide level starts every request at once
- the weakness: one failed page fails the whole crawl
A pool keeps at most concurrency requests in flight and queues a page's links the moment it arrives, so a slow page doesn't hold up the fast branches beside it. URLs are normalised with new URL(link, pageUrl): relative links resolve against the page they were found on, and the #fragment is dropped because it points inside the same page. A page that fails is passed to onError and skipped; its URL stays in the result because it was found, only its own links are unknown. The crawl finishes when nothing is in flight and nothing is queued.
// A pool: at most `concurrency` requests in flight, and a page's links are queued the moment// it arrives, without waiting for the rest of its level. URLs are normalised, and a page that// fails is reported and skipped instead of failing the whole crawl.function getDescendantLinks(start, getAllLinks, { concurrency = 5, onError } = {}) {// Resolve against the page the link was found on, and drop the #fragment: same page.const clean = (link, base) => {const url = new URL(link, base);url.hash = '';return url.href;};return new Promise((resolve) => {const first = clean(start);const seen = new Set([first]);const order = [first]; // queue and result in onelet next = 0;let active = 0;const done = () => {active--;if (active === 0 && next === order.length) resolve(order.slice(1));else pump();};const pump = () => {while (active < concurrency && next < order.length) {const url = order[next++];active++;Promise.resolve().then(() => getAllLinks(url)).then((links) => {for (const link of links) {let href;try {href = clean(link, url);} catch {continue; // not a URL: skip it}if (!seen.has(href)) {seen.add(href);order.push(href);}}done();},(error) => {done();if (onError) onError(error, url);},);}};pump();});}
passes 9 checks run on every build, against the native method where there is one
- finds children of children, each once
- a cycle ends, and the start page isn't its own descendant
- never more than `concurrency` requests in flight
- a fast branch isn't held up by a slow page of the same level
- relative links resolve against their page, and #fragments are the same page
- a link that isn't a URL is skipped
- a failed page is reported and skipped; the rest is still crawled
- getAllLinks may throw synchronously or return a plain array
- an invalid start URL rejects
Crawlers and link checkers
A site map builder, a broken-link checker and a search crawler are all this traversal: fetch a page, collect its links, skip the ones already seen.
Resolving relative links
new URL(link, base) resolves ../about or /docs against the page's own URL, which is what a browser does with an href. Comparing raw href strings misses duplicates.
Dependency graphs
The same traversal walks module imports in a bundler or a package's dependencies: follow each edge, keep a visited set, and cycles are harmless.
No visited set: two pages that link to each other loop forever.
Marking a URL as seen only after its fetch returns, so parallel requests fetch the same page several times.
Awaiting inside the loop when the interviewer asked for async efficiency.
Promise.allover everything with no limit, on a site with thousands of pages.One failed request rejecting the whole crawl.
Treating
/a,/a#topand a relativeaas three different pages.Recursion without a visited set, or deep recursion on a long chain of pages.
What's the time and space complexity?
O(V + E) time: each of the V pages is fetched once and each of the E links costs one set lookup. O(V) space for the set and the queue. In wall-clock time, sequential is the sum of all requests, level-parallel is one round trip per level, and a pool is about V / concurrency round trips.
Breadth-first or depth-first?
Both visit every page once. Breadth-first finds pages in order of distance from the start and parallelises naturally by level. Depth-first with recursion is shorter to write but can go very deep on a long chain.
How would you limit the crawl?
Add a maximum depth or page count, and only follow links whose origin matches the start URL, otherwise one external link takes the crawl out onto the whole web.
How do you avoid overloading the site?
A concurrency limit, a delay between requests to the same host, and respecting the site's robots.txt. Retry failed pages with backoff instead of at once.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
- developer.mozilla.org/en-US/docs/Web/API/URL/URL
- developer.mozilla.org/en-US/docs/Web/API/URL/hash
- en.wikipedia.org/wiki/Breadth-first_search