|
| 1 | +# Pattern : Two Heaps |
| 2 | +**Two Heaps Pattern: Notes** |
| 3 | + |
| 4 | +The **Two Heaps Pattern** is a powerful technique used in solving certain algorithmic problems. It involves using two heaps (data structures) to efficiently manage and process data. Here are the key points about this pattern: |
| 5 | + |
| 6 | +1. **What is the Two Heaps Pattern?** |
| 7 | + - The Two Heaps Pattern uses two heaps simultaneously to solve specific problems. |
| 8 | + - It typically involves a **Min Heap** and a **Max Heap**. |
| 9 | + - The Min Heap helps find the smallest element, while the Max Heap helps find the largest element. |
| 10 | + |
| 11 | +2. **Common Problems Solved Using Two Heaps:** |
| 12 | + - **Median of a Stream**: Maintaining a running median of a stream of numbers. |
| 13 | + - **Sliding Window Problems**: Efficiently handling sliding windows in arrays or strings. |
| 14 | + - **Top K Elements**: Finding the top K elements in a dataset. |
| 15 | + - Other problems where you need to track both minimum and maximum values. |
| 16 | + |
| 17 | +3. **How to Use Two Heaps:** |
| 18 | + - Initialize a Min Heap and a Max Heap. |
| 19 | + - Split the input into two parts: one for maximum elements and the other for minimum elements. |
| 20 | + - For example, if we have the numbers 2, 6, 8, 10, 12, and 15, we split them into: |
| 21 | + - Max heap: 2, 6, 8 |
| 22 | + - Min heap: 10, 12, 15 |
| 23 | + - The median can be calculated based on these heaps (average for even numbers, middle element for odd numbers). |
| 24 | + |
| 25 | +4. **When to Use Two Heaps:** |
| 26 | + - When you can divide the input into two parts, with one part containing maximum elements and the other containing minimum elements. |
| 27 | + - Also applicable when two properties are directly proportional, and you want to minimize one while maximizing the other (e.g., capital and profit). |
| 28 | + |
| 29 | +[Reference: YT Playlist](https://youtube.com/playlist?list=PLYMuCXiM_KMhKHFvfcdyAPHNoVo-qwpKX&feature=shared) |
0 commit comments