Complexity characteristics of a simple heap-based array function

106 views Asked by At

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:

  1. Create a binary min heap of size k + 1.
  2. 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.
  3. Pop all values from the heap and return the results array.

Here is my time complexity analysis for each step:

  1. Negligible.
  2. O(n)
    • O(log n)
    • Negligible
  3. 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!

0

There are 0 answers