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

  • @atishaysrivastava7772
    @atishaysrivastava77723 жыл бұрын

    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

    @techdose4u

    3 жыл бұрын

    Woww ❤️ congratulations 🎉

  • @hardikagarwal7652

    @hardikagarwal7652

    3 жыл бұрын

    Bhai kaise mili intuit m intern?

  • @jettdexter6719

    @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

    @CodeSuccessChronicle

    2 жыл бұрын

    @@jettdexter6719 try forget password dude

  • @pranav288

    @pranav288

    Жыл бұрын

    @@CodeSuccessChronicle it's a bot

  • @ashishkumarchoubey5592
    @ashishkumarchoubey55922 жыл бұрын

    For the first time in almost 6 months finally we see a face behind the voice that has been guiding me in coding.

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    😅

  • @ashishkumarchoubey5592

    @ashishkumarchoubey5592

    2 жыл бұрын

    @@techdose4u Saying hello from Asansol, your neighbouring city

  • @aryanmaniyar7301
    @aryanmaniyar73018 ай бұрын

    Great video, and great questions as well during the switch from brute to optimal! Loved it, thanks :)

  • @munishgarg75
    @munishgarg752 жыл бұрын

    You are really doing an awesome job sir. May God bless you!!!!

  • @aadityasharma6855
    @aadityasharma6855 Жыл бұрын

    Really amazing explaination, hands down one of the best dsa teacher on yt.

  • @minhthuan4479
    @minhthuan44792 жыл бұрын

    2 days to complete this course. Thank you for your valuable lesson.

  • @ravipatel3624
    @ravipatel36243 жыл бұрын

    Best Explanation. Hats off you.

  • @pepetikesavasiddhardha7852
    @pepetikesavasiddhardha7852 Жыл бұрын

    Thanks for the wonderful explination

  • @VijaySharma-qb2rl
    @VijaySharma-qb2rl2 жыл бұрын

    This channel deserves 1M subs!

  • @twi4458
    @twi4458 Жыл бұрын

    Best Explaination on youtube!

  • @paragroy5359
    @paragroy53592 жыл бұрын

    Nice explanation sir...thanks a lot for the video

  • @Mr_SSK
    @Mr_SSK Жыл бұрын

    *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

    @anu8928

    7 ай бұрын

    Very Nicely explained!! 🙏🏼

  • @AR-scorp
    @AR-scorp2 жыл бұрын

    Awesome. Just when you said devide them jnto 2 halve, immediately it became easier.

  • @aakashparmar560
    @aakashparmar5602 жыл бұрын

    Great Explanation.!

  • @prakharagarwal6237
    @prakharagarwal62373 жыл бұрын

    Thanks! Keep up the good work!😃

  • @abhisheksrivastav9152
    @abhisheksrivastav915211 ай бұрын

    Thank you for this nice explanation. I visited different sites to solve this question. Your solution is very simple and efficient to understand.

  • @nguyenthong3096
    @nguyenthong30969 ай бұрын

    You're my hero man.

  • @lalit2926
    @lalit2926 Жыл бұрын

    For the first time, I came to know about real life use of insertion sort.. Thank you Sir !! Great explaintion...

  • @techdose4u

    @techdose4u

    Жыл бұрын

    Welcome :)

  • @NatureLover-oq6uc
    @NatureLover-oq6uc Жыл бұрын

    Mujhe nhi lagta KZread pe Striver aur TechDose se jyada achaa coding ke liye koi channel h........YOU ARE THE GEM❤

  • @chetnaraghav9979
    @chetnaraghav99792 жыл бұрын

    great explanation

  • @theghostwhowalk
    @theghostwhowalk3 жыл бұрын

    Great explanation to this hard problem. Lot of companies ask this one.

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Yea. It's very important :)

  • @dhruvkaran9724

    @dhruvkaran9724

    2 жыл бұрын

    @@techdose4u amazon asked me this and i was totally clueless now i know y i was clueless

  • @Rahul-rp5hk
    @Rahul-rp5hk3 жыл бұрын

    Amazing explanation! It would have helped even more if you could discuss the follow up in the question as well!

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Hmmm....I somehow missed the follow-up I guess :O

  • @Eng.RajniPaneru
    @Eng.RajniPaneru2 жыл бұрын

    thanks for your explanation, sir this is really good .

  • @anikkhan8811
    @anikkhan88113 жыл бұрын

    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

    @techdose4u

    3 жыл бұрын

    Sure bro :)

  • @alperkaya8919
    @alperkaya8919 Жыл бұрын

    perfect Explanation

  • @sejalrai30
    @sejalrai30 Жыл бұрын

    very nice sir thank you so much

  • @ashishlalwani582
    @ashishlalwani5823 жыл бұрын

    the best solution ever !!

  • @nipunaggarwal7568
    @nipunaggarwal75683 жыл бұрын

    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

    @techdose4u

    3 жыл бұрын

    Thanks. Sure

  • @ismail8973
    @ismail89733 жыл бұрын

    Watched the entire heap series. can i hope for more series like this

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Yes

  • @shankhadeepbanerjee4980
    @shankhadeepbanerjee49803 жыл бұрын

    great explaination

  • @HarendraKumar-hl8nh
    @HarendraKumar-hl8nh2 жыл бұрын

    What a beautiful explanation !❤️ Thank you Bhaiya again...

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    Welcome 😀

  • @shubhamdeshmukh9287
    @shubhamdeshmukh92872 жыл бұрын

    amazing , smooth

  • @pujabhardwaj7569
    @pujabhardwaj75692 жыл бұрын

    Thank you for such a great explanation

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    Welcome 😀

  • @taukirkhatri3368
    @taukirkhatri33683 жыл бұрын

    What an amazing explanation!🤩 Hats off to you🙌🏻

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Thanks :)

  • @taukirkhatri3368

    @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

    @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

    @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 🤟🏻

  • @bhargav8263
    @bhargav82632 жыл бұрын

    excellent

  • @shubhamdeshmukh9287
    @shubhamdeshmukh92872 жыл бұрын

    very well, oh wait , Awesome explanation

  • @tushargupta5805
    @tushargupta58053 жыл бұрын

    I'm the 250th like. you deserve more keep it up

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Thanks :)

  • @11shivamAhir00
    @11shivamAhir002 жыл бұрын

    thank u sir

  • @hakeeminfosec
    @hakeeminfosec Жыл бұрын

    thanks sir

  • @hemantvardani1436
    @hemantvardani14362 жыл бұрын

    Thanks

  • @ZhixueYuan1989
    @ZhixueYuan19892 жыл бұрын

    Great teaching!

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    Thanks 😊

  • @DeepakKumar-yc9hr
    @DeepakKumar-yc9hr3 жыл бұрын

    No words for you , only I want to say ......................You are Diamond .......................

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Thanks :)

  • @gandhijainamgunvantkumar6783
    @gandhijainamgunvantkumar67832 жыл бұрын

    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

    @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); } } }

  • @SurajKumar-vo9jf
    @SurajKumar-vo9jf3 жыл бұрын

    Thank you for helping out so much, please do sql also

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Let's see after DSA course.

  • @harshalgarg1149
    @harshalgarg11492 жыл бұрын

    Thank you so much.

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    Welcome

  • @devashishvyas9608
    @devashishvyas96083 жыл бұрын

    nice explanation bro keep the work going

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Thanks

  • @poojitharavuri2943
    @poojitharavuri29433 жыл бұрын

    Sir please do a video on this problem: Median of Two Sorted arrays

  • @vaishnavichilukuri2214
    @vaishnavichilukuri22142 жыл бұрын

    Why can't we use binary search to insert? It will also work with same nlogn complexity, right?

  • @amangupta0229
    @amangupta02293 жыл бұрын

    can we use quick select algorithm for findinding mid or kth element in unordered array

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    You can. But still it will be too expensive and doesn't go well with stream.

  • @tirthjayswal9895
    @tirthjayswal98953 жыл бұрын

    Good explenation

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Thanks

  • @Rajat-Sharma1
    @Rajat-Sharma13 жыл бұрын

    could code own my own after the explanation. you explain really well

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    🔥

  • @PrashantKumar-gg5qd
    @PrashantKumar-gg5qd2 жыл бұрын

    Hi,thanks, i liked your explanation @17:00

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    Thanks :)

  • @anuragagnihotri5238
    @anuragagnihotri52383 жыл бұрын

    Nice explanation

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Thanks

  • @dhruvkaran9724
    @dhruvkaran97242 жыл бұрын

    supeeeeeeerb

  • @danielmcgee2447
    @danielmcgee24473 жыл бұрын

    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

    @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)

  • @PRANAVMAPPOLI
    @PRANAVMAPPOLI3 жыл бұрын

    Nice❣️

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    :)

  • @harryscorner7135
    @harryscorner71352 жыл бұрын

    We can simply use binary search for each element for insertion right?? like bisect. Correct me if I am wrong / missing out something.

  • @harryscorner7135

    @harryscorner7135

    2 жыл бұрын

    Thank you for this Amazing Video Sir

  • @SugamMaheshwari
    @SugamMaheshwari3 жыл бұрын

    Beautiful question and superb explanation ❤

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    Thanks :)

  • @devyeag3096
    @devyeag30962 жыл бұрын

    Why, quick sort algorithm is not used (at the position of insertion sort)

  • @bestsaurabh
    @bestsaurabh3 жыл бұрын

    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?

  • @PhenomenalInitiations
    @PhenomenalInitiations3 жыл бұрын

    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?

  • @yitingg7942
    @yitingg79423 жыл бұрын

    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

    @techdose4u

    3 жыл бұрын

    Let me check the follow ups. Dint see that to be honest.

  • @sarthuaksharma9609

    @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.

  • @akshatshah6413
    @akshatshah64132 жыл бұрын

    Can we use multiset here

  • @tanveer.shaikh
    @tanveer.shaikh2 жыл бұрын

    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

  • @jheelgala6353
    @jheelgala6353 Жыл бұрын

    what if we use avl tree??

  • @manavjain2078
    @manavjain20783 жыл бұрын

    Hey , we can use multiset as well

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    I dint try that. You can try once :)

  • @mwshubham
    @mwshubham3 жыл бұрын

    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

    @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.

  • @salbyrones3075
    @salbyrones3075 Жыл бұрын

    Just a feedback that, In the last else condition, we don't need so many conditions

  • @vanshsindhu8559
    @vanshsindhu85593 жыл бұрын

    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

  • @somurauniyar2610
    @somurauniyar26102 жыл бұрын

    nice explaination sir.... but the code is too complex to understand

  • @sayantaniguha8519
    @sayantaniguha85192 жыл бұрын

    hum n^(2)logn approach se dil todke iha pe ata hai

  • @jagadeeshp2558
    @jagadeeshp25583 жыл бұрын

    Waiting for hashing and recursion ❤️

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    👌🏼

  • @acxd
    @acxd Жыл бұрын

    love babbar has explained this better

  • @santanudutta3809
    @santanudutta38093 жыл бұрын

    Leetcode 480 (Sliding Window Median), please !!

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    👍🏼

  • @sunilkumawat8787
    @sunilkumawat87872 жыл бұрын

    My according median for odd number is (n+1)/2

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    👍🏼

  • @amansiddiqui3218
    @amansiddiqui32182 жыл бұрын

    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.

  • @Sambob006
    @Sambob0063 жыл бұрын

    Question 295 has 295 likes right now lol!

  • @techdose4u

    @techdose4u

    3 жыл бұрын

    😂

  • @tanveer.shaikh
    @tanveer.shaikh2 жыл бұрын

    I feel last condition is extra

  • @manishkumaryadav4303
    @manishkumaryadav4303 Жыл бұрын

    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); } } }

  • @soumyachaudhary2468
    @soumyachaudhary2468 Жыл бұрын

    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); } } }

  • @rishisahoo2772
    @rishisahoo2772 Жыл бұрын

    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; } };

  • @pritishpattnaik4674
    @pritishpattnaik46743 жыл бұрын

    great explanation

  • @megm9963
    @megm99632 жыл бұрын

    Thanks

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    Welcome :)

  • @ai7560
    @ai75602 жыл бұрын

    Thanks

  • @techdose4u

    @techdose4u

    2 жыл бұрын

    Welcome