Python 0811.py
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
def subs(s):
parts = s.split(".")
for i in range(len(parts)):
yield ".".join(parts[i:])
all = defaultdict(int)
for c in cpdomains:
visits, domain = c.split(" ")
for s in subs(domain):
all[s] += int(visits)
for a in all:
yield str(all[a]) + " " + a
Difficulty
and has an acceptance rate of about 76% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of aggregating visit counts for subdomains given a list of strings where each string contains a visit count and a fully qualified domain name. The algorithm parses each entry, decomposes the domain into all possible subdomains, accumulates the counts in a hash map, and finally yields the aggregated results in the required format.
Key Steps
The first logical component is a helper generator that produces every subdomain from a given domain string. The generator splits the domain on the dot character and then yields the suffixes one by one.
def subs(s):
parts = s.split(".")
for i in range(len(parts)):
yield ".".join(parts[i:])
The main routine creates a defaultdict of integers to hold the cumulative counts. It iterates over each input entry, separates the numeric count from the domain, and then iterates over the subdomains produced by the helper. For each subdomain the integer count is added to the map.
all = defaultdict(int)
for c in cpdomains:
visits, domain = c.split(" ")
for s in subs(domain):
all[s] += int(visits)
After all entries have been processed, the function iterates over the keys of the dictionary and yields strings that combine the total count with the corresponding subdomain.
for a in all:
yield str(all[a]) + " " + a
Edge Cases Handled
The code gracefully handles domains that consist of a single label (e.g., "com"). In such a case the subs generator yields the domain itself because the loop runs once with i = 0. The split operation on the input string (c.split(" ")) correctly extracts the count and domain even when the domain contains multiple dots, as the space character is a reliable delimiter.
When the visit count is zero, the conversion int(visits) yields 0, and the addition to the dictionary does not affect the final totals. The use of defaultdict(int) ensures that any subdomain encountered for the first time starts with a count of 0, eliminating the need for explicit existence checks.
The implementation also tolerates leading or trailing whitespace in the input strings because the split(" ") call splits on the first space and discards any surrounding whitespace automatically.
Performance Optimizations
The algorithm leverages a generator (subs) to produce subdomains on demand, avoiding the creation of an intermediate list that would increase memory usage. By yielding each subdomain directly into the accumulation loop, the code processes each subdomain exactly once.
Using defaultdict(int) eliminates conditional logic for initializing dictionary entries, which reduces the overhead of key existence checks during accumulation. The integer conversion of the visit count (int(visits)) occurs only once per input line, and the resulting integer is reused for all subdomains derived from that line, avoiding repeated parsing.
The final iteration over the dictionary keys uses a simple for a in all: loop, which iterates directly over the hash map’s internal storage without constructing additional collections. The yield statement in the last loop allows the caller to consume results lazily, which can be advantageous when the caller processes the output incrementally rather than materializing the entire list at once.
ELI5 - Simplified Explanation
Imagine that websites are like big apartment buildings. Some buildings are small and have one name, but others are giant towers that have smaller sections inside them. Sometimes people visit the whole tower, but they also visit every single individual section inside that tower too.
The code starts by looking at a list of computer addresses that show how many people visited a specific group of websites. The small part called subs is like a little helper that cuts up a long address into smaller pieces. If an address is mail.google.com, it figures out that people visited mail.google.com, but they also visited google.com and just com as well.
Next, the code creates a blank notepad to keep track of the count for every address it sees. It goes through the list of addresses one by one. For each address, it separates the number of visitors from the website name. It uses the little helper to find all the smaller pieces of that website name. Then it writes down the number of visitors next to each of those pieces on the notepad. If it finds a piece that is already on the notepad, it adds the new visitors to the total that is already there.
Finally, the code goes through everything written on the notepad. It takes the total number of visitors and the name of the website piece, puts them together into a new sentence, and shares that information for every single piece it found.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | |||||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 900: RLE Iterator
- problem 945: Minimum Increment to Make Array Unique
- problem 949: Largest Time for Given Digits
- problem 1620: Coordinate With Maximum Network Quality
- problem 2240: Number of Ways to Buy Pens and Pencils
- problem 2249: Count Lattice Points Inside a Circle
- problem 2261: K Divisible Elements Subarrays
- problem 2310: Sum of Numbers With Units Digit K
- problem 2735: Collecting Chocolates
- problem 2800: Shortest String That Contains Three Strings
- problem 2306: Naming a Company
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality