Subdomain Visit Count
Subdomain Visit Count is a medium arrays & hashing problem solved with the hashing pattern.
The best approach, optimal (hash map, cut after each dot), runs in O(n · L) time and O(n · L) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from hash map (split into labels and rebuild) up.
Problem
Web traffic is often logged per full domain name, such as mail.shop.io. A domain is made of labels joined by dots. The rightmost label (io) is the top-level domain, shop.io is one level below it, and mail.shop.io is below that. A visit to a domain also counts as a visit to every parent domain above it: one visit to mail.shop.io is also one visit to shop.io and one visit to io.
You get an array cpdomains of count-paired domains. Each string has the form "rep domain": a visit count, one space, then the full domain, for example "50 mail.shop.io".
Return the total visit count of every domain and parent domain that appears, as strings in the same "rep domain" form. You may return them in any order.
Examples
Example 1
- Input
cpdomains = ["50 mail.shop.io"]- Output
["50 mail.shop.io","50 shop.io","50 io"]- Why
- A visit to mail.shop.io is also a visit to its parent shop.io and to the top-level domain io, so each of the three gets 50.
Example 2
- Input
cpdomains = ["20 news.site.org","5 blog.site.org","7 site.net"]- Output
["20 news.site.org","5 blog.site.org","25 site.org","25 org","7 site.net","7 net"]- Why
- news.site.org and blog.site.org both roll up into site.org and org, so those get 20 + 5 = 25. site.net and net get 7. Any order of the six strings is accepted.
Example 3
- Input
cpdomains = ["3 a.b","4 a.b"]- Output
["7 a.b","7 b"]- Why
- The same domain can appear more than once; its counts add up.
Constraints
1 <= cpdomains.length <= 1001 <= cpdomains[i].length <= 100- Each
cpdomains[i]is"rep d1.d2.d3"or"rep d1.d2": a count, one space, then a domain of two or three labels 1 <= rep <= 10^4- Each label
d1,d2,d3is made of lowercase English letters - The answer may be returned in any order
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Hash map (split into labels and rebuild) | O(n · L) | O(n · L) |
| Optimal (hash map, cut after each dot) | O(n · L) | O(n · L) |
1Hash map (split into labels and rebuild)
O(n · L)Each of the n entries has at most three labels, and joining a suffix costs O(L), where L is the length of an entry, so each entry costs O(L).O(n · L)The map holds at most three domains per entry, each up to L characters long.Split each entry into its count and its domain. Split the domain into labels at the dots. The domain and its parents are the label lists starting at label 0, label 1, and so on, joined back together with dots. Add the count to each of them in a hash map from domain to total, then turn the map into "count domain" strings.
- counts = an empty map from domain to total visits.
- For each entry: split at the space into visits and domain, then split domain at the dots into labels.
- For each i from 0 to labels.length - 1: join labels[i..] with dots and add visits to counts of that string.
- Build the result: for each domain in the map, the string total + " " + domain.
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> counts = new HashMap<>();
for (String entry : cpdomains) {
String[] parts = entry.split(" ");
int visits = Integer.parseInt(parts[0]);
String[] labels = parts[1].split("\\.");
for (int i = 0; i < labels.length; i++) {
String domain = String.join(".", Arrays.copyOfRange(labels, i, labels.length));
counts.merge(domain, visits, Integer::sum);
}
}
List<String> result = new ArrayList<>();
for (Map.Entry<String, Integer> e : counts.entrySet())
result.add(e.getValue() + " " + e.getKey());
return result;
}
}class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
counts = {}
for entry in cpdomains:
rep, full = entry.split(" ")
visits = int(rep)
labels = full.split(".")
for i in range(len(labels)):
domain = ".".join(labels[i:])
counts[domain] = counts.get(domain, 0) + visits
return [f"{total} {domain}" for domain, total in counts.items()]class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
unordered_map<string, int> counts;
for (const string& entry : cpdomains) {
int space = entry.find(' ');
int visits = stoi(entry.substr(0, space));
vector<string> labels;
string label;
for (char c : entry.substr(space + 1)) {
if (c == '.') { labels.push_back(label); label = ""; }
else label += c;
}
labels.push_back(label);
for (int i = 0; i < (int)labels.size(); i++) {
string domain = labels[i];
for (int j = i + 1; j < (int)labels.size(); j++) domain += "." + labels[j];
counts[domain] += visits;
}
}
vector<string> result;
for (auto& [domain, total] : counts)
result.push_back(to_string(total) + " " + domain);
return result;
}
};function subdomainVisits(cpdomains) {
const counts = new Map();
for (const entry of cpdomains) {
const [rep, full] = entry.split(" ");
const visits = parseInt(rep, 10);
const labels = full.split(".");
for (let i = 0; i < labels.length; i++) {
const domain = labels.slice(i).join(".");
counts.set(domain, (counts.get(domain) || 0) + visits);
}
}
const result = [];
for (const [domain, total] of counts) result.push(total + " " + domain);
return result;
}2Optimal (hash map, cut after each dot)
O(n · L)Each entry is scanned once, and it has at most two dots, so it makes at most three substrings of length at most L.O(n · L)Up to three keys per entry, each at most L characters, plus the result strings.There is no need to split and rebuild. The parents of a domain are exactly the substrings that begin right after each dot. So add the visits to the whole domain, then scan it once and, at every dot, add the visits to the substring after that dot. The same hash map collects the totals.
- counts = an empty map from domain to total visits.
- For each entry: find the space. visits = the number before it, domain = the text after it.
- Add visits to counts of domain.
- For each index i where domain has a dot, add visits to counts of domain.substring(i + 1).
- Turn every map entry into the string total + " " + domain.
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> counts = new HashMap<>();
for (String entry : cpdomains) {
int space = entry.indexOf(' ');
int visits = Integer.parseInt(entry.substring(0, space));
String domain = entry.substring(space + 1);
counts.merge(domain, visits, Integer::sum);
for (int i = 0; i < domain.length(); i++) {
if (domain.charAt(i) == '.')
counts.merge(domain.substring(i + 1), visits, Integer::sum);
}
}
List<String> result = new ArrayList<>();
for (Map.Entry<String, Integer> e : counts.entrySet())
result.add(e.getValue() + " " + e.getKey());
return result;
}
}class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
counts = {}
for entry in cpdomains:
space = entry.index(" ")
visits = int(entry[:space])
domain = entry[space + 1:]
counts[domain] = counts.get(domain, 0) + visits
for i, ch in enumerate(domain):
if ch == ".":
parent = domain[i + 1:]
counts[parent] = counts.get(parent, 0) + visits
return [f"{total} {domain}" for domain, total in counts.items()]class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
unordered_map<string, int> counts;
for (const string& entry : cpdomains) {
int space = entry.find(' ');
int visits = stoi(entry.substr(0, space));
string domain = entry.substr(space + 1);
counts[domain] += visits;
for (int i = 0; i < (int)domain.size(); i++) {
if (domain[i] == '.')
counts[domain.substr(i + 1)] += visits;
}
}
vector<string> result;
for (auto& [domain, total] : counts)
result.push_back(to_string(total) + " " + domain);
return result;
}
};function subdomainVisits(cpdomains) {
const counts = new Map();
for (const entry of cpdomains) {
const space = entry.indexOf(" ");
const visits = parseInt(entry.substring(0, space), 10);
const domain = entry.substring(space + 1);
counts.set(domain, (counts.get(domain) || 0) + visits);
for (let i = 0; i < domain.length; i++) {
if (domain[i] === ".") {
const parent = domain.substring(i + 1);
counts.set(parent, (counts.get(parent) || 0) + visits);
}
}
}
const result = [];
for (const [domain, total] of counts) result.push(total + " " + domain);
return result;
}Edge cases to test
- A single entry: the answer has two or three strings
- The same full domain listed twice: its counts are added
- Different subdomains sharing a parent: the parent gets the sum
- A two-label entry that is also the parent of a three-label entry ("5 shop.io" and "3 mail.shop.io")
- Labels that look alike but are different domains, such as "a.bc" and "ab.c": compare whole strings, not letters
- The total for a top-level domain can reach 100 · 10^4 = 10^6, which still fits in an int
Hints
Hint 1
A visit to x.y.z counts for x.y.z, for y.z and for z. Those are the suffixes of the domain that start right after a dot, plus the whole domain.
Hint 2
You need a running total per domain string. Which data structure maps a string to a number?
Hint 3
You do not need to split the domain into labels and glue them back together. Every parent domain is just the substring after one of the dots.
FAQ
What is the best time complexity for Subdomain Visit Count?
Optimal (hash map, cut after each dot) runs in O(n · L) time and O(n · L) extra space. Each entry is scanned once, and it has at most two dots, so it makes at most three substrings of length at most L.
Which pattern does Subdomain Visit Count use?
It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.
Is there a brute force solution for Subdomain Visit Count?
Yes. Hash map (split into labels and rebuild) takes O(n · L) time and O(n · L) space. Split each entry into its count and its domain.
Which edge cases should I test for Subdomain Visit Count?
A single entry: the answer has two or three strings; The same full domain listed twice: its counts are added; Different subdomains sharing a parent: the parent gets the sum; A two-label entry that is also the parent of a three-label entry ("5 shop.io" and "3 mail.shop.io"); Labels that look alike but are different domains, such as "a.bc" and "ab.c": compare whole strings, not letters; The total for a top-level domain can reach 100 · 10^4 = 10^6, which still fits in an int.