Leetcode 811. Subdomain Visit Count
A website domain “discuss.leetcode.com” consists of various subdomains. At the top level, we have “com”, at the next level, we have “leetcode.com”, and at the lowest level, “discuss.leetcode.com”. Given a list of count-paired domains, we need to count the number of visits to each subdomain.
For example, a count-paired domain “9001 discuss.leetcode.com” might represent that discuss.leetcode.com
received 9001
visits. We should split this into:
Function Signature:
vector<string> subdomainVisits(vector<string>& cpdomains);
Here is the C++ implementation:
#include <vector>
#include <string>
#include <sstream>
#include <unordered_map>
using namespace std;
vector<string> subdomainVisits(vector<string>& cpdomains) {
unordered_map<string, int> domainCount;
for (const string& cpdomain : cpdomains) {
// Split into count and domain
stringstream ss(cpdomain);
string countStr, domain;
ss >> countStr >> domain;
int count = stoi(countStr);
// Process the domain and its subdomains
vector<string> subdomains;
size_t pos = 0;
while ((pos = domain.find('.')) != string::npos) {
subdomains.push_back(domain);
domain = domain.substr(pos + 1);
}
// Push the last part
subdomains.push_back(domain);
// Update counts in the unordered_map
for (const string& subdomain : subdomains) {
domainCount[subdomain] += count;
}
}
// Construct the result from the domainCount map
vector<string> result;
for (const auto& entry : domainCount) {
result.push_back(to_string(entry.second) + " " + entry.first);
}
return result;
}
stringstream
to split the input string into count and domain.The time complexity is (O(N \cdot M)) where:
Each domain string is processed independently, and within each string, handling the subdomain splits and hashmap updates are efficient operations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?