Тёмный

Sort A K Sorted Array - Investigating Applications of Min/Max Heaps 

Back To Back SWE
Подписаться 240 тыс.
Просмотров 27 тыс.
50% 1

Free 5-Day Mini-Course: backtobackswe.com
Try Our Full Platform: backtobackswe.com/pricing
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions
Question: Write a program which takes as input a very long sequence of numbers and prints the numbers in sorted order. Each number is at most k away from its correctly sorted position. (Such an array is sometimes referred to as being k-sorted).
Pramp: www.pramp.com
Examples:
Input:
[ 3, -1, 2, 6, 4, 5 , 8 ]
k = 2
Each number is no more than 2 indices from its final sorted position.
Output:
[ -1, 2, 3, 4, 5, 6, 8 ]
It is often that data finds itself in an almost sorted state.
For example: A server needs to sort orders coming in internationally and due to differences in server loads and network routes some earlier orders come in after later orders.
How do we efficiently sort this almost sorted data?
Whenever I hear or think of sorting or searching, I think of my fast sorting algorithms, binary search, and min/max heaps.
Approach 1 (Brute Force)
Just run a quick sorting algorithm like mergesort or quicksort and have the array sorted in O( n * log(n) ) time.
This is an obvious answer.
The key insight we need to make is that most of the items are very close to their final positions and therefore we need to just “touch up” the order of the items.
How will we perform this “touch up”?
Approach 2 (Min Heap To The Rescue)
Example:
[ 3, -1, 2, 6, 4, 5, 8 ]
k = 2
How do I know who belongs at index 0?
Well, this leads me to ask you, what are the potentialities for each index? What items could be at index 0?
3 can, -1 can (if it moves 1 spot back), 2 can (if it moves 2 spots back), but 6 cannot (it would have to move 3 spots back but k = 2, this is not allowed).
Now our interest is in k + 1 items, 3, -1, and 2 each could go at index 0.
Our job is now reduced to finding the minimum of k + 1 elements at a time.
What data structure helps me with keeping track of minimums and maximums in a set of data very well?
A heap.
We will use a min heap because we want access to the smallest item across k + 1 items.
The Algorithm
Add the first k + 1 items to a min heap.
Iterate through every index in the array.
Place the min item and add the next item that has not been added yet to the heap.
When we cannot add un-added items to the heap near the end (at some point every item will have seen the heap but we will not be at the end of the iteration just yet) we can just continue ejecting and placing the min items.
Complexities
Time: O( n * log( k ) )
For all n items we will perform an insertion and removal from a min heap holding k + 1 items.
Space: O( k )
The heap will hold k + 1 numbers at maximum before an item is ejected.
++++++++++++++++++++++++++++++++++++++++++++++++++
HackerRank: / @hackerrankofficial
Tuschar Roy: / tusharroy2525
GeeksForGeeks: / @geeksforgeeksvideos
Jarvis Johnson: / vsympathyv
Success In Tech: / @successintech
++++++++++++++++++++++++++++++++++++++++++++++++++
This question is 11.3 in the book "Elements of Programming Interviews"

Наука

Опубликовано:

 

5 апр 2019

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 183   
@BackToBackSWE
@BackToBackSWE 5 лет назад
Table of Contents: The Problem Introduction 0:00 - 1:33 Why Not Just Sort It? 1:33 - 2:08 Investigating How We Can Actually Use K 2:08 - 3:22 Expressing The Exhaustive Set of Possibilities 3:22 - 5:57 Analyzing The Critical Information 5:57 - 7:17 We Begin Doing Placements 7:17 - 10:51 Time Complexity 10:51 - 12:47 Space Complexity 12:47 - 13:27 Wrap Up 13:27 - 14:05 The code for the problem is in the description. Fully commented for teaching purposes.
@mr.streetwear506
@mr.streetwear506 4 года назад
I am not that good with heap sorting plus O(Nlog(N)) time is taken . If we trade space for time, maybe it can be done in linear time. First make a new array of size maximum value of given array and then count no. of times values appear in given array and place at same index as value in new array. After that just use new array and place the value in sorted manner. idk its right or not. i m still trying,i got this question yesterday in my pramp interview.
@BackToBackSWE
@BackToBackSWE 4 года назад
hows it going with the question now
@mr.streetwear506
@mr.streetwear506 4 года назад
@@BackToBackSWE I edited little bit of my algorithm and its works fine with array which is not having large max value, but it take a little bit more time than heap sort. But I recently found about Radix sort and Count sort and they are perfect for this question . As I am a beginner , I am learning slowly slowly. And I m grateful you replied me, Thank you. Its really motivating.
@prakharpandey5250
@prakharpandey5250 5 лет назад
The way you approach a problem is exactly how the things should be taught. I wish i had find you earlier.
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks haha
@suryaajha2142
@suryaajha2142 4 года назад
@@BackToBackSWE Thanks so much you are just awesome
@prativadas4794
@prativadas4794 4 года назад
The way you explain the problems and make the viewers to think critically is amazing. 👍 Thank you
@BackToBackSWE
@BackToBackSWE 4 года назад
sure.
@venkatkrishna3774
@venkatkrishna3774 3 года назад
Just wow. This is how intuition should be explained. Subscribing now.
@mariasandru7
@mariasandru7 4 года назад
I was just reading EPI, and I have seen this problem on the Heaps section. After a few good minutes, I realised I was hopeless, so I decided to search it on youtube. I did not believe I would have much luck. You can not imagine how relieved and excited I was when I saw that YOU (my favourite person on RU-vid :)))) made a video on this exact topic.
@BackToBackSWE
@BackToBackSWE 4 года назад
glad you found us
@alban.l5096
@alban.l5096 5 лет назад
Wow I just discovered your channel, it's awesome ! Your videos are amazing ! I may not need it now but one thing is sure, I will subscribe to remember where to go when I need it
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks! I appreciate it!
@rohit1987j
@rohit1987j 2 года назад
Best explanation I found on RU-vid
@nagarjunprasad
@nagarjunprasad 5 лет назад
The way you explain stuff from a beginners perspective is really intuitive. Keep up the awesome work. Looking forward to more of your stuff!
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks yo
@harrisli8820
@harrisli8820 5 лет назад
This is awesome. You're a wonderful wonderful teacher. Clear and Concise. Please do more of these videos.
@BackToBackSWE
@BackToBackSWE 5 лет назад
ok, on it chief
@xxbighotshotxx
@xxbighotshotxx 5 лет назад
Dude, thank you so much for posting these videos. Keep it up! They give me an even deeper understanding of CS fundamentals that I hope will give me a better chance with interviews in the future. Your explanations are superb
@BackToBackSWE
@BackToBackSWE 5 лет назад
Thanks. I'll probably do this channel for 1-2 more years and see where it takes me. I hope it grows faster and goes down as one of the greatest SWE channels to ever exist. Long way away, so many more avenues to explore and teach in.
@djhacaptures
@djhacaptures 4 года назад
Discovered your channel yesterday. Great job. Love how you explain on how to approach the problem.
@BackToBackSWE
@BackToBackSWE 4 года назад
nice, welcome
@MrJulian0316
@MrJulian0316 4 года назад
Best channel I've found so far....you really made my brain absorb this challenges the right way.....keep up the great job buddy
@BackToBackSWE
@BackToBackSWE 4 года назад
thanks, will do
@QVL75
@QVL75 5 лет назад
Awesome explanation! The best I've seen on RU-vid.
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks
@reneeliu6676
@reneeliu6676 5 лет назад
Today, I died on this one at my interview...should have been here yesterday.
@BackToBackSWE
@BackToBackSWE 5 лет назад
dang
@danrussell_official
@danrussell_official 3 года назад
me too - the interview was for mostly a frontend role but the last challenge was like a backend challenge....this problem was given and i died. knowing now to use a min heap would have definitely helped! oh well we will know for next time! here's my code (js): let unsorted = [3, 2, 1, 5, 6, 4] let kSorted = (arr, k) => { let minHeap = arr.splice(0, k + 1) let sorted = [] while (arr.length || minHeap.length) { while (minHeap.length) { let min = getMin(minHeap) sorted.push(min[0]) minHeap.splice(min[1], 1) } minHeap = arr.splice(0, k + 1) } return sorted } let getMin = (arr) => { let min = [Infinity, null] for (let i = 0; i < arr.length; i++) { let curr = arr[i] if (curr < min[0]) { min[0] = curr min[1] = i } } return min } console.log(kSorted(unsorted, 2))
@shrad6611
@shrad6611 5 лет назад
worth watching, best video ever You not only give the solution of the problem but show us the path to get that approach of finding a solution
@BackToBackSWE
@BackToBackSWE 5 лет назад
yeah thanks
@rachelhalpern5168
@rachelhalpern5168 4 года назад
I just got this question on Pramp yesterday and was so stuck! Happy to have found your channel :)
@BackToBackSWE
@BackToBackSWE 4 года назад
haha I got it on Pramp too - welcome
@lakshaydutta2299
@lakshaydutta2299 5 лет назад
your concepts are really very clear ! such a nice explanation dude ! you actually made it look very easy!the best part was that you described the whole process of how to start thinking for this question ! thanks man !
@BackToBackSWE
@BackToBackSWE 5 лет назад
Hahaha I don make it look easy but all these videos are prepared and staged almost....like I'm just a normal dude haha
@farheenfirdous6530
@farheenfirdous6530 4 года назад
One of the best video i have ever seen I really wanna say thank you from bottom of my heart 💯
@BackToBackSWE
@BackToBackSWE 4 года назад
sure!
@tom0313choi
@tom0313choi 5 лет назад
Thanks for the video! Great thought process building upto the optimal solution!
@BackToBackSWE
@BackToBackSWE 5 лет назад
wassup, thanks
@SimplyaGameAholic
@SimplyaGameAholic 3 года назад
Super underrated, love your mindset to understand intuitions!
@deepti8920
@deepti8920 3 года назад
You are an awesome teacher! Keep doing great work! God bless!
@johnlabarge
@johnlabarge 5 лет назад
You are amazing. Such a great communicator. And such an awesome thing to make these videos.
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks
@aarshiarora4068
@aarshiarora4068 4 года назад
This channel is a gem
@BackToBackSWE
@BackToBackSWE 4 года назад
nah, u a gem
@24381498
@24381498 5 лет назад
Amazing video. Thanks, please keep making such kind of videos. It helped me to understand this algorithm. I was thinking about why we are taking k+1 heap but you have explained it very well. Thanks.
@BackToBackSWE
@BackToBackSWE 5 лет назад
ok
@joyrahman2008
@joyrahman2008 5 лет назад
Very nice explanation. With that explanation, implementation was very easy. Thumbs up !!
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks 🌽🚜🌽🌽
@bulbultripathy6291
@bulbultripathy6291 3 года назад
This is such a great explanation. Thank you so much!!
@ekejma
@ekejma 3 года назад
Really enjoyed this one, especially the stacking of solutions per index of the possible solution and seeing the binary heap and complexity classes for time/space.
@trustmebro703
@trustmebro703 5 лет назад
Nice walk through. Love it!
@BackToBackSWE
@BackToBackSWE 5 лет назад
sure
@anupriyasingh5407
@anupriyasingh5407 4 года назад
Thank you very much. I love the way you explain things.
@BackToBackSWE
@BackToBackSWE 4 года назад
sure
@kumarc4853
@kumarc4853 4 месяца назад
Great intuition building exercise , thank you very much
@malharjajoo7393
@malharjajoo7393 2 года назад
This is a very good way to explain the heap approach.
@BackToBackSWE
@BackToBackSWE 2 года назад
Thank you, glad you liked it 😀 Do check out backtobackswe.com/platform/content and please recommend us to your family and friends 😀
@soumavanag5025
@soumavanag5025 3 года назад
thanks buddy, awsome explanation!!
@code_yoda1928
@code_yoda1928 5 лет назад
Your videos are awesome,sir.I subscribed to your channel as soon as i listened to your way of explaining.Please keep making videos,your way of teaching is infinitely times better than my college professors
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks!
@harshitair2sahu266
@harshitair2sahu266 4 года назад
deeply explained.....good job
@BackToBackSWE
@BackToBackSWE 4 года назад
thanks.
@anish749
@anish749 4 года назад
Amazing explanation. Very good work.
@BackToBackSWE
@BackToBackSWE 4 года назад
thanks
@Aman-lo3jb
@Aman-lo3jb 5 лет назад
Thankyou for such an amazing explanation...♥️
@BackToBackSWE
@BackToBackSWE 5 лет назад
sure
@ripuvendrasingh8497
@ripuvendrasingh8497 5 лет назад
extraordinary explanation.. need more videos like this sir.
@BackToBackSWE
@BackToBackSWE 5 лет назад
coming right up
@krgaurav2011
@krgaurav2011 5 лет назад
Perfect explanation!
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks
@vishnuvardhan623
@vishnuvardhan623 5 лет назад
awesome explaination of underneath of the problem
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks
@appsicle
@appsicle 5 лет назад
This explanation was brilliant.
@BackToBackSWE
@BackToBackSWE 5 лет назад
Thanks
@varshamehra8164
@varshamehra8164 5 лет назад
your videos are very helpful . thank you brother
@BackToBackSWE
@BackToBackSWE 5 лет назад
sure
@kiordomiorjo352
@kiordomiorjo352 3 года назад
I love your videos man!
@BackToBackSWE
@BackToBackSWE 3 года назад
thx
@F1mus
@F1mus 4 года назад
Awesome explanation.
@BackToBackSWE
@BackToBackSWE 4 года назад
thanks
@shredder_plays
@shredder_plays 5 лет назад
Beautifully Explained thanks please bring some dp questions too for interview preperation
@BackToBackSWE
@BackToBackSWE 5 лет назад
Ok, I'll cover a lot here: , this is the site I'twitter.com/thebigoguidem working on
@parekshamanchanda8083
@parekshamanchanda8083 4 года назад
Great explanation, if we do this way in an interview, selection is 100%
@BackToBackSWE
@BackToBackSWE 4 года назад
ye
@abhisheksunda7925
@abhisheksunda7925 4 года назад
great explanation!!!!
@BackToBackSWE
@BackToBackSWE 4 года назад
thanks
@mzmzgreen
@mzmzgreen 5 лет назад
Thank you for your hard work on those videos. What do you think about doing an episode about dynamic programming? Explain top down and bottom up approaches, dp table method, how to approach it in general etc.
@BackToBackSWE
@BackToBackSWE 5 лет назад
I could. I feel all the dp videos already teach this though. But I could make a video to tie it all together.
@umairalvi7382
@umairalvi7382 3 года назад
Totally awesome
@warrickholfeld6274
@warrickholfeld6274 5 лет назад
Really good videos.
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks
@selvawithedu
@selvawithedu 5 лет назад
very nice explanation about the problem and solution (y)
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks
@indraxneel
@indraxneel 4 года назад
Really llove your explaination
@BackToBackSWE
@BackToBackSWE 4 года назад
thx
@user-oy4kf5wr8l
@user-oy4kf5wr8l 3 года назад
We love u buddy! we love u! every buddy love you!
@ianchui
@ianchui 4 года назад
LOL, I liked your final words, very casual :p
@BackToBackSWE
@BackToBackSWE 4 года назад
yoyo
@vivekpratapsingh6189
@vivekpratapsingh6189 5 лет назад
Top class explanation
@BackToBackSWE
@BackToBackSWE 5 лет назад
thanks
@hamdyahmed1984
@hamdyahmed1984 4 года назад
Smart Idea, thank you (Y)
@BackToBackSWE
@BackToBackSWE 4 года назад
sure
@ayounghosh9218
@ayounghosh9218 4 года назад
this was good
@BackToBackSWE
@BackToBackSWE 4 года назад
thanks
@marlegagaming1274
@marlegagaming1274 5 лет назад
Thankyou Sir
@BackToBackSWE
@BackToBackSWE 5 лет назад
sure
@RahulSharma1
@RahulSharma1 3 года назад
Awesome explanation! I wonder when the k == n.length, it is best to just run a quick sort and save some space? Since quicksort will be in-place (or in worst case O(log n) space as the time complexity will be same as the heap sort.
@BackToBackSWE
@BackToBackSWE 3 года назад
Yeah I think? I'm fuzzy on this problem's description, solutions, etc. but yeah one can do internal optimization like that. The worst case will still rule though.
@yusrahaider2520
@yusrahaider2520 4 года назад
Thank you for making this video! Could you please 'prove' that this would work for any general input?
@BackToBackSWE
@BackToBackSWE 4 года назад
yeah I could do a proof but not worth a full video ya know?
@shrad6611
@shrad6611 5 лет назад
You are even better than the geeks for geeks. If I got a job I will definitely donate you my guru Dakshina (my money) By the Way I am from India lol
@BackToBackSWE
@BackToBackSWE 5 лет назад
hahahaha nice, wassup, one world
@animusdx
@animusdx 5 лет назад
I actually got this problem as my problem for my Twitch Technical phone interview which I messed up really badly. I came up with a brute force solution but I ran out of time before I could really optimize it. But then again a heap never came to mind when I was thinking through it.
@BackToBackSWE
@BackToBackSWE 5 лет назад
Yeah, it happens. Speaking of coincidences, we got a practice exam for my (actual) algorithms exam that is happening tomorrow and this same question was on the practice exam. I didn't even mean for that to happen. Wild
@utsavprabhakar2205
@utsavprabhakar2205 5 лет назад
Hey man. Awesome video. probably the best placement-prep channel on youtube. like when you made that diagram, before you mentioned heap, heap popped into my mind and i paused the video and came up with the solution. initially when i saw the problem, i had no clue how this was going to happen. Anyway I have a major doubt tho. Where can I learn the analysis of time and space complexities for all kinds of loops, recursion,divide conquer etc.
@BackToBackSWE
@BackToBackSWE 5 лет назад
haha nice! That is so cool. And for time complexities... :) I'm making this twitter.com/thebigoguide, it'll be out the end of July. It's why I've been so quiet for so long on the channel
@keemkorn
@keemkorn 4 года назад
Great video Ben, but I had one question. Ultimately, the time complexity comes out to be O(n log(k)) using heaps, but if we were to just opt with sorting the array as is, with merge sort for example, we would get O(n log(n)). How exactly is it, that just outright sorting the array would prove to be significantly worse than the solution you posed? Is it just in the case when N grows exponentially larger? As I would assume that K would just remain constant(relative to a specific problem i.e. k=3, k=4, etc.)? Thanks, bru.
@BackToBackSWE
@BackToBackSWE 4 года назад
It may not be significantly worse asymptotically since the 2 bounds are very similar (a linear factor multiplied by a logarithmic factor). It'd be interesting to see the graphs of work on random sets of calls with exponentially large n and k. The tail behaviour would look pretty similar, but this is like comparing y = 100n to y = n, the first function is objectively slower...but it is linear...both are linear. Just because both bound and will have the same shape of graph, doesn't mean that one may not be much much faster with large inputs. Asymptotic measures look at graph behaviour (think of shape) and nothing concrete.
@codecode4129
@codecode4129 4 года назад
super bro
@BackToBackSWE
@BackToBackSWE 4 года назад
thx
@SupersonicProd
@SupersonicProd 4 года назад
Ben, great videos! I have been watching tons of your videos and it has helped me a lot! I have a quick question about this problem. Will bubble sort be a good strategy here? I feel like in this particular case bubble sort will have a time complexity of O(k*n) = O(n). Please correct me if I'm wrong.
@BackToBackSWE
@BackToBackSWE 4 года назад
thanks and how O(k*n)
@SupersonicProd
@SupersonicProd 4 года назад
@@BackToBackSWE In this case, to sort this array we would have to traverse it at most k times with bubble sort. I haven't actually worked it out so I may be wrong.
@BackToBackSWE
@BackToBackSWE 4 года назад
@@SupersonicProd Isn't bubble sort quadratic? I may be missing something
@StewartW12
@StewartW12 4 года назад
Next time can you make sure your biceps aren't blocking view of the board. Thanks. For real though, this is an awesome explanation of the problem, and how to arrive at the solution. Most of these channels skip the thought process behind solving the question, and it's that type of critical thinking that will help people in their interview - not just memorizing algorithms. Thanks mate, keep up the good stuff!
@BackToBackSWE
@BackToBackSWE 4 года назад
Sure ha
@JanacMeena
@JanacMeena 3 года назад
How did you record your voice during this video? Lavalier? Boom mic? The quality is great.
@stephyjacob1256
@stephyjacob1256 5 лет назад
Can please make videos mainly on backtracking, greedy, dynamic programming .. it will helpful ..because most people find those problem difficult to solve. Thanks
@BackToBackSWE
@BackToBackSWE 5 лет назад
yeah
@lilzjay9732
@lilzjay9732 5 лет назад
thumb up before watching
@BackToBackSWE
@BackToBackSWE 5 лет назад
haha
@fateme_s_slmi4708
@fateme_s_slmi4708 3 года назад
بارک الله شعبون کد خدا بارک الله
@johnenyeart4702
@johnenyeart4702 3 года назад
What are some examples of when you would use this algorithm in real life? I can't think of what sort of situation you would have where you would be given a k-sorted array to begin with or how that k-sorted array would be generated in the first place. Any ideas?
@sauravdas7591
@sauravdas7591 4 года назад
I understand that its almost sorted and hence using the Heap Sort. Since it's no ,can't we try Counting sort? It will be O(n+k) faster than the approach?
@BackToBackSWE
@BackToBackSWE 4 года назад
I'm not sure
@ravitanwar9537
@ravitanwar9537 5 лет назад
hey bro i'm here from your solutions on leetcode(minimum window susbstring):- even though approach of your videos is good i think company wise questions approach would be better . for eg :- take all uber questions , then amazon etc . this covers the most asked ones and all the common interview questions irrespective of the company . hope i made sense . cheers .!
@BackToBackSWE
@BackToBackSWE 5 лет назад
Yes, this is something I pondered when I started this channel. How would I format things. The thing is...I didn't think that that would be a good choice...to revolve a whole channel and movement around company specific questions....although it does align with the mission of the project (to get people jobs)...I just don't think it'd be a good idea to pander to the idea that companies ask a certain set of questions (although some DO do that) as a long-term content strategy. It'd certainly get the channel WAY more views and give it a viral aspect but... What if a company stops asking a question? What if they stop using these kinds of questions all together? A more stable idea in my belief is to revolve the channel around classes of problem and the fundamentals that guide each problem class. I think anyone can look up the company lists and then do those problems and then...yeah I may just be straight wrong but eh...
@8Trails50
@8Trails50 5 лет назад
Back To Back SWE i think your approach is the correct here. Fundamentals > any specific problem set Uber might have asked.
@johnenyeart4702
@johnenyeart4702 3 года назад
There is no guarantee that Amazon asks X, Google asks Y, etc. Interviewers at these companies are allowed to choose whatever question they want to ask, so it is possible (or even probable) that you could get a Facebook question at Google, a Palantir question at AirBNB, etc.
@vaishnavikulkarni8104
@vaishnavikulkarni8104 3 года назад
Hey ben, your approach fails for this example 4 3 1 2 5 with k=2 Any thoughts? Liked your approach BTW
@BackToBackSWE
@BackToBackSWE 3 года назад
Isn't that '4' 3 positions away from it's final sorted position?
@bestsports5278
@bestsports5278 5 лет назад
Just a thought..Can we do it in using DEQUEUE instead of Min Heap..? we maintain the smallest element the queue for every k+1 window...
@bestsports5278
@bestsports5278 5 лет назад
using DQUEUE it will be O(N)
@BackToBackSWE
@BackToBackSWE 5 лет назад
I sort of know what you are saying. Why a dequeue? Even if we maintain the smallest element, how are you cognizant of its position in the underlying structure for removal at all times? Elaborate a little and analyze each operation, I'm interested.
@xxbighotshotxx
@xxbighotshotxx 5 лет назад
@@BackToBackSWE I don't believe a sliding window will work here. This is because we need to always maintain the ordering of the elements to get the smallest value every time
@bob_jones
@bob_jones 5 лет назад
I was reviewing the code you put in the description. It makes sense for the most part, but why did you make it such that the min heap has k + 1 elements at any time instead of just k elements?
@BackToBackSWE
@BackToBackSWE 5 лет назад
Because for the first position (and next positions onward) we compete k+1 elements. It is easiest if you look at the video and see concretely why.
@bob_jones
@bob_jones 5 лет назад
@@BackToBackSWE I watched the video before the comment. I think I got it since I have had a night's sleep. I think it is because we include the first element plus the k elements to the right.
@BackToBackSWE
@BackToBackSWE 5 лет назад
@@bob_jones yeah
@MithileshDSCS
@MithileshDSCS 3 года назад
4:44 good stuff XD
@user-kw3vv6gy3y
@user-kw3vv6gy3y 3 года назад
build a heap with k elements takes O(k) time so the time complexity is O(n*log(k) + k) == O(n*log(k))?
@BackToBackSWE
@BackToBackSWE 3 года назад
building a heap with k elements is log(k) per insertion (if we hold k items at max in heap) over k items so Θ(k*logk).
@ganeshreddy8521
@ganeshreddy8521 4 года назад
Wow
@BackToBackSWE
@BackToBackSWE 4 года назад
thx
@mariasandru7
@mariasandru7 4 года назад
Silly question but what is the difference between this and the heap sort? Just the space complexity?
@BackToBackSWE
@BackToBackSWE 4 года назад
No question is silly, the only similarity is the data structure used to sort. If k=n then yes, this is basically heapsort where all items enter the heap and are placed out. But heapsort only uses the sift up subroutine in the initial build heap phase before the placement phase, and it only sifts up the first n/2 items one by one.
@booanger
@booanger 2 года назад
if k value is unknown is there a way to find k value faster than O(nlgn)
@KishoreKumar-pf8ku
@KishoreKumar-pf8ku 3 года назад
There is a better way actually, build heap for first k+1 elements which takes O(k) time, and then do the operations for the remaining elements which would take O((n-k)(logk)), the total time complexity would be O(k+(n-k)logk) which is better than O(nlogk)
@anuradhadesai1573
@anuradhadesai1573 4 года назад
Hi ..In your code for (int i = 0; i < k && i < n; i++) { minHeap.add(arr[i]); } shouldn't this be ----- i < K+1 ?
@BackToBackSWE
@BackToBackSWE 4 года назад
I'm not sure, I wrote it a while back
@zdanodron
@zdanodron 5 лет назад
This is actually the solution to a slightly different interview problem: k-left sorted array where elements cannot move left more than k positions. In you case the restriction is on both directions so it’s more complicated and your solution doesn’t work. Imagine the first element in your array is the biggest (10). It’ll stay in the min heap all the way to the end and will end up as the last one in the final array so it’d move more thank k=3 positions to the right
@BackToBackSWE
@BackToBackSWE 5 лет назад
"Imagine the first element in your array is the biggest (10)". In the video example the first element cannot 10. The only possible positions that 10 can end up if in a final sorted arrangement (as in the video example): k = 3 arr = [ 6, 5, 3, 2, 8, 10, 9 ] are [ x, x, 10, x, x, x, x ] (3 to left) [ x, x, x, 10, x, x, x ] (2 to left) [ x, x, x, x, 10, x, x ] (1 to left) [ x, x, x, x, x, 10, x ] (0 change) [ x, x, x, x, x, x, 10 ] (1 to right) "It’ll stay in the min heap all the way to the end and will end up as the last one in the final array so it’d move more thank k=3 positions to the right". k cannot be 3 if the 10 is in first position (index 0). What am I missing? I am confident that this is correct, but I may be wrong. - Ben
@zdanodron
@zdanodron 5 лет назад
Back To Back SWE I mean try the following input: K = 3 Arr = [10, 6, 5, 3, 2, 8, 9] 10 shouldn’t move past 4th position
@BackToBackSWE
@BackToBackSWE 5 лет назад
@@zdanodron Yes, that input is invalid is what I mean. 10 can't be there or else it breaks the problem description since it will be 6 positions from its "final resting place". Does that make sense? It does not conform to the fundamental problem description that allows the approach to work in the first place. The heap approach SHOULDN'T work for that input because of the very nature of it. It breaks our fundamental assumption about the possibilities at any one index. (the elimination we do in the video)
@zdanodron
@zdanodron 5 лет назад
Back To Back SWE Fair enough. After reading the problem description again, I find you are correct indeed. I’ve got confused because once I was asked a similar question to produce a K -sorted array for an arbitrary input
@BackToBackSWE
@BackToBackSWE 5 лет назад
@@zdanodron No problem, it is no biggie. Glad I cleared it up, I got worried for a second 😅 Keep asking great questions, I'm happy you are challenging things. Continue. It is the sign of a great learner to challenge what they know and make these connections.
@johnlabarge
@johnlabarge 5 лет назад
With a small enough K probably worth just doing a straight linear minimum.
@BackToBackSWE
@BackToBackSWE 5 лет назад
What is a straight linear minimum?
@annajoen6923
@annajoen6923 4 года назад
where is the code for it ?
@BackToBackSWE
@BackToBackSWE 4 года назад
The repository is deprecated - we only maintain backtobackswe.com now.
@johnlabarge
@johnlabarge 5 лет назад
Bro you been working out?
@BackToBackSWE
@BackToBackSWE 5 лет назад
yeah, I've weakened though
@SergioBilello
@SergioBilello 4 года назад
where is the code?
@BackToBackSWE
@BackToBackSWE 4 года назад
The repository is deprecated - we only maintain backtobackswe.com now.
@abhashjha9725
@abhashjha9725 4 года назад
For anyone looking for a code implementation can look at the link below. Hope this helps. I took this video as a reference for the code and also commented where it was required. pastebin.com/2xRuGeAi
@BackToBackSWE
@BackToBackSWE 4 года назад
nice!
@abhashjha9725
@abhashjha9725 4 года назад
Thanks man :)
Далее
If Barbie came to life! 💝
00:37
Просмотров 14 млн
Sorting Algorithms Explained Visually
9:01
Просмотров 527 тыс.
I've been using Redis wrong this whole time...
20:53
Просмотров 349 тыс.
when foldable cellphones follow the trend#shorts
0:11
Просмотров 641 тыс.