Skip to content

Gallery Subdomain Traffic

LeWiz24 edited this page Aug 13, 2024 · 2 revisions

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
      • To calculate the number of visits to each subdomain from a list of count-paired domains.
    • What input is provided?
      • An array of count-paired domains cpdomains.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Parse the count-paired domains to extract and accumulate the visit counts for each subdomain.

1) Initialize a dictionary `visit_count` to store the accumulated visit counts.
2) Iterate through each `cpdomain` to parse the count and domain.
3) For each domain, break it into subdomains and update the visit counts.
4) Convert the dictionary to a list of strings in the required format and return it.

⚠️ Common Mistakes

  • Incorrectly parsing the domain to extract subdomains.

I-mplement

from collections import defaultdict

def subdomain_visits(cpdomains):
    visit_count = defaultdict(int)
    
    for cpdomain in cpdomains:
        count, domain = cpdomain.split()
        count = int(count)
        fragments = domain.split('.')
        
        for i in range(len(fragments)):
            subdomain = '.'.join(fragments[i:])
            visit_count[subdomain] += count
    
    result = []
    for domain, count in visit_count.items():
        result.append(f"{count} {domain}")
    
    return result
Clone this wiki locally