Subdomain Visit Count
Problem
Given a list of count-paired domains, return the count of visits to each subdomain.
- 1 ≤ cpdomains.length ≤ 100
- Each cpdomain follows the format "count domain"
- The count is a positive integer not exceeding 10⁴
- The domain consists of lowercase English letters, digits, and dots
Example
cpdomains = ["9001 discuss.leetcode.com"]["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]The input means there were 9001 visits to 'discuss.leetcode.com'. A visit to this domain also counts as a visit to each parent domain: 'discuss.leetcode.com', 'leetcode.com', and 'com'. The algorithm splits the domain into parts and builds every suffix subdomain, adding 9001 visits to each one.
Approach
Straightforward Solution
A naive approach might attempt to parse each domain and count visits for each possible subdomain separately without aggregation, leading to redundant computations and inefficient lookups.
Core Observation
Each visit count applies not only to the full domain but also to all its parent subdomains. This means the problem reduces to aggregating counts for all suffixes of the domain split by dots.
Path to Optimal
The key insight is to use a hash map to accumulate counts for each subdomain. By splitting each domain into parts and iterating over all suffixes, the algorithm aggregates counts in a single pass. This transforms the problem into a frequency counting task over all subdomains, enabling efficient O(N * M) time complexity, where N is the number of domains and M is the average number of subdomain parts.
Optimal Approach
Iterate over each count-paired domain, split it into count and domain, then split the domain by dots. For each suffix subdomain, update its count in a hash map. Finally, construct the result list by concatenating counts and subdomains from the hash map. This approach guarantees a single pass over the input and efficient aggregation.
Time
O(N * M)
Each of the N count-paired domains is processed once. Splitting each domain into M parts and iterating over all suffixes results in O(M) operations per domain, leading to O(N * M) total time.
Space
O(N * M)
In the worst case, each domain has M subdomains, and all are unique, requiring O(N * M) space in the hash map to store counts.
Pattern Spotlight
Hash Maps (Frequency Counting with String Manipulation)
When counting occurrences of hierarchical or nested keys (like subdomains), break the keys into components and aggregate counts for all suffixes or prefixes using a hash map to achieve efficient frequency accumulation.
Solution
| 1 | class Solution: |
| 2 | def subdomainVisits(self, cpdomains: list[str]) -> list[str]: |
| 3 | visit_counts = {} |
| 4 | |
| 5 | for entry in cpdomains: |
| 6 | count_string, domain = entry.split() |
| 7 | visit_count = int(count_string) |
| 8 | |
| 9 | parts = domain.split(".") |
| 10 | |
| 11 | for index in range(len(parts)): |
| 12 | subdomain = ".".join(parts[index:]) |
| 13 | visit_counts[subdomain] = visit_counts.get(subdomain, 0) + visit_count |
| 14 | |
| 15 | result = [] |
| 16 | |
| 17 | for domain, count in visit_counts.items(): |
| 18 | result.append(str(count) + " " + domain) |
| 19 | |
| 20 | return result |
Step-by-Step Solution
Aggregate Visit Counts for Each Subdomain
| 3 | visit_counts = {} |
| 5 | for entry in cpdomains: |
| 6 | count_string, domain = entry.split() |
| 7 | visit_count = int(count_string) |
| 9 | parts = domain.split(".") |
| 11 | for index in range(len(parts)): |
| 12 | subdomain = ".".join(parts[index:]) |
| 13 | visit_counts[subdomain] = visit_counts.get(subdomain, 0) + visit_count |
Objective
To parse each count-paired domain and accumulate visit counts for all subdomains in a hash map.
Key Insight
Splitting the domain by dots produces all subdomain components. Iterating over these components from left to right and joining suffixes allows the algorithm to capture every subdomain from the most specific to the top-level domain. Using a hash map to accumulate counts ensures efficient aggregation without redundant computations.
Interview Quick-Check
Core Logic
Split each domain into parts and iterate over all suffixes to accumulate counts in a hash map, capturing visits to all subdomains.
State & Boundaries
Ensure the count is converted to an integer and added to existing counts or initialized if the subdomain is new.
Common Pitfalls & Bugs
Forgetting to convert the count string to an integer or incorrectly joining subdomain parts can lead to wrong counts or malformed keys.
Construct the Result List from Aggregated Counts
| 15 | result = [] |
| 17 | for domain, count in visit_counts.items(): |
| 18 | result.append(str(count) + " " + domain) |
| 20 | return result |
Objective
To transform the aggregated counts in the hash map into the required output format.
Key Insight
Iterating over the hash map entries and concatenating the count and subdomain as a string produces the final output. This step translates the internal frequency representation into the problem's expected output format.
Interview Quick-Check
Core Logic
Convert each hash map entry into a string of the form 'count subdomain' and collect them into a list.
State & Boundaries
Ensure all entries in the hash map are included in the output, regardless of order.
Line Analysis
This solution has 1 Critical line interviewers watch for.
visit_counts[subdomain] = visit_counts.get(subdomain, 0) + visit_count
Update the visit count for the current subdomain in the hash map.
Incrementing the count in the hash map accumulates visits from all relevant domains, ensuring accurate total counts.
visit_counts = {}
Initialize a hash map to store visit counts for each subdomain.
This data structure enables efficient aggregation of counts for all subdomains by providing O(1) average-time insertions and lookups.
parts = domain.split(".")
Split the domain into its subdomain parts by the dot character.
Breaking the domain into parts allows the algorithm to generate all suffix subdomains for counting.
for index in range(len(parts)):
Iterate over each possible suffix index in the domain parts.
This loop generates every subdomain from the most specific to the top-level domain, ensuring complete coverage for counting.
subdomain = ".".join(parts[index:])
Join the suffix parts to form the current subdomain string.
Joining parts from the current index to the end reconstructs the subdomain for which the visit count is aggregated.
count_string, domain = entry.split()
Split the entry into count string and domain string.
Separating the count from the domain is essential to parse the input correctly and process counts numerically.
visit_count = int(count_string)
Convert the count string to an integer.
Numeric conversion is necessary to perform arithmetic aggregation of visit counts.
result.append(str(count) + " " + domain)
Append the formatted string 'count subdomain' to the result list.
Formatting the output as specified by the problem is necessary for correct submission and interpretation.
return result
Return the list of formatted visit count strings.
Returning the result completes the function, providing the aggregated visit counts in the required format.
for domain, count in visit_counts.items():
Iterate over each subdomain and its aggregated count in the hash map.
Enumerating all entries ensures the output includes every subdomain with its total visit count.
for entry in cpdomains:
Iterate over each count-paired domain in the input list.
Processing each input entry sequentially ensures all visit counts are accounted for in the aggregation.
result = []
Initialize a list to store the final result strings.
This list will hold the formatted output strings representing visit counts per subdomain.
Test Your Understanding
Why is it necessary to aggregate counts for all suffix subdomains rather than just the full domain?
Because each visit to a domain also counts as a visit to all its parent subdomains, so to accurately count visits, the algorithm must accumulate counts for every suffix subdomain derived from the full domain.
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct Subdomain Visit Count from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Subdomain Visit Count drill