Kth LARGEST ELEMENT IN AN ARRAY - SOLUTION EXPLAINED [PYTHON]
Вставка
- Опубліковано 25 чер 2024
- In this video we're going to be solving a popular interview question that can be solved using a heap data structure. It's a popular question at pretty much all the FAANG companies and will be going forward as it's a very commonly used topic in most algorithms interviews.
You would probably see me in all your videos at this point but I appreciate you man! Thank you! I pray I get my faang job soon with the effor Tim putting in!
It really clear explanation, and also shows the time and space complexity.
Great video what does it mean heapq and why you didn't import it to use it
heapq is the Python standard library for heaps. In Leetcode it's basically globally imported for you so you don't have to write `import heapq`
Can you tell me why not do this instead?
def findKthLargest(self, nums: List[int], k: int) -> int:
#max heap creation
negatedNums = [-x for x in nums]
heapq.heapify(negatedNums)
returnElement = -1
#remove k elements
while k>0:
returnElement = heapq.heappop(negatedNums)
k-=1
return -1*returnElement
Runtime to create the heap is O(N) and runtime to pop an element is O(logN) and we do it K times = O(N + kLogN) = O(kLogN) is that not enough? How do justify O(NLogK) is better than this?
I believe when you heapify nums, you need to perform a heap operation for N items, resulting in O(NlogN) every time?
Why you don't implement heap data structure instead of using heapq
Why would I do that, it's complete overkill.