Sobes.tech
Middle+

Implement a top-5 service retrieval in O(N) using an auxiliary structure.

sobes.tech AI

Answer from AI

To obtain the top 5 services in O(N), you can use a data structure called a "min-heap" of fixed size 5. The idea is to iterate through all services once, maintaining the current top 5 according to the desired criterion (for example, by the number of requests or rating).

Example in Go:

package main

import (
	"container/heap"
	"fmt"
)

type Service struct {
	Name  string
	Score int
}

type MinHeap []Service

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].Score < h[j].Score }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	*h = append(*h, x.(Service))
}

func (h *MinHeap) Pop() interface{} {
	old := *h
	n := len(old)
	item := old[n-1]
	*h = old[0 : n-1]
	return item
}

func Top5Services(services []Service) []Service {
	h := &MinHeap{}
	heap.Init(h)

	for _, s := range services {
		if h.Len() < 5 {
			heap.Push(h, s)
		} else if s.Score > (*h)[0].Score {
			heap.Pop(h)
			heap.Push(h, s)
		}
	}

	// Result is in the heap, can be sorted in descending order
	result := make([]Service, h.Len())
	for i := len(result) - 1; i >= 0; i-- {
		result[i] = heap.Pop(h).(Service)
	}
	return result
}

func main() {
	services := []Service{
		{"A", 10}, {"B", 50}, {"C", 30}, {"D", 40}, {"E", 20}, {"F", 60}, {"G", 15},
	}
	top5 := Top5Services(services)
	for _, s := range top5 {
		fmt.Println(s.Name, s.Score)
	}
}

This approach iterates through the array once (O(N)) and maintains a heap of 5 elements, which is efficient in terms of time and memory.