Subdomain Visit Count — LeetCode 811 Python Solution

MediumArrayHash TableStringCounting
Problem
#811
Pattern
Hash Map
Reading time
2 min

The problem

A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com".

Example

Input
cpdomains = ["9001 discuss.leetcode.com"]
Output
["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]
Explanation
We only have one website domain: "discuss.leetcode.com".

Python solution

Python
class Solution:
    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
        cnt = Counter()
        for s in cpdomains:
            v = int(s[: s.index(' ')])
            for i, c in enumerate(s):
                if c in ' .':
                    cnt[s[i + 1 :]] += v
        return [f'{v} {s}' for s, v in cnt.items()]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 811. Subdomain Visit Count is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 811. Subdomain Visit Count?
LeetCode 811. Subdomain Visit Count is rated Medium on LeetCode.
What is the time complexity of LeetCode 811. Subdomain Visit Count?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 811. Subdomain Visit Count?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 811. Subdomain Visit Count cover?
LeetCode 811. Subdomain Visit Count is tagged Array, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview