Subdomain Visit Count - Problem

A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.

A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.

For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.

Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.

Input & Output

Example 1 — Basic Three-Level Domain
$ Input: cpdomains = ["9001 discuss.leetcode.com"]
Output: ["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
💡 Note: Visiting "discuss.leetcode.com" contributes 9001 visits to itself and all parent domains: "leetcode.com" and "com"
Example 2 — Multiple Domains with Overlap
$ Input: cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output: ["901 mail.com", "50 yahoo.com", "900 google.mail.com", "5 wiki.org", "5 org", "1 intel.mail.com", "951 com"]
💡 Note: Multiple domains contribute to shared parent domains: "mail.com" gets 900+1=901 visits, "com" gets 900+50+1=951 visits
Example 3 — Two-Level Domain Only
$ Input: cpdomains = ["100 facebook.com"]
Output: ["100 facebook.com", "100 com"]
💡 Note: Two-level domain generates only itself and top-level domain "com"

Constraints

  • 1 ≤ cplists.length ≤ 100
  • 1 ≤ cplists[i].length ≤ 100
  • cplists[i] follows either the format "rep d1.d2.d3" or "rep d1.d2"
  • rep is an integer in the range [1, 104]
  • d1, d2, d3 consist of lowercase English letters

Visualization

Tap to expand
Subdomain Visit Count: Domain Hierarchy Tracking["900 google.mail.com"]Input: Count-Paired Domainsgoogle.mail.com ← 900 visitsmail.com ← 900 visitscom ← 900 visitsDomain Hierarchy Expansion"900 google.mail.com""900 mail.com""900 com"Output: Visit Count ResultsEach domain visit counts toward all parent levelsgoogle.mail.com → mail.com → com
Understanding the Visualization
1
Input
Count-paired domains with visit numbers
2
Extract Subdomains
Each domain generates multiple subdomains
3
Output
Accumulated visit counts for all subdomains
Key Takeaway
🎯 Key Insight: Domain visits cascade up the hierarchy - use hash map to efficiently accumulate counts for all subdomains
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
89.2K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen