Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of getting first n largest elements in min heap?

Tags:

python

Given that heapq in python is min heap as specified in python doc, assume that I have a heapq with m elements, what is the time complexity of calling nlargest? I don't think the complexity is O(n*lg(m)) because simply popping the root and heapify again in a min heap only get you nsmallest?

How does heapq.nlargest work?

like image 302
Gary Avatar asked Mar 17 '15 21:03

Gary


People also ask

What is the time complexity of finding the largest element in a min-heap?

Brute force approach: We can check all the nodes in the min-heap to get the maximum element. Note that this approach works on any binary tree and does not makes use of any property of the min-heap. It has a time and space complexity of O(n).

What is the time complexity for getting minimum element in min-heap?

The time complexity to find the minimum element in a min-heap is O(1) , that is the primary purpose of such a container. It was literally made to find the smallest (or largest) element in constant time. The operation that is O(logn) is insertion.

Where in a min-heap might the largest element reside?

(CLRS 6.1-4) Where in a min-heap might the largest element reside, assuming that all elements are distinct? Solution: Since the parent is greater or equal to its children, the smallest element must be a leaf node.

What is the time complexity of Max Heap?

Time Complexity of Min/Max Heap The Time Complexity of this operation is O(1).


Video Answer


1 Answers

You can see the code here. Suppose you do a heapq.nlargest(n, it), where it is an iterable with m elements. It first constructs a min heap with the first n elements of it. Then, for the rest m-n elements, if they are bigger than the root, it takes the root out, puts the new element, and shifts it down. At the end, the complexity is O(log(n) * m).

like image 185
matiasg Avatar answered Sep 28 '22 03:09

matiasg