#811
Subdomain Visit Count
MediumArrayHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a hash map to efficiently count visits for each subdomain while iterating through the input only once. This reduces the time complexity significantly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a hash map to store the visit counts for each subdomain.
- 2Step 2: For each count-paired domain, split it into count and domain.
- 3Step 3: Generate subdomains and update their counts in the hash map.
- 4Step 4: Convert the hash map into the required output format.
solution.py13 lines
1# Full working Python code
2from collections import defaultdict
3
4def subdomainVisits(cpdomains):
5 count_map = defaultdict(int)
6 for cp in cpdomains:
7 count, domain = cp.split()
8 count = int(count)
9 parts = domain.split('.');
10 for i in range(len(parts)):
11 subdomain = '.'.join(parts[i:])
12 count_map[subdomain] += count
13 return [f'{count} {subdomain}' for subdomain, count in count_map.items()]ℹ
Complexity note: This complexity is due to the single pass through the input and the efficient counting using a hash map.
- 1Understanding how subdomains are structured helps in generating them efficiently.
- 2Using a hash map allows for quick updates and retrievals of counts.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.