3 ms·
collections.Counter.most_common() uses heapq.nlargest() which is slightly more efficient than a full n*log n sort. But implementing a heap correctly from scratc
by cben 13y ago
collections.Counter.most_common() uses heapq.nlargest() which is slightly more efficient than a full n*log n sort.
But implementing a heap correctly from scratch is I guess outside the scope the OP intends for the interview question.
I would expect a good candidate to:
1. know that a heap is optimal here (remembering whether Counter uses it is optional)
2. express reluctance to implement it from scratch because surely the stdlib can do it better.
So IMHO using libraries like this ruins the question only in the sense of showing its not a challenge for the candidate. Something so simple should not take a page of code.
- klipt 13y ago> collections.Counter.most_common() uses heapq.nlargest() which is slightly more efficient than a full n*log n sort. Creating a heap is O(n) if I remember correctly, so that may well be the most efficient solution.