Find Median from Data Stream
This video explains how to find median in a data stream.In this problem, given a stream of integers we are required to find median at any given point in a running integer also known as stream of integers.I have explained the problem with intuitive examples and i have also shown all the required intuition for solving the problem.I have first solved it using simple solution using sorting technique which is insertion sort.Later, I have shown the intuition for optimization and solved using 2 heaps. One maxheap containing left half values and the other as minheap containing the right half values of the ordered array.We can find median in constant time using the formula as I have shown for ODD and EVEN number of elements.
CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
======================================PLEASE DONATE=============================
🧡 SUPPORT OUR WORK: / techdose
💚 UPI-ID: surya.kahar@ybl
💞JOIN Membership: / @techdose4u
==============================================================================
INSTAGRAM : / surya.pratap.k
LinkedIn: / surya-pratap-kahar-47b...
WEBSITE: techdose.co.in/
TELEGRAM Channel LINK: t.me/codewithTECHDOSE
TELEGRAM Group LINK: t.me/joinchat/SRVOIxWR4sRIVv5...
=======================================================================
USEFUL LINKS:
🟠Must do TIPS to ACE Virtual Interview: • 🔴Must do Tips to ACE y...
🟢Best strategy to excel your coding interview: • 🔴Best strategy to exce...
🟡Get your dream job in 1 month: • 🔴Get your dream job in...
🔵How to crack dream job in just 2 months: • How to crack dream job...
🟣7 Days DSA plan: techdose.co.in/7-days-dsa-che...
RELATED LINKS:
Power of Heap: • Power of Heap
Concepts of Heap: • Concepts of Heap | Und...
Representation of Heap: • Representation of Heap...
Heapify Algorithm: • Heapify Algorithm | Ma...
Build heap algorithm: • Build Heap Algorithm |...
Heap Algorithm: • Heap Algorithms | Extr...
Heapsort Algorithm: • Heapsort Algorithm | C...
Heap Implementation: • Heap Implementation | ...
Top K frequent elements: • Top K Frequent Element...
Sort a K-sorted array: • Sort K sorted array | ...
Sliding window maximum: • Sliding Window Maximum...
Merge K sorted lists: • Merge K sorted lists |...
CODE LINK: techdose.co.in/median-from-da...
#heap #datastream #2heaps
Пікірлер: 137
Hey thanks for uploading, I have requested this video in previous video and yesterday I got intern offer from Intuit. Thanks to you ❤️. Everything you explain are too good to grab and follow-up.
@techdose4u
3 жыл бұрын
Woww ❤️ congratulations 🎉
@hardikagarwal7652
3 жыл бұрын
Bhai kaise mili intuit m intern?
@jettdexter6719
2 жыл бұрын
i guess Im randomly asking but does any of you know a way to log back into an instagram account? I was dumb forgot the login password. I would love any help you can give me!
@CodeSuccessChronicle
2 жыл бұрын
@@jettdexter6719 try forget password dude
@pranav288
Жыл бұрын
@@CodeSuccessChronicle it's a bot
For the first time in almost 6 months finally we see a face behind the voice that has been guiding me in coding.
@techdose4u
2 жыл бұрын
😅
@ashishkumarchoubey5592
2 жыл бұрын
@@techdose4u Saying hello from Asansol, your neighbouring city
Great video, and great questions as well during the switch from brute to optimal! Loved it, thanks :)
You are really doing an awesome job sir. May God bless you!!!!
Really amazing explaination, hands down one of the best dsa teacher on yt.
2 days to complete this course. Thank you for your valuable lesson.
Best Explanation. Hats off you.
Thanks for the wonderful explination
This channel deserves 1M subs!
Best Explaination on youtube!
Nice explanation sir...thanks a lot for the video
*THE IMPLEMENTATION CAN BE MADE A LOT MORE SIMPLIER- * class MedianFinder { public: priority_queue maxheap; //1st half -> in case odd size of the total stream, the extra ele will be in the left half (max-heap) priority_queue minheap; //2nd half MedianFinder() { } void addNum(int num) { int lsize = maxheap.size(); int rsize = minheap.size(); if(lsize==0) maxheap.push(num); // the right-half is surely empty -> so, num is the 1st element in stream -> store it in the first half else if(lsize==rsize) { // as the max-heap can take one extra element -> So, ONE element will go on first half (BUT, NOT NECESSARILY 'NUM') if(num that means lsize>rsize. So, one element will surely be inserted in right side (BUT, NOT NECESSARILY 'NUM') if(num>maxheap.top()) minheap.push(num); // when num>maxHeap.top(), it will obviously go on the right-side -> No Violation else{ // Otherwise, we need to shift the maxHeap.top() to the minHeap, and push the 'num' in maxHeap int temp = maxheap.top(); maxheap.pop(); maxheap.push(num); minheap.push(temp); } } } double findMedian() { int totSize = maxheap.size() + minheap.size(); return totSize%2==1? maxheap.top() : (maxheap.top()+minheap.top())/2.0; } }; EXPLANATION IN SIMPLE WORDS- -> We divide the entire array into two halves, and there can be two cases - - In case of ODD size, the maximum element from the left side will be the mediun (as we keep one extra element in the left side) - In case of EVEN size, the average of 'maximum from left' and 'minimum from right' will be the mediun -> In order to maintain the max and min from both the sides respectively we can use maxHeap for the left-side (as the root will hold the max), and minHeap for the right-side (as the root will hold the min) BUT, WHEN TO INSERT IN WHICH SIDE? -> There can be 3 major cases- 1. When both the sides are empty - Insertion will take place in left side for sure 2. When both the sides have equal elements (but, not 0) - One element will surely be inserted in left-side as we keep one extra element in left side, BUT not necesarily the current element. There will be 2 cases- - when the current element is lesser than the minimum of right-side, the current element will surely be inserted in left-side, as there's NO VIOLATION - Otherwise, shift the minHeap.top() to the maxHeap, and push the 'num' in minHeap (to maintain the overall ordering) 3. When left-side already have one extra element - in this case one element will surely be inserted in right-side, BUT not necessarily the current one. There will be 2 cases- - if the current element is greater than the maximum of left-side, then obviously the current element will be placed in the right-side (No Violation) - Otherwise, we need to shift the maxHeap.top() to the minHeap, and push the 'num' in maxHeap TC: O(N*logN), as it takes O(logN) for the operations in HEAP SC: O(N), as we store the elements in HEAP*/ ANYWAYS, AMAZINGGGGGGGGGGGGG EXPLANATION....
@anu8928
7 ай бұрын
Very Nicely explained!! 🙏🏼
Awesome. Just when you said devide them jnto 2 halve, immediately it became easier.
Great Explanation.!
Thanks! Keep up the good work!😃
Thank you for this nice explanation. I visited different sites to solve this question. Your solution is very simple and efficient to understand.
You're my hero man.
For the first time, I came to know about real life use of insertion sort.. Thank you Sir !! Great explaintion...
@techdose4u
Жыл бұрын
Welcome :)
Mujhe nhi lagta KZread pe Striver aur TechDose se jyada achaa coding ke liye koi channel h........YOU ARE THE GEM❤
great explanation
Great explanation to this hard problem. Lot of companies ask this one.
@techdose4u
3 жыл бұрын
Yea. It's very important :)
@dhruvkaran9724
2 жыл бұрын
@@techdose4u amazon asked me this and i was totally clueless now i know y i was clueless
Amazing explanation! It would have helped even more if you could discuss the follow up in the question as well!
@techdose4u
3 жыл бұрын
Hmmm....I somehow missed the follow-up I guess :O
thanks for your explanation, sir this is really good .
Really nice man! The questions you put to improve over the brute force algo are really crucial to understand the intuition. Thanks Sir. Plz consider doing more leetcode :)
@techdose4u
3 жыл бұрын
Sure bro :)
perfect Explanation
very nice sir thank you so much
the best solution ever !!
Just completed this Heap Series. You are just amazing. Recommended your channel to all my friends. Sir, is deque important for interviews? If so, can you also please make a series on deque also?
@techdose4u
3 жыл бұрын
Thanks. Sure
Watched the entire heap series. can i hope for more series like this
@techdose4u
3 жыл бұрын
Yes
great explaination
What a beautiful explanation !❤️ Thank you Bhaiya again...
@techdose4u
2 жыл бұрын
Welcome 😀
amazing , smooth
Thank you for such a great explanation
@techdose4u
2 жыл бұрын
Welcome 😀
What an amazing explanation!🤩 Hats off to you🙌🏻
@techdose4u
3 жыл бұрын
Thanks :)
@taukirkhatri3368
3 жыл бұрын
I don't know why your channel is not getting a proper growth!!! Such an amazing series of videos. But no one is sharing your content.
@taukirkhatri3368
3 жыл бұрын
Do you have an account on Instagram? You can promote it there. I will also share your videos on my profile. I know I don't have much followers but 'something is better than nothing' Right?
@taukirkhatri3368
3 жыл бұрын
And also can you show your profiles of Codechef or CodeForces or other coding platforms on which you are doing Competitive Programming in upcoming video? Because all the people are interested in numbers only. So it will help you to grow up your channel 🤟🏻
excellent
very well, oh wait , Awesome explanation
I'm the 250th like. you deserve more keep it up
@techdose4u
3 жыл бұрын
Thanks :)
thank u sir
thanks sir
Thanks
Great teaching!
@techdose4u
2 жыл бұрын
Thanks 😊
No words for you , only I want to say ......................You are Diamond .......................
@techdose4u
3 жыл бұрын
Thanks :)
I think in the else part of the addNum function, we don't have to write that many conditions, as we know that the maxheap size is 1 greater than minheap size, hence we must insert the element such that after the insertion maxheap.size() will be same as minheap.size(). So here we just have to check whehter num is less than or equal (
@manishkumaryadav4303
Жыл бұрын
we can make it even shorter.... . void addNum(int num) { int l=maxh.size(),r=minh.size(); if(l==r) maxh.push(num); else minh.push(num); if(r!=0) { if(maxh.top()>minh.top()) { int a=maxh.top(),b=minh.top(); maxh.pop(); minh.pop(); maxh.push(b); minh.push(a); } } }
Thank you for helping out so much, please do sql also
@techdose4u
3 жыл бұрын
Let's see after DSA course.
Thank you so much.
@techdose4u
2 жыл бұрын
Welcome
nice explanation bro keep the work going
@techdose4u
3 жыл бұрын
Thanks
Sir please do a video on this problem: Median of Two Sorted arrays
Why can't we use binary search to insert? It will also work with same nlogn complexity, right?
can we use quick select algorithm for findinding mid or kth element in unordered array
@techdose4u
3 жыл бұрын
You can. But still it will be too expensive and doesn't go well with stream.
Good explenation
@techdose4u
3 жыл бұрын
Thanks
could code own my own after the explanation. you explain really well
@techdose4u
3 жыл бұрын
🔥
Hi,thanks, i liked your explanation @17:00
@techdose4u
2 жыл бұрын
Thanks :)
Nice explanation
@techdose4u
3 жыл бұрын
Thanks
supeeeeeeerb
Isn't nlogn the same time complexity keeping a vector, and then sorting it at time of calculating median? wouldn't it be easier and equivalent in time complexity? also how is it possible to have maxHeap size >1 and minheap size >0, i thought your goal was to keep maxHeap greater by 1 or equal to min heap size? therefore you cannot push directly to minHeap for this scenario?
@HARSHITKUMAR-wj4ex
3 жыл бұрын
no that would be n^2logn time because in that case you would be sorting n time n numbers and that would be n*(nlogn)
Nice❣️
@techdose4u
3 жыл бұрын
:)
We can simply use binary search for each element for insertion right?? like bisect. Correct me if I am wrong / missing out something.
@harryscorner7135
2 жыл бұрын
Thank you for this Amazing Video Sir
Beautiful question and superb explanation ❤
@techdose4u
3 жыл бұрын
Thanks :)
Why, quick sort algorithm is not used (at the position of insertion sort)
We can directly use the underlying vector used for min heap. Since we know the heap size, we can fetch the middle element(s) in O(1). Can you please suggest what's the issue with this approach?
It took 3.01seconds for me. Not sure if I wrote a good code. Did it take the same time for you also? or even less?
Hi Surya, May I ask How to answer before follow ups for this question? If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution? If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
@techdose4u
3 жыл бұрын
Let me check the follow ups. Dint see that to be honest.
@sarthuaksharma9609
3 жыл бұрын
Bucket sort is one way for small range questions. Keep 100 buckets for all the values for the second follow up keep 101 buckets one extra bucket for all the values greater than 100 keep them sorted as they are just 1% sorting them won't be costly. Read about bucket sort and try to apply here you will get the intuition.
Can we use multiset here
in case of else condition you have made an extra check by checking if size of min heap == 0 and then followed by condition I think that is extra not required to do that and also it is confusing
what if we use avl tree??
Hey , we can use multiset as well
@techdose4u
3 жыл бұрын
I dint try that. You can try once :)
Does practice is a only solution to get the solution of such problems? It is very hard to guess the best solution of such problems without getting hints.
@techdose4u
3 жыл бұрын
Practice obviously helps. But there are other factors like how well you understand a problem statement and how much you enjoy doing this as well as guidance.
Just a feedback that, In the last else condition, we don't need so many conditions
Sir I like your face Cam. 😍 But It would be great, if increase size of your face and have green screen at ur back. Thanks Sir
nice explaination sir.... but the code is too complex to understand
hum n^(2)logn approach se dil todke iha pe ata hai
Waiting for hashing and recursion ❤️
@techdose4u
3 жыл бұрын
👌🏼
love babbar has explained this better
Leetcode 480 (Sliding Window Median), please !!
@techdose4u
3 жыл бұрын
👍🏼
My according median for odd number is (n+1)/2
@techdose4u
2 жыл бұрын
👍🏼
if still anyone having problem to understand this, i'll highly recommend you to watch Keerti Purswami's video. You will definitely understand and also the code is too short compared to this one.
Question 295 has 295 likes right now lol!
@techdose4u
3 жыл бұрын
😂
I feel last condition is extra
add function can be made shorter void addNum(int num) { int l=maxh.size(),r=minh.size(); if(l==r) maxh.push(num); else minh.push(num); if(r!=0) { if(maxh.top()>minh.top()) { int a=maxh.top(),b=minh.top(); maxh.pop(); minh.pop(); maxh.push(b); minh.push(a); } } }
No need to make the third else condition that large: void addNum(int num) { int lsize = maxheap.size(); int rsize = minheap.size(); if(lsize==0){ maxheap.push(num); }else if(lsize == rsize){ int rtop = minheap.top(); if(num > rtop){ minheap.pop(); maxheap.push(rtop); minheap.push(num); }else{ maxheap.push(num); } }else{ int ltop = maxheap.top(); if(num > ltop){ minheap.push(num); }else{ maxheap.pop(); minheap.push(ltop); maxheap.push(num); } } }
you can follow this too: class MedianFinder { public: priority_queuemaxHeap; priority_queueminHeap; MedianFinder() { } void addNum(int num) { maxHeap.push(num); minHeap.push(maxHeap.top()); maxHeap.pop(); if(minHeap.size()>maxHeap.size()){ maxHeap.push(minHeap.top()); minHeap.pop(); } } double findMedian() { if(maxHeap.size()>minHeap.size()) return double(maxHeap.top()); else return (double(maxHeap.top())+ double(minHeap.top()))/2; } };
great explanation
Thanks
@techdose4u
2 жыл бұрын
Welcome :)
Thanks
@techdose4u
2 жыл бұрын
Welcome