Pregunta de entrevista de Island

process(id) – A function that receives string IDs (e.g., "a", "b", "c", "d") as input. conclude() – A function that returns the top 10 results. The goal is to achieve an O(n) time complexity.

Respuesta de la entrevista

Anónimo

6 de mar de 2025

A naive approach would be to store the inputs in a hashmap, then sort the entries and return the top 10 results. However, this results in an O(n log n) time complexity due to sorting. A better solution is to maintain a hashmap to track the occurrences of each ID while simultaneously maintaining a min-heap (priority queue) of size 10. As we process new inputs, we update their counts in the hashmap. If the heap contains fewer than 10 elements, we add the new entry. If it's full, we check if the new input has a higher count than the smallest element in the heap. If so, we replace the smallest element. This approach ensures an O(n) time complexity, as we avoid sorting and only perform constant-time operations per input.