Heap Data Structure, Min and Max Heap with Leetcode # 215,
3 min readJan 8, 2024
Intuition
In this problem, I have used the technique of heap called “minHeap”
if you already know about the minheap its perfect to directly jump into the approach section, for those who do not know about heap and minheap or maxheap I will explain it to you in my own simple words:
- Heap
Heap is a special tree-based-data-structure, in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. - Min Heap
In a Min-Heap the key present at the root node must be less than or equal among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree. In a Min-Heap the minimum key element is present at the root. Below is the Binary Tree that satisfies all the properties of Min Heap.
- Max Heap
In a Max-Heap the key present at the root node must be greater than or equal among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree. In a Max-Heap the maximum key element is present at the root. Below is the Binary Tree that satisfies all the properties of Max Heap.
- Note: a little help from GFG for better explaination (a good plateform for programmers).
Approach
Perfect, Now you have the idea of min heap and max heap, here we will use the min heap technique or strategy. let's discuss the steps one by one:
- Push all the elements from the
nums
array to theminHeap
array.
Apply theheapify
function to sort theminHeap
array using the minheap
technique, sorting the elements in place. - Store the length of the given array
nums
in a variable callednumber
for future use. - Now, we will pop the elements from the lower portion of our
array
until we reach thekth
largest element: - We will reduce the
number
variable one by one until we meet the element which is at thekth
location.
Once we reach the largest element, we willpop
it is our answer like this!return heapq.heappop(minHeap)
Complexity
- Time complexity:
The time complexity of this code isO(n + klogn)
, wheren
is the number of elements in the input listnums
. The initialheapification
of theminHeap
takesO(n)
time, and then the loop runsk
times, each time performing aheappop
operation which takesO(logn)
time. Therefore, the total time complexity isO(n + klogn)
. - Space complexity:
The spacecomplexity
of this code isO(n)
because theminHeap
list is a copy of thenums
list and its size is proportional to the size of the input list.
Plz, Make me happy by upvoting.
Python
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
minHeap = nums[:]
heapq.heapify(minHeap)
number = len(nums)
while number > k:
number -= 1
heapq.heappop(minHeap)
return heapq.heappop(minHeap)