Subdomain Visit Count (LeetCode 811): Solution and Explanation
Each entry says a domain was visited some number of times. Count the visits for every domain and all of its parent domains.
Intuition
A visit to discuss.leetcode.com is also a visit to leetcode.com and to com. Those parents are exactly the suffixes of the domain that start right after a dot.
So each entry hands its count to at most three keys: the full domain, and the domain with one or two labels peeled off the left.
A hash map from domain string to total visits collects everything. Shared parents such as com simply keep growing as more entries credit them.
Approach: Hash map over domain suffixes
- Create an empty map counts.
- For each entry, split it into rep and domain.
- Set sub = domain. Repeatedly add rep to counts[sub], then cut sub after its first dot. Stop when sub has no dot left.
- Return one string "count domain" per map entry.
Step-by-step example
cpdomains = ["9001 discuss.leetcode.com"]
- Split the entry: rep = 9001, domain = discuss.leetcode.com.
- counts["discuss.leetcode.com"] = 9001. Peel off discuss.
- counts["leetcode.com"] = 9001. Peel off leetcode.
- counts["com"] = 9001. No dot is left, so this entry is done.
- Return ["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"].
Code: Python, Java, C++
1class Solution:
2 def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
3 counts = {}
4 for entry in cpdomains:
5 rep, domain = entry.split()
6 rep = int(rep)
7 sub = domain
8 while True:
9 counts[sub] = counts.get(sub, 0) + rep
10 dot = sub.find('.')
11 if dot < 0:
12 break
13 sub = sub[dot + 1:]
14 return [f"{c} {d}" for d, c in counts.items()]1class Solution {
2 public List<String> subdomainVisits(String[] cpdomains) {
3 Map<String, Integer> counts = new LinkedHashMap<>();
4 for (String entry : cpdomains) {
5 int space = entry.indexOf(' ');
6 int rep = Integer.parseInt(entry.substring(0, space));
7 String sub = entry.substring(space + 1);
8 while (true) {
9 counts.merge(sub, rep, Integer::sum);
10 int dot = sub.indexOf('.');
11 if (dot < 0) break;
12 sub = sub.substring(dot + 1);
13 }
14 }
15 List<String> result = new ArrayList<>();
16 for (Map.Entry<String, Integer> e : counts.entrySet()) result.add(e.getValue() + " " + e.getKey());
17 return result;
18 }
19}1class Solution {
2public:
3 vector<string> subdomainVisits(vector<string>& cpdomains) {
4 unordered_map<string, int> counts;
5 vector<string> order;
6 for (const string& entry : cpdomains) {
7 size_t space = entry.find(' ');
8 int rep = stoi(entry.substr(0, space));
9 string sub = entry.substr(space + 1);
10 while (true) {
11 if (!counts.count(sub)) order.push_back(sub);
12 counts[sub] += rep;
13 size_t dot = sub.find('.');
14 if (dot == string::npos) break;
15 sub = sub.substr(dot + 1);
16 }
17 }
18 vector<string> result;
19 for (const string& d : order) result.push_back(to_string(counts[d]) + " " + d);
20 return result;
21 }
22};Time and space complexity
O(n * L)
Each of the n entries has at most three suffixes, and building or hashing each suffix costs up to L characters.
O(n * L)
The map holds up to 3n distinct suffix strings.
Other approaches
Split on dots and join (time O(n * L), space O(n * L))
Split the domain into labels and join labels[i:] for each i. Same result, but each join rebuilds the string from pieces.
Reversed-label trie (time O(n * L), space O(n * L))
Insert the labels right to left into a trie (com, then leetcode, then discuss) and add rep at every node on the path. Each node is one subdomain. It mirrors the domain hierarchy but needs a traversal to rebuild the strings.
Common mistakes
- Crediting only the full domain and forgetting the parent domains.
- Splitting on every character position instead of only after dots, which creates fake domains like "eetcode.com".
- Formatting the output as "domain count" instead of "count domain".
Frequently asked questions
Does the output order matter?
No. Any order is accepted, so iterating the map in whatever order it gives is fine.
Why not count only top-level domains separately?
Every level is asked for. A domain with two dots produces three answers: itself, its parent and the top-level domain.
Can the same domain appear in several entries?
Yes. The map adds the counts together, which is exactly what the answer needs.