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?
- A. Sort all n entries and scan – always O(n) total
- B. Build a max-heap of all n entries and pop k times – O(k) total
- C. Use a BST of entries keyed by code – O(k log n)
- 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
- Problem: Merge k sorted lists of order timestamps into one sorted list. python import heapq def mergek(lists): h = [(l[0], i, 0) for i, l…
- Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half). python import heapq…
- Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost. python import heapq def…
- Problem: Return the k points closest to the origin (ties broken by smaller index). python import heapq pts = [(3, 3), (5, -1), (-2, 4)…
- Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time. python…
- Problem: Merge overlapping booking intervals. python def merge(iv): iv.sort(); out = [] for s, e in iv: if out and s <= out[-1][1]…