A website domain like "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". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.
For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.
Given an array of count-paired domainscpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.
The key insight is that each domain visit contributes to all its parent domains. Use a hash map to accumulate visit counts for each subdomain. Parse each input to extract count and domain, then generate all subdomains by splitting at dots. Best approach is the optimized hash map with single-pass parsing. Time: O(n×m), Space: O(n×m) where n is number of domains and m is average subdomains per domain.
Common Approaches
Approach
Time
Space
Notes
✓
Optimized Hash Map with String Processing
O(n × m)
O(n × m)
Efficiently parse domains and use hash map for frequency counting with minimal string operations
Brute Force with Hash Map
O(n × m)
O(n × m)
Parse each domain string and extract all subdomains, using hash map to count visits
Optimized Hash Map with String Processing — Algorithm Steps
Initialize hash map for domain visit counts
For each input, parse count and domain in single pass
Generate subdomains by finding dot positions in domain string
Accumulate counts in hash map and format final output
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Single Parse
Extract count and domain in one pass
2
Dot Finding
Locate dot positions without splitting
3
Direct Accumulation
Add counts directly to hash map
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DOMAINS 1000
#define MAX_LEN 256
struct DomainCount {
char domain[MAX_LEN];
int count;
};
int findDomain(struct DomainCount* domains, int size, const char* domain) {
for (int i = 0; i < size; i++) {
if (strcmp(domains[i].domain, domain) == 0) {
return i;
}
}
return -1;
}
char** solution(char** cpdomains, int cpdomain_size, int* returnSize) {
struct DomainCount domains[MAX_DOMAINS];
int domain_count = 0;
for (int i = 0; i < cpdomain_size; i++) {
// Find space separator
char* space = strchr(cpdomains[i], ' ');
int count = atoi(cpdomains[i]);
char* domain = space + 1;
// Add count to full domain
int idx = findDomain(domains, domain_count, domain);
if (idx >= 0) {
domains[idx].count += count;
} else {
strcpy(domains[domain_count].domain, domain);
domains[domain_count].count = count;
domain_count++;
}
// Find all dot positions and create subdomains
char* dot = strchr(domain, '.');
while (dot) {
char* subdomain = dot + 1;
idx = findDomain(domains, domain_count, subdomain);
if (idx >= 0) {
domains[idx].count += count;
} else {
strcpy(domains[domain_count].domain, subdomain);
domains[domain_count].count = count;
domain_count++;
}
dot = strchr(subdomain, '.');
}
}
// Format result
char** result = (char**)malloc(domain_count * sizeof(char*));
for (int i = 0; i < domain_count; i++) {
result[i] = (char*)malloc(MAX_LEN);
sprintf(result[i], "%d %s", domains[i].count, domains[i].domain);
}
*returnSize = domain_count;
return result;
}
int main() {
char line[10000];
fgets(line, sizeof(line), stdin);
// Simple JSON parsing for array of strings
char* cpdomains[100];
int count = 0;
char* start = strchr(line, '"');
while (start) {
start++;
char* end = strchr(start, '"');
if (!end) break;
int len = end - start;
cpdomains[count] = (char*)malloc(len + 1);
strncpy(cpdomains[count], start, len);
cpdomains[count][len] = '\0';
count++;
start = strchr(end + 1, '"');
}
int returnSize;
char** result = solution(cpdomains, count, &returnSize);
// Output as JSON array
printf("[");
for (int i = 0; i < returnSize; i++) {
if (i > 0) printf(",");
printf("\"%s\"", result[i]);
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n × m)
n input domains, each generating average m subdomains
n
2n
✓ Linear Growth
Space Complexity
O(n × m)
Hash map stores all unique subdomains across all inputs
n
2n
⚡ Linearithmic Space
89.2K Views
MediumFrequency
~15 minAvg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.