How do I implement a min-heap and max-heap in TypeScript?
Min-heaps and max-heaps are binary trees used for efficient priority queue operations. In TypeScript, you can implement them using arrays with helper functions for insertion and deletion.
Heaps are specialized binary trees that are used to maintain the maximum or minimum element in constant time, making them ideal for priority queue operations. A min-heap maintains the smallest element at the root, while a max-heap keeps the largest element at the root. Both types of heaps can be implemented using arrays, where the parent-child relationships are easily managed using simple index arithmetic. Specifically, for an element at index i, the left child is at index 2 * i + 1, and the right child is at index 2 * i + 2. When inserting an element into a heap, the element is added at the end of the array, and then it 'bubbles up' to maintain the heap property (for min-heap, it moves up until it is smaller than its parent, and for max-heap, it moves up until it is larger). Conversely, when removing the root element (the smallest or largest), the last element replaces the root, and then it 'sinks down' to restore the heap property. In TypeScript, you can implement heaps using arrays and helper functions for insertion, deletion, and heapify operations. Min-heaps and max-heaps are essential for solving problems like finding the k-th smallest or largest element in a dataset, scheduling tasks, and implementing algorithms like Dijkstra’s for shortest paths.