#1236
Medium Algorithms Web crawler
String Depth-First Search Breadth-First Search Interactive
68.8% acceptance
Mar 31, 2026
308
337
Given a url startUrl and an interface HtmlParser, implement a web crawler to crawl all links that are under the same hostname as startUrl.
Return all urls obtained by your web crawler in any order.
Your crawler should:
Start from the page: startUrl
Call HtmlParser.getUrls(url) to get all urls from a webpage of given url.
Do not crawl the same link twice.
Explore only the links that are under the same hostname as startUrl.
As shown in the example url above, the hostname is example.org. For simplicity sake, you may assume all urls use http protocol without any port specified. For example, the urls http://leetcode.com/problems and http://leetcode.com/contest are under the same hostname, while urls http://example.org/test and http://example.com/abc are not under the same hostname.
The HtmlParser interface is defined as such:
interface HtmlParser {
// Return a list of all urls from a webpage of given url.
public List getUrls(String url);
}
Below are two examples explaining the functionality of the problem, for custom testing purposes you'll have three variables urls, edges and startUrl. Notice that you will only have access to startUrl in your code, while urls and edges are not directly accessible to you in code.
Note: Consider the same URL with the trailing slash "/" as a different URL. For example, "http://news.yahoo.com", and "http://news.yahoo.com/" are different urls.
Solution
C++
Time O(n²)
Space O(1)
/**
* // This is the HtmlParser's API interface.
* // You should not implement it, or speculate about its implementation
* class HtmlParser {
* public:
* vector<string> getUrls(string url);
* };
*/
class Solution {
public:
string getHostname(const string& url) {
int start = url.find("//") + 2;
int end = url.find('/', start);
return end == string::npos ? url.substr(start) : url.substr(start, end - start);
}
vector<string> crawl(string startUrl, HtmlParser htmlParser) {
string hostname = getHostname(startUrl);
unordered_set<string> visited;
vector<string> result;
queue<string> q;
q.push(startUrl);
visited.insert(startUrl);
while (!q.empty()) {
string url = q.front(); q.pop();
result.push_back(url);
for (const string& next : htmlParser.getUrls(url)) {
if (!visited.count(next) && getHostname(next) == hostname) {
visited.insert(next);
q.push(next);
}
}
}
return result;
}
};