Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: From n = 10⁶ log entries, return the k = 10 most frequent error codes. Which approach is the most efficient?

  1. A. Sort all n entries and scan – always O(n) total
  2. B. Build a max-heap of all n entries and pop k times – O(k) total
  3. C. Use a BST of entries keyed by code – O(k log n)
  4. D. Count with a hash map, then keep a min-heap of size k over the (count, code) pairs – O(n + m log k) for m distinct codes

Correct answer: D. Count with a hash map, then keep a min-heap of size k over the (count, code) pairs – O(n + m log k) for m distinct codes

Counting is O(n); a size-k heap over m distinct codes costs O(m log k). Sorting entries is O(n log n). Heapifying n raw entries ignores that frequencies must be counted first. Bucket sort by frequency is another O(n + m) option.

More Coding Interview Problems questions

Exams that ask this topic