Complete the code to declare a min heap array for storing elements.
int minHeap[[1]];The min heap size should be equal to k, the number of top frequent elements to find.
Complete the code to push an element into the min heap.
void push(int val) {
minHeap[size] = val;
int i = size;
size++;
while (i > 0 && freq[minHeap[i]] < freq[minHeap[1]]) {
int parent = (i - 1) / 2;
int temp = minHeap[i];
minHeap[i] = minHeap[parent];
minHeap[parent] = temp;
i = parent;
}
}We compare the current element with its parent to maintain heap property.
Fix the error in the code to pop the smallest element from the min heap.
int pop() {
int root = minHeap[0];
minHeap[0] = minHeap[size - 1];
size--;
int i = 0;
while (2 * i + 1 < size) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int smallest = left;
if (right < size && freq[minHeap[right]] < freq[minHeap[1]]) {
smallest = right;
}
if (freq[minHeap[i]] <= freq[minHeap[smallest]])
break;
int temp = minHeap[i];
minHeap[i] = minHeap[smallest];
minHeap[smallest] = temp;
i = smallest;
}
return root;
}We compare right child with left child to find the smaller one.
Fill both blanks to build a frequency map and insert elements into the min heap.
for (int i = 0; i < n; i++) { freq[nums[i]] = freq[nums[i]] + 1; } for (int key = 0; key < maxKey; key++) { if (freq[key] > 0) { if (size < [1]) { push(key); } else if (freq[key] > freq[minHeap[0]]) { pop(); push(key); } } } return minHeap[[2]];
We insert until heap size reaches k, then compare with minHeap root at index 0.
Fill all three blanks to extract top k frequent elements from the min heap into result array.
int result[[1]]; for (int i = [2]; i >= 0; i--) { result[i] = pop(); } return result;
Result array size is k. Loop from k-1 down to 0 to fill result in reverse order.
