> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/heaps-and-priority-queue/295.-find-median-from-data-stream.md).

# 295. Find Median from Data Stream

## Problem Statement

<br>

The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

* For example, for `arr = [2,3,4]`, the median is `3`.
* For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.

Implement the MedianFinder class:

* `MedianFinder()` initializes the `MedianFinder` object.
* `void addNum(int num)` adds the integer `num` from the data stream to the data structure.
* `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.

&#x20;

**Example 1:**

<pre><code><strong>Input
</strong>["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
<strong>Output
</strong>[null, null, null, 1.5, null, 2.0]

<strong>Explanation
</strong>MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
</code></pre>

&#x20;

**Constraints:**

* `-105 <= num <= 105`
* There will be at least one element in the data structure before calling `findMedian`.
* At most `5 * 104` calls will be made to `addNum` and `findMedian`.

## Intuition

```
MAintain two heaps and Balance them, For more refer Sliding Window Median
```

### Links

<https://leetcode.com/problems/find-median-from-data-stream/description/>

### Video Links

### Approach 1:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
class MedianFinder {
public:  
    priority_queue<int> max_heap;
    priority_queue<int, vector<int>, greater<int>> min_heap;

    void addNum(int num) {
        if(max_heap.empty() or num <= max_heap.top())
            max_heap.push(num);
        
        else 
            min_heap.push(num);

        if(max_heap.size()+1 < min_heap.size()){
            max_heap.push(min_heap.top());
            min_heap.pop();
        }
        else if(min_heap.size()+1 < max_heap.size()){
            min_heap.push(max_heap.top());
            max_heap.pop();
        }
    }
    
    double findMedian() {
        if(max_heap.size() == min_heap.size())
            return ((double)min_heap.top() + (double)max_heap.top()) / 2.0;

        else if(max_heap.size() > min_heap.size())
            return (double)max_heap.top();

        return (double)min_heap.top();

    }
};
```

{% endcode %}

### Approach 2:

```
Self code
```

{% code title="C++" lineNumbers="true" %}

```cpp
class MedianFinder {
public:
    priority_queue<int> max_heap;
    priority_queue<int, vector<int>, greater<int>> min_heap;
    void balance(){
        int a=max_heap.size(), b=min_heap.size();
        if(a==b or a==1+b or b==1+a)
            return ;

        else if(b>a and b!=1+a){
            int temp = min_heap.top();
            min_heap.pop();
            max_heap.push(temp);
        }
        else if(a>b and a!= 1+b){
            int temp = max_heap.top();
            max_heap.pop();
            min_heap.push(temp);
        }
    }

    void addNum(int num) {
        if(max_heap.size() == 0 or min_heap.size() == 0)
            max_heap.push(num);
        else if(num < max_heap.top()){
            max_heap.push(num);
        }
        else
            min_heap.push(num);

        

        balance();
    }
    
    double findMedian() {
        int a=max_heap.size(), b=min_heap.size();
        // return 0;
        if(a == b)
            return (max_heap.top() + min_heap.top() )/ 2.0;
        else if(a > b)
            return max_heap.top();
        return min_heap.top();
    }
};
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://coding-9.gitbook.io/untitled/heaps-and-priority-queue/295.-find-median-from-data-stream.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
