LeetCode 811: Subdomain Visit Count Solution
Master LeetCode problem 811 (Subdomain Visit Count), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
811. Subdomain Visit Count
Problem Explanation
Explanation
To solve this problem, we can iterate through each domain in the input array, split the count and domain parts, and then split the domain into its subdomains. We will maintain a hashmap to store the count of visits for each subdomain. By iterating through each domain and its subdomains, we can update the count for each subdomain in the hashmap. Finally, we will construct the result array by combining the count and subdomain.
- Time complexity: O(n * m), where n is the number of domains and m is the maximum number of subdomains in a domain.
- Space complexity: O(n * m), where n is the number of domains and m is the maximum number of subdomains in a domain.
Solution Code
import java.util.*;
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> countMap = new HashMap<>();
for (String cpdomain : cpdomains) {
String[] parts = cpdomain.split(" ");
int count = Integer.parseInt(parts[0]);
String domain = parts[1];
String[] subdomains = domain.split("\\.");
StringBuilder sb = new StringBuilder();
for (int i = subdomains.length - 1; i >= 0; i--) {
sb.insert(0, subdomains[i]);
countMap.put(sb.toString(), countMap.getOrDefault(sb.toString(), 0) + count);
sb.insert(0, ".");
}
}
List<String> result = new ArrayList<>();
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
result.add(entry.getValue() + " " + entry.getKey());
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 811 (Subdomain Visit Count)?
This page provides optimized solutions for LeetCode problem 811 (Subdomain Visit Count) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 811 (Subdomain Visit Count)?
The time complexity for LeetCode 811 (Subdomain Visit Count) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 811 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 811 in Java, C++, or Python.