Skip to content

Commit 2ffde66

Browse files
author
hasibulislam999
committed
Find Median from Data Stream problem solved
1 parent 84e5511 commit 2ffde66

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Title: Find Median from Data Stream
3+
* Description: 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.
4+
* Author: Hasibul Islam
5+
* Date: 28/04/2023
6+
*/
7+
8+
class MedianFinder {
9+
//Initilize max and min heap
10+
constructor() {
11+
this.minHeap = new MinPriorityQueue(); //supported by leetcode
12+
this.maxHeap = new MaxPriorityQueue();
13+
}
14+
15+
addNum(num) {
16+
//add to min and pop the top for max to keep them in the order that we want
17+
this.minHeap.enqueue(num);
18+
this.maxHeap.enqueue(this.minHeap.dequeue().element);
19+
//balance them
20+
if (this.minHeap.size() < this.maxHeap.size()) {
21+
this.minHeap.enqueue(this.maxHeap.dequeue().element);
22+
}
23+
//console.log(this.minHeap.toArray(), this.maxHeap.toArray()) //run this to understand better
24+
}
25+
26+
findMedian() {
27+
if (this.minHeap.size() > this.maxHeap.size())
28+
// if one is bigger 21 and 345 example just pop from 345(min heap)
29+
return this.minHeap.front().element;
30+
else
31+
return (this.minHeap.front().element + this.maxHeap.front().element) / 2; // 21 and 34 example, pop 1 and 3 and find average
32+
}
33+
}
34+
35+
/**
36+
* Your MedianFinder object will be instantiated and called as such:
37+
* var obj = new MedianFinder()
38+
* obj.addNum(num)
39+
* var param_2 = obj.findMedian()
40+
*/

0 commit comments

Comments
 (0)