Gallery Subdomain Traffic - codepath/compsci_guides GitHub Wiki

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

def subdomain_visits(cpdomains):
    # Step 1: Use a regular dictionary to count visits
    visit_count = {}
    
    for cpdomain in cpdomains:
        # Step 2: Split the count and the domain
        count, domain = cpdomain.split()
        count = int(count)
        fragments = domain.split('.')
        
        # Step 3: Create subdomains and count visits
        for i in range(len(fragments)):
            subdomain = '.'.join(fragments[i:])
            if subdomain in visit_count:
                visit_count[subdomain] += count
            else:
                visit_count[subdomain] = count
    
    # Step 4: Prepare the result list
    result = []
    for domain, count in visit_count.items():
        result.append(f"{count} {domain}")
    
    return result