r/programminghelp • u/the_recovery1 • Jan 03 '21
Python Need help understanding time complexity of this code
I have two loops like so that runs over a list of numbers with n elements
for n in numsList:
heapq.heappush(heap, n)
while heap:
num = heapq.heapop(h)
The time complexity of first loop is nlogn since there are n elements and the heap needs to maintain the heap property when elements are inserted (heapify on each loop) so it is nlogn ( n elements x heap insert cost for each element which is logn)
While the second loop, runs for n elements and heappop takes logn times for each run so overall for second loop is nlogn again?
I am not clear on either actually especially the second loop where I believe it should be n instead of nlogn.
Thanks!
3
Upvotes
1
u/serg06 Jan 03 '21
Yep both are n*log(n) so overall it's n*log(n)