I have a simple algorithm task for which I'd like to practice my complexity analysis, and I was hoping to get some confirmation that I'm correct.
The task is; implement a function that takes an array of numbers of size n
, and returns the k
highest values. The implementation should be time and space efficient.
Here is my pseudo-code:
- Create a binary min heap of size k + 1.
- For each number in the array;
- Push the value onto the heap.
- If the heap size is now larger than k, pop the minimum value.
- Pop all values from the heap and return the results array.
Here is my time complexity analysis for each step:
- Negligible.
- O(n)
- O(log n)
- Negligible
- O(k)
So total complexity should be O(n.log n + k)? Space complexity should be O(k + 1)?
Also, any critique of my method welcomed.
Thanks in advance!