Hello there, budding programmer! I hope you're ready because today we're going to dive deep into high-level data manipulation and increase our understanding of heaps. Heaps are fundamental data structures commonly used in algorithms. We're going to leverage their potential today in an interesting algorithmic problem. Are you ready for the challenge? Let's get started!
A heap is a specialized binary tree-based data structure that satisfies the heap property: for a Min Heap, every parent node is less than or equal to its child nodes; for a Max Heap, every parent node is greater than or equal to its child nodes. This property makes heaps particularly efficient for operations like finding the minimum or maximum value.
In practice, heaps can be implemented using arrays. For a given node at index i in an array:
- Its left child is at index
2 * i + 1 - Its right child is at index
2 * i + 2 - Its parent is at index
Math.floor((i - 1) / 2)
In our context, we use two specific types of heaps: a Min Heap and a Max Heap. The Min Heap is used to store the larger half of the numbers seen so far, while the Max Heap stores the smaller half. JavaScript does not have built-in heap functionality, so we will implement one or use an external library.
Here, we'll use simple custom implementations for MinHeap and MaxHeap.
To make the functions easier to understand, let's define our MinHeap and MaxHeap classes first. We will use negation to simulate a MaxHeap with MinHeap operations.
The MinHeap class defines a min-heap with methods to add elements (add), remove and return the smallest element (poll), get the smallest element without removing it (peek), and get the heap size (size). The methods _heapifyUp and _heapifyDown maintain the heap property after adding or removing elements, respectively. The MaxHeap class extends MinHeap by using negation to maintain a max-heap; it overrides the add, poll, and peek methods to negate the values, effectively turning the min-heap operations into max-heap operations.
