Subdomain Visit Count

The problem requires counting the visits for each subdomain in the given count-paired domains. We can solve this by parsing each domain and then breaking it into its subdomains, keeping track of the counts in a dictionary.

Here’s how we can solve this:

  1. Initialize a Dictionary: We’ll create a dictionary to store the count for each subdomain.

  2. Parse Each Count-Paired Domain: We’ll iterate through each count-paired domain, split it into the count and the domain, and then further split the domain into its subdomains.

  3. Update the Counts: For each subdomain, we’ll update the count in the dictionary.

  4. Format the Output: Finally, we’ll format the result into the required string format and return it.

Below is the code for this approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
        # Dictionary to store the counts of subdomains
        counts = {}

        # Iterate through each count-paired domain
        for cpdomain in cpdomains:
            count, domain = cpdomain.split()
            count = int(count)

            # Split the domain into subdomains and update the counts
            parts = domain.split(".")
            for i in range(len(parts)):
                subdomain = ".".join(parts[i:])
                counts[subdomain] = counts.get(subdomain, 0) + count

        # Format the output as a list of strings
        return [f"{count} {subdomain}" for subdomain, count in counts.items()]

Example:

  • 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"]
  • Explanation: The counts for each subdomain are computed by splitting and accumulating the counts for each level.

Insights:

  • Time Complexity: The code runs in (O(n \cdot m)) time, where (n) is the number of count-paired domains, and (m) is the maximum length of a domain.
  • Space Complexity: The space complexity is also (O(n \cdot m)) as we store the counts for each subdomain.
  • Usage of Dictionary: Utilizing a dictionary simplifies the code by efficiently keeping track of counts and handling unique subdomains.
  • String Manipulation: The key part of the problem involves parsing the input and manipulating strings to extract subdomains.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# @param {String[]} cpdomains
# @return {String[]}
def subdomain_visits(cpdomains)
  result = {}

  for cpdomain in cpdomains
    visits, domains = cpdomain.split(' ')
    domains = domains.split('.')
    i = 0
    j = domains.length

    while i < j do
      domain = domains[i..j].join('.')
      result[domain] = result[domain].to_i + visits.to_i
      i = i + 1
    end
  end

  result.keys.map do |key|
    "#{result[key]} #{key}"
  end
end