Find the least frequent value in a list in O(n log n) or better, and the k-th largest element in expected O(n) time. Explain the complexity.
Answer
Model answer, written in a candidate's voice
In short
- Count frequencies with a hash map in O(n), then scan counts; sorting is an O(n log n) fallback.
- Define tie-breaking explicitly, e.g. return the smallest value among tied least-frequent values.
- Use randomised quickselect for k-th largest in expected O(n); worst case is O(n^2).
- Alternative: keep a size-k min-heap in O(n log k) time and O(k) space.
- Handle empty input, invalid k, duplicates, all-equal lists, and k=1/k=n.
In full
For the least frequent value, I would count frequencies with a hash map in O(n) time and O(m) space, then scan the counts once to find the minimum frequency; sorting is an O(n log n) alternative if I want a simpler but slower approach. I would state a tie-breaking policy up front, such as returning the smallest value among all tied least-frequent values, because otherwise the answer is ambiguous. For the k-th largest element, randomised quickselect gives expected O(n) time by partitioning around a random pivot and recursing only into the side containing the k-th order statistic; its worst case is O(n^2), though deterministic linear-time selection exists. A heap alternative is to maintain a min-heap of the k largest seen so far, which costs O(n log k) time and O(k) space, with the root equal to the k-th largest. Edge cases: empty list has no least frequent value and no valid k-th largest; k must satisfy 1 <= k <= n; duplicates and all-equal lists are handled by the same counting/selection logic; k=1 is the maximum and k=n is the minimum.
What a strong answer covers
- Hash counting O(n), or sorting O(n log n).
- A tie-breaking policy.
- Quickselect in expected O(n); a heap in O(n log k).
- Edge cases.
Common mistakes
- Nested O(n²) counting.
- Not knowing quickselect’s worst case.