A web address like docs.site.org is made of labels joined by dots. A visit to it also counts as a visit to every shorter address you get by dropping labels from the left: site.org and org.
You get a list cpdomains. Each item is a count, a space, and a domain, such as "40 docs.site.org", meaning that domain was visited 40 times. Return the total visits for every domain and parent domain that appears, as strings in the same "count domain" shape. The order does not matter.
Example 1
Input: cpdomains = ["340 shop.acme.io"] Output: ["340 shop.acme.io", "340 acme.io", "340 io"] Why: one visit counts for the domain and both of its parents
2 more examples and the constraints
Example 2
Input: cpdomains = ["60 news.site.org", "25 site.org",
"7 blog.site.org", "12 mail.net"]
Output: ["60 news.site.org", "92 site.org", "92 org",
"7 blog.site.org", "12 mail.net", "12 net"]
Why: site.org collects 60 + 25 + 7 = 92 visitsExample 3
Input: cpdomains = ["9 go.dev", "4 go.dev"] Output: ["13 go.dev", "13 dev"] Why: the same domain can appear twice; its counts add up
Constraints
- 1 ≤ length of cpdomains ≤ 100
- Each item is at most 100 characters
- Each domain has two or three lower-case labels
- Each count is between 1 and 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Two lists, linear searchO(m²)
- Hash map of suffix totalsO(m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 300 suffixes | Verdict |
|---|---|---|---|
| Two lists, linear search | O(m²) | Passes here; scales badly | |
| Hash map of suffix totals | O(m) | Best; one update per suffix |
m = total number of suffixes, at most three per entry.
Edge cases to test
- Same domain twice. ["9 go.dev", "4 go.dev"] adds up to 13 for both go.dev and dev.
- A parent listed on its own. ["2 b.c", "3 a.b.c"] gives 5 for b.c, not two separate lines.
- Two labels only. "1 x.y" has just two suffixes: x.y and y.
- Large counts. Three entries of 10,000 under one top level reach 30,000; still fits an int.
Common mistakes
- Forgetting the top-level label itself, such as org, which is also a domain.
- Writing a second line for a domain that already exists instead of adding to it.
- Parsing the count into the domain name by splitting on dots before the space.
How to talk through it
- 1Clarify. Does a domain count as its own parent? Can the same domain appear twice? Does the output order matter?
- 2Give the simple version. List every suffix and search a list for it; say the search makes it quadratic.
- 3Name the tool. Totals per key are a hash map: one O(1) update per suffix.
- 4Code the suffix loop. Cut at the first dot until none is left, adding the count each time.
- 5Test out loud. Run a repeated domain and a parent that appears on its own.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?