The solution’s stated time complexity is O(nlogk), because we push/pop n times with a heap of size k.
Instead of pushing the first k elements individually, what if we added them to the heap’s underlying list and then ran heapify? This would take O(k), so our final time complexity would be O(k) + O((n-k)logk) = O((n-k)logk).
Course: Grokking Coding Interview Patterns in Python - Learn Interactively
Lesson: https://www.educative.io/courses/grokking-coding-interview-patterns-python/solution-top-k-frequent-elements