A website domain “visit count” is represented as a string cpdomain
, consisting of a count followed by a space, followed by the address. Given a list of such count-paired domains, return the count of total visits for each subdomain.
For example, a count-paired domain “9001 discuss.leetcode.com” indicates that the domain discuss.leetcode.com
was visited 9001 times. A subdomain will count visits for every domain it is a part of.
discuss.leetcode.com
counts visits to discuss.leetcode.com
, leetcode.com
, and com
.Input:
["9001 discuss.leetcode.com"]
Output:
["9001 leetcode.com", "9001 discuss.leetcode.com", "9001 com"]
def subdomainVisits(cpdomains):
from collections import defaultdict
# Dictionary to store counts of each subdomain
subdomain_count = defaultdict(int)
for full_domain in cpdomains:
count, domain = full_domain.split()
count = int(count)
subdomains = domain.split('.')
# Form and count all subdomains
for i in range(len(subdomains)):
subdomain = '.'.join(subdomains[i:])
subdomain_count[subdomain] += count
# Build the output list
result = [f"{value} {key}" for key, value in subdomain_count.items()]
return result
# Example usage
input_list = ["9001 discuss.leetcode.com"]
print(subdomainVisits(input_list))
Thus, the overall time complexity is O(N + D*L) which is generally linear with respect to the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?