Sir please send the code for running median of a stream of integers.I can’t code it.
Code of Running median of a stream
hello @ayushgoyal20
refer this ->
- Create two heaps. One max heap to maintain elements of lower half and one min heap to maintain elements of higher half at any point of time…
- Take initial value of median as 0.
- For every newly read element, insert it into either max heap or min heap and calulate the median based on the following conditions:
- If the size of max heap is greater than size of min heap and the element is less than previous median then pop the top element from max heap and insert into min heap and insert the new element to max heap else insert the new element to min heap. - -
- Calculate the new median as average of top of elements of both max and min heap.
- If the size of max heap is less than size of min heap and the element is greater than previous median then pop the top element from min heap and insert into max heap and insert the new element to min heap else insert the new element to max heap. - -
- Calculate the new median as average of top of elements of both max and min heap.
- If the size of both heaps are same. Then check if current is less than previous median or not. If the current element is less than previous median then insert it to max heap and new median will be equal to top element of max heap. If the current element is greater than previous median then insert it to min heap and new median will be equal to top element of min heap.
still if u face any issue in implementation
then u can refer this->
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.