Middle+
Implement a function to find the service with the most logs in each namespace. What is the complexity of algorithms for top-1, top-2, top-10?
sobes.tech AI
Answer from AI
To find the service with the most logs in each namespace, you can use the following approach:
- Iterate through all logs, group them by namespace and service, counting the number of logs.
- For each namespace, determine the service with the maximum number of logs.
Example implementation in Go:
type Log struct {
Namespace string
Service string
}
func TopServicePerNamespace(logs []Log) map[string]string {
counts := make(map[string]map[string]int)
for _, log := range logs {
if counts[log.Namespace] == nil {
counts[log.Namespace] = make(map[string]int)
}
counts[log.Namespace][log.Service]++
}
result := make(map[string]string)
for ns, svcCounts := range counts {
maxCount := 0
var topService string
for svc, count := range svcCounts {
if count > maxCount {
maxCount = count
topService = svc
}
}
result[ns] = topService
}
return result
}
Algorithm complexity for top-N
-
Top-1: like in the example above — one pass through logs O(M), where M is the number of logs, and then a pass through services in each namespace. If on average there are S services per namespace and N namespaces, the total is — O(M + N*S).
-
Top-2, Top-10: you need to sort services by log count for each namespace or use a data structure to maintain the top-N.
- Sorting services for each namespace: O(N * S log S)
- Using a heap for top-N: O(N * S log N)
If N and S are small, sorting is quite acceptable. If they are very large, it’s better to use a heap for optimization.