829. Subdomain Visit Count
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to process a list of "count-paired domains". Each entry provides a visit count and a domain name. A key rule is that a visit to a specific domain, such as discuss.leetcode.com, also implies a visit to all its parent domains—in this case, leetcode.com and com. Our task is to calculate the total visit count for every unique subdomain across all given entries and return the results as a list of strings, each formatted as "total_count subdomain".
Solution
Subdomain Visit Count in Python
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
# Use a dictionary to store the counts of each subdomain.
# Key: subdomain string, Value: visit count.
counts = {}
# Iterate through each count-paired domain string.
for cpdomain in cpdomains:
# Parse count and domain by splitting at the space.
count_str, domain = cpdomain.split(' ')
count = int(count_str)
# Process the domain and all its parent subdomains.
while True:
# Add the count to the current domain (or subdomain).
# .get() with a default value handles new keys gracefully.
counts[domain] = counts.get(domain, 0) + count
# Find the next dot.
dot_index = domain.find('.')
# If no dot is found, we've processed all subdomains.
if dot_index == -1:
break
# Move to the parent domain by taking the substring after the dot.
domain = domain[dot_index + 1:]
# Prepare the result list using a list comprehension for conciseness.
# f-strings are used for easy string formatting.
return [f"{count} {domain}" for domain, count in counts.items()]
Subdomain Visit Count in Java
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
// Use a HashMap to store the counts of each subdomain.
// Key: subdomain string, Value: visit count.
Map<String, Integer> counts = new HashMap<>();
// Iterate through each count-paired domain string.
for (String cpdomain : cpdomains) {
// Find the position of the space to separate count and domain.
int spaceIndex = cpdomain.indexOf(' ');
// Parse the count.
int count = Integer.parseInt(cpdomain.substring(0, spaceIndex));
// Get the domain string.
String domain = cpdomain.substring(spaceIndex + 1);
// Process the domain and all its parent subdomains.
while (true) {
// Add the count to the current domain (or subdomain).
// getOrDefault handles the case where the key is not yet in the map.
counts.put(domain, counts.getOrDefault(domain, 0) + count);
// Find the next dot.
int dotIndex = domain.indexOf('.');
// If no dot is found, we've processed all subdomains.
if (dotIndex == -1) {
break;
}
// Move to the parent domain by taking the substring after the dot.
domain = domain.substring(dotIndex + 1);
}
}
// Prepare the result list.
List<String> result = new ArrayList<>();
// Iterate through the map to format the output strings.
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
result.add(entry.getValue() + " " + entry.getKey());
}
return result;
}
}
Subdomain Visit Count in C++
class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
// Use an unordered_map to store the counts of each subdomain.
// Key: subdomain string, Value: visit count.
unordered_map<string, int> counts;
// Iterate through each count-paired domain string.
for (const string& cpdomain : cpdomains) {
// Find the position of the space to separate the count and the domain.
size_t space_pos = cpdomain.find(' ');
// Parse the count. stoi converts string to integer.
int count = stoi(cpdomain.substr(0, space_pos));
// Extract the domain string.
string domain = cpdomain.substr(space_pos + 1);
// Process the domain and all its parent subdomains.
while (true) {
// Add the count to the current domain (or subdomain).
counts[domain] += count;
// Find the next dot.
size_t dot_pos = domain.find('.');
// If no dot is found, we have reached the top-level domain.
if (dot_pos == string::npos) {
break;
}
// Move to the parent domain by taking the substring after the dot.
domain = domain.substr(dot_pos + 1);
}
}
// Prepare the result vector.
vector<string> result;
// Iterate through the map to format the output strings.
for (auto const& [domain, count] : counts) {
result.push_back(to_string(count) + " " + domain);
}
return result;
}
};
Subdomain Visit Count in TypeScript
function subdomainVisits(cpdomains: string[]): string[] {
// Use a Map to store the counts of each subdomain.
// Key: subdomain string, Value: visit count.
const counts: Map<string, number> = new Map();
// Iterate through each count-paired domain string.
for (const cpdomain of cpdomains) {
// Find the position of the space to separate count and domain.
const spaceIndex = cpdomain.indexOf(' ');
// Parse the count.
const count = parseInt(cpdomain.substring(0, spaceIndex));
// Extract the domain string.
let domain = cpdomain.substring(spaceIndex + 1);
// Process the domain and all its parent subdomains.
while (true) {
// Add the count to the current domain (or subdomain).
// Use || 0 to handle cases where the key is not yet in the map.
const currentCount = counts.get(domain) || 0;
counts.set(domain, currentCount + count);
// Find the next dot.
const dotIndex = domain.indexOf('.');
// If no dot is found, we have reached the top-level domain.
if (dotIndex === -1) {
break;
}
// Move to the parent domain by taking the substring after the dot.
domain = domain.substring(dotIndex + 1);
}
}
// Prepare the result array.
const result: string[] = [];
// Iterate through the map to format the output strings.
counts.forEach((count, domain) => {
result.push(`${count} ${domain}`);
});
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.