video_id
stringlengths
11
11
content
stringlengths
0
123k
datetime
stringlengths
19
19
leetcode_number
int64
1
2k
thumbnail
stringlengths
48
151
title
stringlengths
9
106
VcBy0s5q2kk
Hi guys, welcome to the channel, you are doing 90 days software 90 days software engineering prep with me, this is question number six, lead engineering prep with me, this is question number six, lead code is the overall question of 75, lead code is 151 question, code is the overall question of 75, lead code is 151 question, reverse words in a string, okay so reverse words in a string, okay so what is the question, let me show you. what is the question, let me show you. what is the question, let me show you. string, The Sky is Blue, you have to create it, Blue is Kaida, you have to do it in Offcourse O, you have to do it in Offcourse O and you do n't have to take extra space, okay, there are some cases like Hello World, there is space at the beginning and the And And And a good two space bar example is to a good two space bar example is to make a single space bar out of two space bars, make a single space bar out of two space bars, then there can be a space in the middle, there can be then there can be a space in the middle, there can be extra space at the beginning and at the end, the rest is a extra space at the beginning and at the end, the rest is a simple question, okay, so simple question, okay, so what did I do? what did I do? what did I do? take a case in which there are some spaces in the beginning, so I will denote the spaces with dots so that it can be seen, then dot dot the dot dot sky, one dot is blue, two dots are like this, okay, so I have given it to us as If you want to make 'The' then see this is If you want to make 'The' then see this is If you want to make 'The' then see this is found in the string, I have found in the string, I have trimmed the string, there is trim function, it will trimmed the string, there is trim function, it will blow away the space in front and back, so blow away the space in front and back, so by trimming, you know what has become 'The dot, dot, by trimming, you know what has become 'The dot, dot, sky, dot' is good, here also there was a dot, sky, dot' is good, here also there was a dot, blue. blue. blue. and the last space gets blown away. By trimming the string dot gets blown away by trimming. Then I split it on space. The split function which is what happens if I This is This is This is done, then after trimming, if I split done, then after trimming, if I split it, trimming does it, trimming does not change the original string. After not change the original string. After trimming, you get a string, then I will trimming, you get a string, then I will trim dot, split and split trim dot, split and split it on space, here I note it with dot. it on space, here I note it with dot. This dot is denoting space, I This dot is denoting space, I will trim it, so I know what will become an array will trim it, so I know what will become an array of strings, then I will get the of strings, then I will get the inside the array, then there is nothing between these two dots, inside the array, then there is nothing between these two dots, so I will not so I will not get anything, then look, look, the beginning. get anything, then look, look, the beginning. get anything, then look, look, the beginning. first dot, from the very beginning to the first dot, you got the, then from this dot, to this one, to this one, there's nothing in between, you got that, the sky between this dot to the next dot. From this dot, we will get the color between the next dot and from this we will get the blue till the last one. Okay, so you will get this array, you will get this array, what will I do now by splitting, now put a reverse loop on this array and I will take it, appended the blue, I will take it, appended the blue, I will take it, appended the blue, this is the new string string builder, this is the new string string builder, appended the blue in it, it's okay, appended the blue in it, it's okay, put the blue in the string builder, then put put the blue in the string builder, then put a space after that, put a space as per your a space after that, put a space as per your wish, wish, then for the sake of ease, added one. then for the sake of ease, added one. then for the sake of ease, added one. sky, put a space, now this one does n't have to be processed, I saw while processing a string that it doesn't have to be appended in the string builder, for that I thought whether it is MT So it does So it does So it does not have to be appended, then after inserting the 'the', I not have to be appended, then after inserting the 'the', I added a space in the last one and added a space in the last one and this became this in the string builder, now when I converted the string builder this became this in the string builder, now when I converted the string builder into a string, then my into a string, then my string is blue, the dot is sky, dot, the string is blue, the dot is sky, dot, the dot, so leave the last one. dot, so leave the last one. dot, so leave the last one. leave the last dot, you have to leave the last space, then if I leave it through the sub string function, then it becomes my string which I return, so bring it, I will do this code, the question is easy for you, so I will erase this. Look, I trimmed the front and back space, split it, got an array of words on top of the space, now I have to make a string builder, why do I have to make a string builder because appending to a string is the work of O, this string I will return I will return I will return s bud s builder dut string string s bud s builder dut string string builder by converting it into I will return. If you have to take sub builder by converting it into I will return. If you have to take sub string also then you will see that I have string also then you will see that I have put this reverse loop aa equal to put this reverse loop aa equal to words, I will start from the end of the array words, I will start from the end of the array aa g e 0 aa minus aa g e 0 aa minus aa g e 0 aa minus getting words one by one, but I will use Word of I only if the length of Word of I is greater than zero, otherwise I will not use it. I will keep appending it in the string builder. Who has words, whose name is not a word, I will keep doing this, I will keep I will keep doing this, I will keep I will keep doing this, I will keep adding one space after every word, I will keep adding one space, there will be an extra space at the end, if I have to leave it, then I will use the substring function. I will use the substring function and know myself from zero to the last. So if I put only the string builder dot length here, then I have to enter the length minus and I, then the last character will be left out, so from where we take the zero from the beginning, we will take the zero. Whatever you enter as the last index, the If it is s, then if I If it is s, then if I If it is s, then if I give the length - 1, then the last character will be left out. give the length - 1, then the last character will be left out. Okay, I think this should work and its Okay, I think this should work and its time. We write s. If we think now, then let me think about the time complexity. I will let you see first. think about the time complexity. I will let you see first. Submission is going on. Submission is going on. Submission is going on. happening fast enough? So see this trim function o split function o array of words has come, loop has been put on the words and kept on appending o if I made a mistake Now, Now, Now, if string plus is equal to two, then there will be a if string plus is equal to two, then there will be a loop of o. This is an addition to the string. loop of o. This is an addition to the string. An addition to the string is of o. An addition to the string is of o. Append in string builder is of o1, Append in string builder is of o1, so that is not a problem. In the last sub so that is not a problem. In the last sub string is o, so total leg error. string is o, so total leg error. string is o, so total leg error. n't take extra space because string miller is output space so that is okay, this was our my brothers question number 6 of lead code 75 so this is the question I have put you mean while I have put today's journal which is ours in the link. Our first link will be in the first description. You go to the journal and tell us in the comments how is your preparation going. Keep preparing along with me. There are 90 days of preparation and we are already ready. I have solved the lead code 75. I am doing it I am doing it I am doing it quickly. Dream and bud also have to be done. Alright let's quickly. Dream and bud also have to be done. Alright let's meet the meet the next question. Thank you so much. Bye bye.
2024-03-21 13:09:03
151
https://i.ytimg.com/vi/V…axresdefault.jpg
Leetcode 151 | Reverse words in a string | 6th from LC 75 | 90 days SE prep
RBlcUlUkDCU
hello everybody is a male and today I'm going to teach you how to solve the many going to teach you how to solve the many rooms to problem given an array of rooms to problem given an array of meeting time intervals consisting of meeting time intervals consisting of start and end times find the minimum start and end times find the minimum number of conference rooms required number of conference rooms required example 1 the input is this list of example 1 the input is this list of intervals so every interval has a start intervals so every interval has a start time and an end time and every interval time and an end time and every interval is a meeting so as you can see the is a meeting so as you can see the output is 2 because you need two rooms output is 2 because you need two rooms for these meetings why because we need for these meetings why because we need one room for the meeting that starts at one room for the meeting that starts at 0 and ends Authority and then we need 0 and ends Authority and then we need another room for these two meetings and another room for these two meetings and because these two meetings do not because these two meetings do not overlap we can use the same room for overlap we can use the same room for them as you can see this one starts at them as you can see this one starts at time 5 and ends at time 10 and this one time 5 and ends at time 10 and this one starts at 10:15 and ends at time 20 so starts at 10:15 and ends at time 20 so as you can see they do not overlap so as you can see they do not overlap so they can use the same room but this one they can use the same room but this one ends at times 30 so it overlaps so it ends at times 30 so it overlaps so it needs its own room example 2 the needs its own room example 2 the intervals is this list that only has one intervals is this list that only has one interval it only has one meaning so we interval it only has one meaning so we only need one room so how can we solve only need one room so how can we solve this problem we can solve this problem this problem we can solve this problem by sorting every interval by the start by sorting every interval by the start time and then we can use a data time and then we can use a data structure like a priority queue to sort structure like a priority queue to sort the end times of every interval and then the end times of every interval and then we traverse the intervals and as we we traverse the intervals and as we traverse the interval we push the end traverse the interval we push the end times to the priority queue and put push times to the priority queue and put push into a priority queue takes Big O log n into a priority queue takes Big O log n time so we push every end time to the time so we push every end time to the Prarie queue Prarie queue and we check if the start time we check and we check if the start time we check if the end time of this interval is if the end time of this interval is greater than the start time of the next greater than the start time of the next interval if that's the case they overlap interval if that's the case they overlap so we need to have a separate room but so we need to have a separate room but if that's not the case if this if the if that's not the case if this if the end time of this interval for example is end time of this interval for example is less than or equal to the start time of less than or equal to the start time of this interval then they do not overlap this interval then they do not overlap so they can have or they can use the so they can have or they can use the same room so that's the main idea here same room so that's the main idea here so the time complexity would be big-oh so the time complexity would be big-oh and log n because we have to sort by the and log n because we have to sort by the start time and the space complexity start time and the space complexity would be big-oh of n because we are would be big-oh of n because we are using a priority queue for the end times using a priority queue for the end times so without further ado I'm gonna show so without further ado I'm gonna show you how to write the code first I'm you how to write the code first I'm going to sort every interval or the list going to sort every interval or the list by the start time of every interval so by the start time of every interval so I'm gonna say collections that sort the I'm gonna say collections that sort the intervals so I will have a lambda a b8 a intervals so I will have a lambda a b8 a start start - beta start so what I'm doing here is that I'm sorting the list by the start time so all the intervals will be sorted by the start time like in this example here as you can see it is already sorted so 0 then 5 and then 15 so they're in ascending order so after I saw the intervals I need to have a priority queue of integer PQ just a file of new priority queue and in this priority queue I'm gonna have all the end times of the intervals and the priority queue will keep the minimum end time at the top so as you can see that's the main property of the priority queue you can have a minimum priority queue or an or a maximum priority queue in this case I have a minimum priority queue so every time I will have the minimum at the top so I will have access to the minimum and then I can compare the minimum end time with the start time of this interval and if they do not overlap then they can be in the same room otherwise I have to have another room for this interval and I didn't tell you this but as you can see I'm using a lambda here but I can also use I can also use a comparator I can use a comparator but I prefer to use a lambda so then what I'm going to do is that I'm going to traverse from left to right so for interval interval in and I will check every interval and if and I will check every interval and if not pick you that is empty and pick you not pick you that is empty and pick you that pick is less than or equal to interval that start then pick you that pause so if I have something in the priority queue and the minimum or the top element in the priority queue which is an end time it's less than or equal to the start time of this interval that means that they do not overlap so I can use the same room for these two intervals so what I do is that I remove the minimum end time from the Prairie queue so to indicate that I can use the same room for this interval and after I remove that minimum end time I can just say P queued up offer interval that end then I only have to worry about the end time for this new interval so every time I push the end time for the interval and the priority queue will keep those end times in the way that I need them so the minimum will be at the top then I just need to return PQ that size because by the end the priority queue will contain only the end times of the meetings that the number of end times will be equal to the number of meetings that I need as you can see I always push the end times to the Prairie queue but if I find out that the minimum of the priority queue is less than or equal to the start time of this interval I remove the end time for that I removed the end time for that interval and push the end time for this new it seems to working fine I'm gonna it seems to working fine I'm gonna submit a solution all right so this is submit a solution all right so this is working perfectly as I said before the working perfectly as I said before the time complexity is Big O n log n because time complexity is Big O n log n because of the sort the space complexity is Big of the sort the space complexity is Big O of n if you liked this video please O of n if you liked this video please press the like button don't forget to press the like button don't forget to subscribe and see you next time
2024-03-21 11:27:48
126
https://i.ytimg.com/vi_w…xresdefault.webp
Coding Interview Tutorial 126 - Meeting Rooms II [LeetCode]
iW3cGJRv_sA
hey hey everybody this is Larry this is February first day of the uh the code February first day of the uh the code daily challenge hit the like button hit daily challenge hit the like button hit the Subscribe button uh join me on the Subscribe button uh join me on Discord let me know what you think about Discord let me know what you think about today's prom and easy one and uh uh yeah today's prom and easy one and uh uh yeah if you're joining us uh look I'm I'm on if you're joining us uh look I'm I'm on the lead code contest page because the lead code contest page because there's a click for 10 Lee code I don't there's a click for 10 Lee code I don't know if that's consistent for everyone know if that's consistent for everyone let me know if you also get the coins let me know if you also get the coins but yeah but yeah um the shortest month of the year so um the shortest month of the year so definitely take this opportunity to uh definitely take this opportunity to uh get that streak going I suppose to get get that streak going I suppose to get that month streak but yeah let's see that month streak but yeah let's see what am I doing 1071 greatest common what am I doing 1071 greatest common divisor of strings divisor of strings okay so giveness t s t divides as if s okay so giveness t s t divides as if s is equal to some multiple of t uh given is equal to some multiple of t uh given the the the largest string that X such the the the largest string that X such that X divides both okay that X divides both okay and they're both a thousand so well so so yeah um I think this one is pretty straightforward in theory if you know the constraints um oh yeah and I I am going to do an uh an extra question today just you know because this is an easy one so definitely stay tuned and check out that subscribe button or whatever but yeah but this one is straightforward if you're not overthinking it or try to be too clever um the the key part is noticing that constraint is n right or n is equal to a thousand less than a thousand so then we can just prove first on on the prefix of one of them and then see if it's the other one right and that's basically the idea that I'm gonna do here I'm gonna go um the answer has to be um the answer has to be by definition a prefix or a suffix to I by definition a prefix or a suffix to I mean it doesn't really matter I mean mean it doesn't really matter I mean they're both the same they're both the same um because that's how this division um because that's how this division seems to work so basically what you're seems to work so basically what you're going to do is just take going to do is just take first some prefix first some prefix um or suffix and then see if it also um or suffix and then see if it also um quote unquote divides into the other um quote unquote divides into the other one so that's pretty much it so that we one so that's pretty much it so that we can move forwards like that and can move forwards like that and basically basically um yeah there's a thousand possible um yeah there's a thousand possible prefixes prefixes um given you know what we discussed so um given you know what we discussed so then that means that and each of them then that means that and each of them will same you know take over one will same you know take over one thousand thousand um for comparison um for comparison um linear time so it's going to be n um linear time so it's going to be n Square which for n is equal to a Square which for n is equal to a thousand is a million which should be thousand is a million which should be fast enough which is why I said fast enough which is why I said um okay so let's let's get started um okay so let's let's get started um um I mean I think you could also take the I mean I think you could also take the shorter one maybe it doesn't really shorter one maybe it doesn't really matter I mean you know in a long scheme matter I mean you know in a long scheme of things of things um yeah um yeah and then we just tick and then we just tick uh yeah maybe we can do it from one to n uh yeah maybe we can do it from one to n and then we do let's just say the and then we do let's just say the current string is equal to string one to current string is equal to string one to I I I think this is good right I'm always I think this is good right I'm always I always uh I always uh I always get confused about like I always get confused about like inclusive exclusives I always have to inclusive exclusives I always have to double check double check um okay so this is good this is um okay so this is good this is basically what we want right so then basically what we want right so then basically now we can do well I maybe we basically now we can do well I maybe we can do L for length then yeah can do L for length then yeah um um well maybe before that we go if and my L well maybe before that we go if and my L is equal to zero or if it's not equal to is equal to zero or if it's not equal to zero we continue so then we could save zero we continue so then we could save some energy comparing otherwise we do some energy comparing otherwise we do this and then this and then um say copies as you go to node by L um say copies as you go to node by L then if s times copies is you go to uh then if s times copies is you go to uh is not equal to string one then we is not equal to string one then we continue as well and then we also do the continue as well and then we also do the same thing for the other one same thing for the other one um sorry people keep ping me but yeah um maybe copies or you know let me go to M over l or something like that if s times copies it's not equal to string over two then we continue just for symmetry reasons otherwise this is good so um yeah so then we can just return l in theory but we actually did it well by we I mean me did it do it the wrong way so let's actually go counting from uh from from the bigger number up so we uh from from the bigger number up so we could just return the first time this could just return the first time this happens happens um I returned the number and instead of um I returned the number and instead of the actual string so that's a mistake the actual string so that's a mistake um I was they don't actually tell you oh I guess they don't tell you that there's no string return empty string but I guess you can say that technically maybe the empty string fits it depending how you want to Define uh it's a little bit awkward though that's why I was looking for it um though obviously I was also one but uh but yeah we can just return s and I don't know how that actually Compares without like any hours all right cool um yeah like I said this is going to be N squared this is O of N and and just um just cut both of these uh or and individually so it's gonna be N squared um yeah that's all I have for this one definitely don't complicate things if you don't have to um there probably some weird Z algorithm type thing for this one but uh yeah let you know in my comments below um that's why I have for this problem I'm gonna do an extra one after this so stay tuned uh but yeah uh stay good stay healthy to good mental health I'll see y'all later and take
2024-03-25 16:43:31
1,071
https://i.ytimg.com/vi_w…xresdefault.webp
1071. Greatest Common Divisor of Strings - Day 1/28 Leetcode February Challenge
LC8BE2XT7Pg
Hello Hi Guys Welcome To Kushwaha Set Two Numbers Part 2 In This Question Science Numbers Part 2 In This Question Science And MP Link Playlist Details * And MP Link Playlist Details * non-resident Indians Team Mostly Acid non-resident Indians Team Mostly Acid Comes First And Inch Of The Note Container Comes First And Inch Of The Note Container Single Digit 882 Numbers End Return Single Digit 882 Numbers End Return Retention Request You Majumdar Two Numbers Retention Request You Majumdar Two Numbers Two Not Two Not Two Not Number 01 Self Ok For Example Seat Haldi Number Isse 1243 Label Number 56 Or Ministry This Is Dual Sim Lutia Doob Pizza Bread 727 243 And Add Here More Than 56125 Result Of This Edition Subha No That Edition Start from behind Start from behind Start from behind certificate unit number three idiots se z certificate unit number three idiots se z page from back to front part hai page from back to front part hai ki adi add english hum elastic pim 342 ki adi add english hum elastic pim 342 323 427 and on Instagram 46546 509 vinod 323 427 and on Instagram 46546 509 vinod lekin em travels in english from starting to lekin em travels in english from starting to end not from end to end not from end to starting sudhir verification 0280 starting sudhir verification 0280 Shyamveer Will Not Get Number-1 And Husband Number-1 Modified In This Manner 1564 In This Order In Love You To And 1564 In This Order In Love You To And Subsequent Events In English Fennel But What Do We Will Do Subsequent Events In English Fennel But What Do We Will Do Subscribe Posting Subscribe Posting Story Will Be Represented In Subscribe First Day First First Will Subscribe First Day First First Will Convert Into This World Will Even Numbers Convert Into This World Will Even Numbers of List Number Two Two Two Play List Start Today Element of List in To-Do List Ek Album Ko - One End List To Take Into Coma That SDO Edison Electronic Description mein ka makhan wa jhalmal top link list one in this tags 125 left side effect simple function desist from list to states function in directions first list notes1 bhi kama stock int as one tips by reference because of making changes in distant third world Least One Is Not MP Album Not Least One Is Not MP Album Not Least One Is Not MP Album Not Equal Toe Equal Toe A Reminder Album Not Equal To Null What Will U Will A Reminder Album Not Equal To Null What Will U Will Simply Ask Value Of Album That Album Well In Tourist Will Ask Value Of Album A Well In Tourist One And Will Do Albums It's not only they can take only he also reserves It's not only they can take only he also reserves It's not only they can take only he also reserves in in parameters are not able to edit and looted parameters are not able to edit and looted and eligible to next to next return from the far away from all the and eligible to next to next return from the far away from all the limits of liquid will take another step to 232 373 element subscribe 900 Will Be Coming Back Notes Will Be Coming Back Notes Will Be Coming Back Notes And Will Forward One Corridor 1212 Thi And Will Forward One Corridor 1212 Thi Next9 800 Next9 800 E Will Start Will Produce Elements E Will Start Will Produce Elements Edition Element India News Festival Answer Solid Just Write Edition Element India News Festival Answer Solid Just Write The Function For Telling Period The Function For Telling Period Edition Of The Limits For Events 6 And Edition Of The Limits For Events 6 And Students Of Peace Students Of Peace 2000 This Given Baking 2000 This Given Baking 2000 This Given Baking E Will Declare Variables Chord Deep Mist Zero Know Where To Calculate Dism Intex Equal To Adjacent To Top That In Twice Equal To A Student Top Also Sincere Taken In Top Ten Lines About This Tagged With Spot Back Dost Value Servant Whatsup And Stood Up The Soul Will Carry Forward Them To A Novel Endurance Orissa Modulus Point Submersible To So Drishti's swift to take element toys toys time and put them into the third subscribe button subscribe and 2.5 that video.com that and int committee's two x plus carrier which has been verified from previous edition here one.com will do Ek Hai Curry And Were Ek Hai Curry And Were Ek Hai Curry And Were Greatly Reduced Poochha Answer Pooch Summit And Carries Equal Greatly Reduced Poochha Answer Pooch Summit And Carries Equal To Some David Beckham To Some David Beckham Notification More Videos Subscribe & Notification More Videos Subscribe & Share Subscribe Over Vid It Will Be Share Subscribe Over Vid It Will Be Pushed Into A Snow After Chapter 10 Country A Condition All The Present in a answer answer Present in a answer answer Present in a answer answer and present in all aspects and present in all aspects of ancestors during state will look like of ancestors during state will look like this 307 and this caffeine this 307 and this caffeine consider some incident with me to family 307 easy and office consider some incident with me to family 307 easy and office tech and answer and so content 07 2012 at tech and answer and so content 07 2012 at last last value most loud 500 verses last last value most loud 500 verses Last Position Of Stock 9059 19 These Tabs Will Last Position Of Stock 9059 19 These Tabs Will Convert Into The In To Convert Into The In To -Do List Top Model Presents A New -Do List Top Model Presents A New Window Will Lead You To Convert Into Subscribe 559 United States Will Simply Return Chief Head Teacher Will Return From These Right the Right the Right the function at least to list function with oo function at least to list function with oo tattoo list function and ignorant and art tattoo list function and ignorant and art now input start this now input start this support 250 ML list note star held between insulin tap i unil form earliest note 4 temp which unil form earliest note 4 temp which will helps in treating are newly-formed will helps in treating are newly-formed link list link list Yesterday morning last you this note mp dad festival Yesterday morning last you this note mp dad festival will intensify to take top most s.com will will intensify to take top most s.com will not when you will make new notes are not when you will make new notes are busy busy e agree with you value a great new e agree with you value a great new notification list note 4 new notification list note 4 new play list node xx play list node xx i laugh fir i laugh fir i laugh fir Chipper Additional It Means That Is Not The Dead Uniform Nod Is The Noble Vikram Head Of The Head Of Uniform Link To This Video * Note And All They Need A Temple To Temple To Held At Bhi Notification Is Difficult To Nail But He Did Not Equal To Null Shubh Else But Will Do It Will Simply Due From Next Physical To Notes That And Temples Equal To Temp Next Video MB Turn Off Held From This Function Of Three For Lips Over And Cold Not Run On Ye Kaisa Darwaza Editor Invalid List Ye Kaisa Darwaza Editor Invalid List Ye Kaisa Darwaza Editor Invalid List 4 Health Is Wealth To Internal Ok Surya Yes Return Head Tattoo Should Not Return Yes Return Head Tattoo Should Not Return Value Main Value Main Mukesh Sari Dolta Hai Mukesh Sari Dolta Hai Play List Note Star A And Listen Cheerleading Fat Knowledge Submitted On Me Chicken Cod Decade Ego By On Me Chicken Cod Decade Ego By Selective Video Teri Meri Love Selective Video Teri Meri Love Selective Video Teri Meri Love write Hindi comment section so guys please subscribe my channel and like this video
2024-03-22 12:38:29
445
https://i.ytimg.com/vi_w…xresdefault.webp
Add two numbers II Leetcode | Leetcode 445 | Leetcode november challenge
wued6gzSjI4
okay let's do today's question 270 closest the binary search tree value the closest the binary search tree value the question is given the number deputy question is given the number deputy binary search tree and the target value binary search tree and the target value we need to find the value in the binary we need to find the value in the binary search tree that is closest to the search tree that is closest to the target the dart endowed skier given target the dart endowed skier given target value is a 13-point the second target value is a 13-point the second thing is you are guaranteed to have only thing is you are guaranteed to have only one unique value in the binary search one unique value in the binary search tree that is closest to the target so tree that is closest to the target so the example here we have a binary search the example here we have a binary search tree the it's the values 2 4 2 5 1 3 tree the it's the values 2 4 2 5 1 3 if we want to find the closest value in if we want to find the closest value in the binary search tree that is close to the binary search tree that is close to that that's the closest to the target that that's the closest to the target 3.7 it's quite obvious that the root 3.7 it's quite obvious that the root node has it is the you know the answer node has it is the you know the answer it has a distance that's point to it has a distance that's point to knowing something 0.28 something that's knowing something 0.28 something that's the smallest compared to all the other the smallest compared to all the other nodes in there but this example doesn't nodes in there but this example doesn't give us a really nice idea how we give us a really nice idea how we actually go into traversal so the tree actually go into traversal so the tree so maybe we should decrement this value so maybe we should decrement this value to be like a two point seven two point to be like a two point seven two point seven so and then even though it says seven so and then even though it says three point seven just try to imagine three point seven just try to imagine we're working one example that has a we're working one example that has a target value that's two point seven way target value that's two point seven way let's see how we would do to manually let's see how we would do to manually solve this so if we're looking at the solve this so if we're looking at the root that's obviously in our entry point root that's obviously in our entry point to the tree to the tree we compared the difference between four we compared the difference between four and the two point seven we got one point and the two point seven we got one point three that's the current current closest three that's the current current closest distance and four is now as far as we distance and four is now as far as we know the closest of no value and we know the closest of no value and we should actually utilize the property of should actually utilize the property of the binary search tree to help us to go the binary search tree to help us to go and free so things and free so things number four is larger than 2.7 we should number four is larger than 2.7 we should go to explore only the lepton children's go to explore only the lepton children's because only the left of children's are because only the left of children's are the values that's a smaller than for all the values that's a smaller than for all the values to the right is larger than 4 the values to the right is larger than 4 and since 4 is larger than 2.7 all the and since 4 is larger than 2.7 all the values here to the to the right of it values here to the to the right of it it's going to have larger distance to it's going to have larger distance to the target value compared to this node the target value compared to this node value so we should the the comparative value so we should the the comparative comparison of this no value and the comparison of this no value and the target combined with the property of the target combined with the property of the binary search tree is telling us to go binary search tree is telling us to go to the left so we look at the number 2 to the left so we look at the number 2 here the distance now reduced from 1.3 here the distance now reduced from 1.3 to 0.7 and we update and have a to 0.7 and we update and have a candidate solution from 4 to 2 and candidate solution from 4 to 2 and things 2 is smaller than 2 pi 7 it's things 2 is smaller than 2 pi 7 it's telling us to go to explore the right telling us to go to explore the right Karina's of it and things know where we Karina's of it and things know where we are at the leaf node there is no more we are at the leaf node there is no more we can explore after doing the comparison can explore after doing the comparison and updates which is this one is and updates which is this one is compared to 2.7 it has a distance of 0.3 compared to 2.7 it has a distance of 0.3 which is now even smaller than the which is now even smaller than the previous one we updated the candidate previous one we updated the candidate from 2 to 3 and since 3 is a leaf node from 2 to 3 and since 3 is a leaf node we terminate the augurs and I just we terminate the augurs and I just returned that returned the candidate as returned that returned the candidate as the final solution so that's the pretty the final solution so that's the pretty much the solution in terms of a time and much the solution in terms of a time and space complexity we are exploiting only space complexity we are exploiting only one path from the root towards the leaf one path from the root towards the leaf nodes so the time complexity is little nodes so the time complexity is little the depths of the tree and for the space the depths of the tree and for the space we we would just use one pointer for the we we would just use one pointer for the traversal node and traversal node and just one variable to hold the candidate just one variable to hold the candidate value so it's constant space value so it's constant space so yeah let's cut it up or myself over so yeah let's cut it up or myself over and let's code so we will have a and let's code so we will have a traversal node which start with the root traversal node which start with the root in our entry point we have a candidate in our entry point we have a candidate value there it just starts with the value there it just starts with the nodes value and while we are still you nodes value and while we are still you know still a volume node not that's know still a volume node not that's something that you know when we are to something that you know when we are to leaf node the other children's are the leaf node the other children's are the the two children's are no pointers we the two children's are no pointers we just move that to either side we will we just move that to either side we will we will end up being a null pointer and we will end up being a null pointer and we will once we do that we will break out will once we do that we will break out of this value we should update the of this value we should update the candidate whenever we move to a new node candidate whenever we move to a new node that's the we can compare the candidate that's the we can compare the candidate with the current node value in terms of with the current node value in terms of their distance to to the target value their distance to to the target value that's distance the absolute difference and if the nodes value is smaller than the target that tells us we should go to larger than the target the only other option is that we just so the only other option is that we just so happen to find a note that is exactly happen to find a note that is exactly the same value as a target we should the same value as a target we should just return that Nevada just return that Nevada and once we break out this one loop and once we break out this one loop meaning that we at the very last meaning that we at the very last iteration we are at a leaf node and we iteration we are at a leaf node and we just do move to either side it's gonna just do move to either side it's gonna be now so we just return the candidate so that that should be the algorithm yep it's it's okay okay yeah that's a quick
2024-03-22 12:28:54
270
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode 270 Closest Binary Search Tree Value
KXp7_aoyMyk
welcome back to Cod Meets World today we're looking at Elite code problem we're looking at Elite code problem number 133 which is called clone graph number 133 which is called clone graph so given a reference of a node in a so given a reference of a node in a connected undirected graph we need to connected undirected graph we need to return a deep copy a clone of that graph return a deep copy a clone of that graph so each node in the graph contains a so each node in the graph contains a value which is an integer and then a value which is an integer and then a list of all of its neighbors I think list of all of its neighbors I think this is just telling us that it's an this is just telling us that it's an adjacency list and we need to give the adjacency list and we need to give the graph back is a CO a complete copy we graph back is a CO a complete copy we can't reference any node in the original can't reference any node in the original graph so there's this picture here where graph so there's this picture here where we see an original graph and we're not we see an original graph and we're not allowed to return the same graph so we allowed to return the same graph so we can't just recreate the graph and return can't just recreate the graph and return it we have to return a graph where all it we have to return a graph where all the nodes have their same neighbors but the nodes have their same neighbors but these are all all these blue nodes are these are all all these blue nodes are copies of the yellow nodes and this red copies of the yellow nodes and this red one doesn't work because they are one doesn't work because they are actually in a different order so I've actually in a different order so I've drawn a graph which kind of looks like a drawn a graph which kind of looks like a tree but they're one and the same and it tree but they're one and the same and it has four nodes in it and we're going to has four nodes in it and we're going to talk about how to make a deep copy of talk about how to make a deep copy of this graph what I need to do is go this graph what I need to do is go through the entire graph consider each through the entire graph consider each node and I need to put the exact right node and I need to put the exact right nodes with the exact correct Neighbors nodes with the exact correct Neighbors in a copy so the way that this graph in a copy so the way that this graph would look as an adjacency list is we would look as an adjacency list is we would have an entry in a dictionary for would have an entry in a dictionary for each of the four nodes and then we would each of the four nodes and then we would have a list of that nodes neighbors so have a list of that nodes neighbors so node one has neighbors of two and three node one has neighbors of two and three so I would write that as two and three so I would write that as two and three in the adjacency list two has only one in the adjacency list two has only one neighbor which is the one and this is a neighbor which is the one and this is a non directional graph undirected so non directional graph undirected so neighbors point to each other if that neighbors point to each other if that makes sense it's not a tree where it makes sense it's not a tree where it only Flows In One Direction three has only Flows In One Direction three has two neighbors the one and the four and two neighbors the one and the four and four just has one neighbor which is four just has one neighbor which is three so this problem is asking us given three so this problem is asking us given this adjacency list representation of this adjacency list representation of the graph we need to Traverse through it the graph we need to Traverse through it and create a copy but what we'll do and create a copy but what we'll do first is sort of just I guess a bre first is sort of just I guess a bre first search of sorts so I will have a c to put the nodes that I need to visit I'm going to have a current variable to keep track of the value that we're looking at now and then over on the right here I will draw I will write in the copy as we process everything so the way we'll start here is we'll get the root node whatever we're given to start and we will create a copy of that node by calling node with the value you and no Neighbors at the start and we'll add that as an entry in our new adjacency list which again I'll write in green no Neighbors at the start we just add that to the copy and then we need to insert the not the copy of the one the original one so the white one we need to insert that into the front of our que because that's the node that we're going to visit first to start exploring the rest of the graph so our first step is we pop off that first value in the Q we can set our current value equal to that value so we're starting at that value here that's our current so we'll do the first thing we'll do is Loop over any neighbors that this node has so the first neighbor that it has is a two so we'll check hey is there a two in the copy there is not so we need to create that node we'll create a brand new node and put it in with no neighbors and then because we are currently looking at node one and We're looping over its neighbors so it has a neighbor of two we need to also reflect that in the copy that node one has a neighbor of two so we'll take this opportunity to put a two as one of the neighbors of the one node the next thing we have to do because we hadn't seen the two before is we need to keep exploring from that node because maybe it has other children as well so to do that we will enter the white two here into the que so that we can keep exploring it on the next round now we're still on number one is our current node so we need to keep looping over all of its neighbors we already looked at two so now we have to look at three and the first thing we ask ourselves is is that three in this copied adjacency list and it's not so we need to go ahead and add a three as well and just like we did for the two because this three is a CH not a child it's a neighbor of one we need to reflect that same relationship over here so again we will make three another one of the neighbors of one so those are all the neighbors and as we can see these match exactly which is good that means our algorithm is working the way that it's supposed to just like we did with the two because we explored this three and added it to the copy we also need to keep go we need to go to the three and check to see if it has any other neighbors that we haven't seen so we will also add the three to the two visit Q now we're finally finished processing this one because we iterated over all of its neighbors so we can now pop off the next value on the Q and replace our current with that value the first thing we do like last time is check is there an entry in copy already that's a two and there is that's right here so nothing to do but then we have to look does two have any neighbors and it does two has a neighbor of one so we need to reflect this in our copy so we can go in and say that two has a neighbor of one and that's its only neighbor so we've completed the full processing of this two so just like we've been doing that means we can pop off the next value which is a three make that our current and so now we're processing this three here first thing we do is look is it in the copy it already is there so nothing to add and now again we look at the neighbors so the Neighbors in the in this case are one and four so that means three has neighbors of one and four so we'll add those and because we haven't visited the four yet and the reason we know that we haven't visited the four is because it's not in the copy we need to add it to our Q so that we can visit it next so the four can go there and now that we've looped Over All of the neighbors of three we can pop our next value which is the four that makes for our current so we're down here the first thing we ask is is that in our copy it is not we're missing the four so we need to go add that first so we'll add a four with no neighbors and now we Loop over the neighbors of the one that we are on so because our current is four we're looking at the four here we Loop over all of its neighbors we see that there's just one which is the three so we go ahead and add that three the only neighbors of four have already been explored we've already been there so there's nothing to add to the Q and so when we go to pop our next value it's actually empty so that means that we are done with the algorithm and to make sure that it works you may have noticed that if we compare our original and our copy each of these are equal meaning we've successfully created a deep copy of the graph first we can do a quick check by saying that if the node doesn't exist meaning it's null uh all we have to do here is return none so there's nothing left to try if we're given a empty graph but then if that's not the case we need to to create our copy so we can set that equal to an empty dictionary and then we need to add to our empty dictionary which is our copy we need to add the original node I showed this in the example on the Whiteboard but the very first step is we need to add that very first node to the copy so we can do that again we can't just set it equal to node because that would be referencing the same node in both graphs we want it to be a deep copy so we actually need to create a new node but we'll pass it the same value that the original node had so this is making that first one uh in written in green except we're not adding any of the neighbors yet we'll add those when we actually iterate through the search algorithm the one other thing we'll do is create our CU so we can call that to visit we'll set it equal to a deck because that's a nice easy Q implementation in Python and then we can actually pass in our first value which will be node because that's where we want to start searching through the original graph we want to start at the top here so we can Loop while the deck is not empty so while while to visit has values in it the first thing we will do is set our current and that can be to visit dot pop left which will remove the front value of the que like we did on the Whiteboard we're going to want to Loop over all of the neighbors of this value so we can say for neighbor in current. neighor we can say if neighbor is not in copy we need to copy we can say copy neighbor equals we copy we can say copy neighbor equals we have to again make a new node and set have to again make a new node and set that equal to that equal to neighbor. Val just like we did up here neighbor. Val just like we did up here we also need to append any of the we also need to append any of the neighbors that we haven't se scene to neighbors that we haven't se scene to our Q so we can say to our Q so we can say to visit. append and we will add neighbor like this finally we also have to add the neighbors associated with this node in the copy graph not the original graph in the copy so we can say copy for current access the neighbors and then we need to append to that the neighbor that we just inserted so copy neighbor so that means we're taking the current value that we're on and we are appending to its neighbors the value that we just inserted here so that's what's happening in line 18 and I think all that's left to do is we just need to return we need to return the new graph which is copy but I think it says we need to return a copy of the given node as a reference oh the first node the first node so I think we can return copy for is it just node because that would be the original one copy node would be the first value so I think we just return that one let's see if that works unexpected indentation these all need to come back on like that sorry everyone my fault so there we go that passes all the test cases including the empty ones so I will submit this and hopefully we're passing everything yes right on so uh that is beating 75% of the other test cases for Speed not doing as well for memory that's interesting because I figured we just had to create oh I guess maybe the the Q is could be adding some extra space but either way this is a fun one um it seems really easy when you first set out thinking oh I just need to make a copy of this but it actually requires a breadth first search you could also do a depth first search they would they would be pretty much equivalent but hope you enjoyed uh leave any comments down below if you have questions concerns or better ways to do this I will see you in the
2024-03-21 11:58:43
133
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 133 (Clone Graph) using Python
6TPFUdVlLHg
yes today we are going to solve a little co2 problem in 1349 it's a hard problem co2 problem in 1349 it's a hard problem and it's posted by Rahul right so as and it's posted by Rahul right so as always we are going to explain this always we are going to explain this problem by introduce the example here so problem by introduce the example here so in the input we are going to have a in the input we are going to have a two-dimensional array and this array two-dimensional array and this array tell us there are some seeds right and tell us there are some seeds right and if the character is Punky means that the if the character is Punky means that the seeds cannot be used right and if it is seeds cannot be used right and if it is dot it means a student can sit there dot it means a student can sit there right and the output put here is how right and the output put here is how many students we can put into the many students we can put into the classroom right so we need to get the classroom right so we need to get the maximum number right so in this case the maximum number right so in this case the maximum number of students we can feel maximum number of students we can feel in the map is 4 right why Cannot these in the map is 4 right why Cannot these two seats be occupied by students two seats be occupied by students because if we place a student here this because if we place a student here this student can see the students before him student can see the students before him upper right upper left and left and the upper right upper left and left and the right right so if we put a student here right right so if we put a student here somewhere somewhere it's up left right left and the rights it's up left right left and the rights cannot be a seat sit by students anymore cannot be a seat sit by students anymore so that's the rule in the classroom so that's the rule in the classroom right so how do we calculate the number right so how do we calculate the number of the maximum number of students of the maximum number of students so let's first take a look at the scale so let's first take a look at the scale of this problem so there are at most M of this problem so there are at most M eight rows and AIDS columns is quite a eight rows and AIDS columns is quite a small number right so as soon as we find small number right so as soon as we find out the scale the problem is small we out the scale the problem is small we need to reflect that we can use binary need to reflect that we can use binary compression here so and it is to compression here so and it is to calculate as a maximum so we can reflect calculate as a maximum so we can reflect that we also need to use dynamic that we also need to use dynamic programming right so to use dynamic programming right so to use dynamic programming programming what is formula here so here is the what is formula here so here is the formula F IJ means for the first for the formula F IJ means for the first for the first I row if the state is J what is first I row if the state is J what is the maximum number of students so what the maximum number of students so what is the state here today the J means if is the state here today the J means if we let's say there is one row so first we let's say there is one row so first row right and the initial state is 0 row right and the initial state is 0 right so 5 0 in binary format means right so 5 0 in binary format means their own right so if this city is their own right so if this city is occupied it means like this right and occupied it means like this right and this is the binary format so let's this is the binary format so let's translate it into decimal that is 0 1 translate it into decimal that is 0 1 they were there earlier right so in they were there earlier right so in decimal is AIDS right and the water bar so this two seats are occupied in a means in binary is like right actually is 16 so for each row we can actually is 16 so for each row we can have States because the for each seat is have States because the for each seat is under occupied by students which is a 1 under occupied by students which is a 1 or not occupied by a student which is 0 or not occupied by a student which is 0 so for each row we can always get a so for each row we can always get a number that is less than 2 to the power number that is less than 2 to the power of M in death decimal format right so M of M in death decimal format right so M here is as large as 8 so it's not so big here is as large as 8 so it's not so big less than one solid right it's still a less than one solid right it's still a small number so if the ice Rose state is small number so if the ice Rose state is J so J is a decimal number which we can J so J is a decimal number which we can transform it into a binary form and that transform it into a binary form and that number can represent this Rose State number can represent this Rose State right so let's move on what is TK here right so let's move on what is TK here so TK here means for the ice row for so TK here means for the ice row for example for the first row the state is K example for the first row the state is K let's say his state is currently like let's say his state is currently like this right so one of the city is this right so one of the city is occupied right occupied right and we can do something to this state and we can do something to this state right what we can do we can place right what we can do we can place another student into the road right for another student into the road right for example we can place a student here so example we can place a student here so that is the transition of our state's that is the transition of our state's right so initially the initial state is right so initially the initial state is all their own and we can iterate all of all their own and we can iterate all of the options we have we only have M the options we have we only have M options so at most of eight options options so at most of eight options right so we added put students at the right so we added put students at the first assets or the second assets or first assets or the second assets or just certain seat or the eight seats just certain seat or the eight seats right so we add most has eight options right so we add most has eight options so we can just iterate each of them and so we can just iterate each of them and in that way we can deduct all the other in that way we can deduct all the other states we can have around the initial states we can have around the initial state right and we can be sure that if state right and we can be sure that if state J is bigger the number of state J state J is bigger the number of state J is bigger than I stated J is always is bigger than I stated J is always transformed from states that is less transformed from states that is less than J right so we can in this way we than J right so we can in this way we can deduct all of those states from the can deduct all of those states from the initial states right so here is a detail initial states right so here is a detail of the transition between two states so of the transition between two states so in the ice row we choose to place a in the ice row we choose to place a student at D so in our example we choose student at D so in our example we choose a student D here right a student D here right and there's a new state this this is the and there's a new state this this is the oldest state right and the new state is oldest state right and the new state is k2 the or operator two one move left T k2 the or operator two one move left T digits right so D here is two so we move digits right so D here is two so we move one two it's left right so we get odd one two it's left right so we get odd number like this and we do our or number like this and we do our or operations so that we get number like operations so that we get number like this right so this is the new state and this right so this is the new state and if the new states that original value is if the new states that original value is lesser than the new value we can replace lesser than the new value we can replace it using the bigger one right so this it using the bigger one right so this guy is the initial state plus 1 right guy is the initial state plus 1 right because TK is the maximum number of because TK is the maximum number of students we can get from this state and students we can get from this state and now we add a new student into the states now we add a new student into the states so the counter of students is increased so the counter of students is increased by 1 right so that is the way we get the by 1 right so that is the way we get the transition between two states and to to transition between two states and to to be cautious so we had to make sure we be cautious so we had to make sure we put a student at a good place right how put a student at a good place right how do we issue of that so first we need to do we issue of that so first we need to make sure that for the current States make sure that for the current States there there is no students or there there is no students or ready occupied this place right for ready occupied this place right for example if the initial state is like example if the initial state is like this we cannot put another student at this we cannot put another student at this place anymore because in this place this place anymore because in this place is already occupied right so we need to is already occupied right so we need to check it if the place itself is not check it if the place itself is not occupied right and we need to also check occupied right and we need to also check the to the left of that place is not the to the left of that place is not occupied as well because of the rule occupied as well because of the rule right and also to the right also to the right and also to the right also to the upper left upper right so how do we upper left upper right so how do we check up left and the upper right here check up left and the upper right here is where we need to use f IJ right so we is where we need to use f IJ right so we need to in order to calculate F IJ need to in order to calculate F IJ we can be sure that we already calculate we can be sure that we already calculate F I minus 1 and J right so we are going F I minus 1 and J right so we are going to have for loop for I so I minus 1 is to have for loop for I so I minus 1 is always calculated before F I right so if always calculated before F I right so if these values are already occupied so we these values are already occupied so we can iterate each of the values so let us can iterate each of the values so let us say we are going to calculate F 2 right say we are going to calculate F 2 right we are going to calculate all of the F 2 we are going to calculate all of the F 2 values in this row right that means we values in this row right that means we already calculate F 1 values in the already calculate F 1 values in the first row right so we are going to first row right so we are going to iterate all of the f1 states so from zero to two to the power of M we are going to iterate all of them and after we get the number I mean get to the state of the first zero when we calculate as a secondary law we can be sure that the the row just data of the row above them and we can check in the upper left and the upper left upper right is occupied by students right so this part can make use of the states of the upper row right so I guess that's it we can now take a look at the code here so here is the code so we initialize the F so this is n rows right and this is our two to the power of n states right we get n and n then we set the initial value to minus 1 so minus 1 is we cannot get this kind of states right for example if for the first 0 each of the seeds are bad right so you cannot get 1 1 1 you binary form for the first row right because all the seats are bad so that means F 1 or equal to minus 1 right if we'd equals to zero that means you cannot put any students in that state right you see essentially the same thing there oh and the - mines essentially does anything so the initial state is that if zero zero equals to zero right if we and take the first the the row before the first zero and for the states is zero the maximal student we can put in is zero right so that makes sense and we are going to start from the first zero to the last zero and we are going to iterate all of the states for the rope before I write so J is the state of the upper row right remember that J is the state of the upper world and now we initialize the array of T and make them all 0 initially and the fullest States 0 its value is f I minus 1 J so why is that so this guy is the upper row with J as a state right and T 0 means we don't put any students in this row right so if we don't put any student in the current 0 and the upper rows it's Jay then it means we can just directly put the maximum number of students of the stated J into the T zero right because T is the aroma so we don't put any student in the current Terrell right and if I zero equals to maximum of these two numbers so we are going to use T 0 to updates if I am zero right so I guess that's also pretty obvious and the let's move on so okay here is in the current i0 the state is K so it's current rows states right and the first iteration is that we use initial States we start from the initial States and we iterate all of our options here so we can put a student at the first place at the second place all the way to the end place right so we are going to iterate all of our options to add one more student and because the current state is K right so we need to make sure that the option do not we do not choose the option that the cities are already occupied by by K right if K is like this and we want to put another two Atlas the this place we are going to have force here right so this part to make sure of that this part make sure of that it's left city is also not occupied this part is make sure that the right seat is not occupied and this part is deal with J here right so do you still remember that the J means the state of the upper row so here is where we check the upper left is not occupied and here is so where we check in the upper right is not occupied and that they both use J here right so when we need to check the current 0 we use K right and we need to check in the upper row we use J so this two states are very important J and K and if all these conditions are satisfied it means we can actually put a student at that place and we can calculate the next states and that we are going to update the state's value right we always choose the bigger value and in the end we are going to choose the maximum value of for the first n rows right so and the returns the answer so I guess that's it thank you for
2024-03-21 00:25:45
1,349
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode 1349 - DP, Binary Compression
TAmv6Csq3Ss
Hello everyone welcome to my channel Quote Surrey with Mike So today we are going to with Mike So today we are going to do video number 18 of our maths playlist, do video number 18 of our maths playlist, it is marked easy but it is a very good it is marked easy but it is a very good question, we made it approachable, number 1716 is calculate money in lead code bank ok so let's see. What the question is trying to say is that Hersey wants to save money for his first car. He puts money in the lead quote bank every day. Now how does he keep the money in the bank? He wants to be seen. He Dollar on Dollar on Dollar on Monday the first day is ok and every day Monday the first day is ok and every day from Tuesday till Sunday will put in from Tuesday till Sunday will put in dollar more than the day before right dollar more than the day before right like let's assume this is Monday this is Tuesday this is Thursday this is Friday this is like let's assume this is Monday this is Tuesday this is Thursday this is Friday this is Saturday this Saturday this is Sunday is Sunday is Sunday kept one more than the previous day on Tuesday, kept two on Tuesday, kept one more than the previous day, kept two on Tuesday, kept three on Wednesday, kept four here, five here, six here, seven here again Look Look Look what he is doing on every subsequent Monday, he will put what he is doing on every subsequent Monday, he will put more than the previous Monday. Now more than the previous Monday. Now look, pay attention. Now when the next Monday comes, look, pay attention. Now when the next Monday comes, tell me what he will do. See, on the previous tell me what he will do. See, on the previous Monday he had put one, now he will put two, Monday he had put one, now he will put two, okay after that. okay after that. okay after that. sa 8 After that when Monday comes again what will he do then see the previous Monday had put two, this time he will put three ok then it will move ahead one by one r pa ₹ ₹ and so on He will deposit He will deposit He will deposit so what you have to do is you have given and kept so what you have to do is you have given and kept return the total amount of money he will have return the total amount of money he will have in the bank at the end of the eighth day total and in the bank at the end of the eighth day total and days he has and it days he has and it is collecting money so let's see this is collecting money so let's see this How much money will be collected in the last day? Okay, How much money will be collected in the last day? Okay, so let's see the example. It will seem so let's see the example. It will seem even simpler. Like look at the first example, even simpler. Like look at the first example, here he has only four days, here he has only four days, so he must have started from Monday. Monday, Tuesday, Wednesday, Thursday were only four days, okay. were only four days, okay. were only four days, okay. one dollar was kept on Monday, two three days were kept on Tuesday, how much has the total become, the total has become 10, then the answer is 10. Okay, now look at this example, the total is 10 days, it has Monday, Monday will start Tuesday. Wednesday Thursday Friday Saturday Sunday came back ok now new Monday will start again it will be 10 days let's see one doti cha pa 6 sa 8 Tuesday Wednesday ok so how will the money be kept from this look at the total 10 days have passed since I Gave 10 days, did not put one here, then kept Gave 10 days, did not put one here, then kept Gave 10 days, did not put one here, then kept increasing it one by one, got 6, then when next Monday increasing it one by one, got 6, then when next Monday came, I had kept one in the previous Monday, so came, I had kept one in the previous Monday, so in the next Monday, just do its plus in the next Monday, just do its plus and, that is, two, its plus and, done, and, that is, two, its plus and, done, okay then. okay then. okay then. is nothing further, he can only deposit the money for 10 days, ok, so find out the total, 1 + 2+ 3+ 4 + 5 6 7 + 2 + 3 + 4, so the Only 37 will come, okay till now it is clear, if Only 37 will come, okay till now it is clear, if Only 37 will come, okay till now it is clear, if we see then the first approach will come, do it as it is we see then the first approach will come, do it as it is told, ok, told, ok, approach one, what is approach one, simply do the approach one, what is approach one, simply do the simulation you have been told to do, simulation you have been told to do, as it is done. as it is done. doing it as explained in the question, I mean, doing it as explained in the question, I mean, look at what I am saying here, I have look at what I am saying here, I have explained here that as much explained here that as much money as is deposited every week, keep adding it, money as is deposited every week, keep adding it, after that when after that when after that when increase the Monday one by two, i.e. by one, from the previous one, then run the whole week, it becomes seven days, then go to the third week and so on, so keep taking out each week as it is Now Now Now look here, pay attention, you are seeing in the first week there are seven days, look here, pay attention, you are seeing in the first week there are seven days, in the second week it has in the second week it has accumulated only till nine days, okay, so we have to pay attention to this thing accumulated only till nine days, okay, so we have to pay attention to this thing that we do not cross it, otherwise that we do not cross it, otherwise see, in the beginning there are at least seven days. see, in the beginning there are at least seven days. see, in the beginning there are at least seven days. remember how many days we had in total. There were 10 days, neither were there 10 days and this one has completed seven here. Now how many are left? 10 - 7 that is 3 so here three are left. Only You see, you have to You see, you have to You see, you have to run it only for 3 days, you do run it only for 3 days, you do n't have to do further days because it will be 10 days, n't have to do further days because it will be 10 days, okay, it is clear till now, so let's see okay, it is clear till now, so let's see how we can do it, we will do it exactly as told, how we can do it, we will do it exactly as told, first of all, keep in first of all, keep in mind that mind that mind that that brother n, which is the greater day, will keep collecting money till it becomes 0, it is clear till now, okay, the second step is that brother, take out the money of sen days and add it, how much will be collected in 7 days. Its ok now when sen days are gone then subtract sen days from n ok days are subtracted from n and after that go back to step one is n equal to 0 yes again money add of seven days Do but pay attention that let's assume that in this example n = 10, right, is 10 equal to 0, yes, right, we have added the money of 7 days, okay, that means we have added these seven days, okay, that's it. After doing n - 7 i.e. 10 - 7 that is 3 became 3, went back to the while loop, is 3 greater day 0, yes, take out 7 days, what no, only three days are left, so I Not the minimum of days, which is Not the minimum of days, which is Not the minimum of days, which is left, either the days are left, look at this, left, either the days are left, look at this, here the value of minimum of n was here the value of minimum of n was 3, otherwise th will come from 3, that is, three days will have to be 3, otherwise th will come from 3, that is, three days will have to be taken out, here are only three days in the last week. taken out, here are only three days in the last week. So what was left is okay, this thing may be So what was left is okay, this thing may be tricky, you can handle it in your own way tricky, you can handle it in your own way but here instead of writing down the intake, but here instead of writing down the intake, I reduced the minimum to 7A because Yes, it is three Yes, it is three Yes, it is three and the minimum in sa is three, so we will and the minimum in sa is three, so we will add up only money for three days. Okay, after that we will add up only money for three days. Okay, after that we will do the same steps again. My 7, 3-7, do the same steps again. My 7, 3-7, what has happened - 4, brother, yes, this one is a what has happened - 4, brother, yes, this one is a while loop here. while loop here. while loop here. minus 4 which is greater zero, no, it is clear till here, so it is quite simple and yes, one thing to pay attention to in this matter is that when you are adding Monday's dice, it is neither Monday nor the There was dollar on Monday and then on next Monday it was There was dollar on Monday and then on next Monday it was There was dollar on Monday and then on next Monday it was NPS, that is, there was L, NPS, that is, there was L, then on next Monday we will have to deposit $3 like this. If then on next Monday we will have to deposit $3 like this. If you are okay then we will handle that too. you are okay then we will handle that too. As soon as we have done it for one week, As soon as we have done it for one week, how much money will he deposit on Monday? how much money will he deposit on Monday? how much money will he deposit on Monday? Monday plus equal two, okay, how much will it start on Monday, so in Monday, one, I have added one d here, okay, so let's see a simple example, a dry run, n e two, how much was 10. Na n is equal to 10. Okay, while a while is n greater than 0, yes 10 which is greater than 0, okay, so what I will do here is I will try to find out the sane days, not even the sane days, the minimum of n is 7, So here n is 10 and 7 sen is there and So here n is 10 and 7 sen is there and So here n is 10 and 7 sen is there and what is the minimum if it is seven then sen days what is the minimum if it is seven then sen days can be calculated because now the value of n is 10 so can be calculated because now the value of n is 10 so 7 days can be calculated neither so 7 days can be calculated neither so what did I do here 7 days money what did I do here 7 days money what did I do here 7 days money then how much will be the money for 7 days? After calculating, the sum of 1 2 3 4 5 6 7 is correct. 1 + 2 + 3 + 4 + 5 + 6 + 7 is correct. Now pay If it If it If it was one then the value of Monday was one. It was was one then the value of Monday was one. It was in the beginning. We have calculated 7 days. in the beginning. We have calculated 7 days. After that what After that what I said was that if we have calculated 7 days then I said was that if we have calculated 7 days then make n = n - 7 because 7 days have already passed. make n = n - 7 because 7 days have already passed. No and yes, one thing to note is that the No and yes, one thing to note is that the money to be added on Monday was $ler and added money to be added on Monday was $ler and added plus plus plus and ok ok that's all plus plus plus and ok ok that's all we had till now, this we had till now, this was the code Gun Gun Gun is 0, yes, so now we are calculating the value of second week. is 0, yes, so now we are calculating the value of second week. Okay, so about the second week, what did I say Okay, so about the second week, what did I say that the minimum of n is 7, my th, so yes, we will calculate the value of only three days and remember the value of Monday, it was two, so two. value of only three days and remember the value of Monday, it was two, so two. value of only three days and remember the value of Monday, it was two, so two. start with 2 Ps 3 Ps Ch, we will calculate only three days, okay, 2 Ps 3 Ps is done and after that we will do the same again n = n 7 i.e. n 3 Ma or Min will become 4, this time the value of Monday. Plus will be plus but this time look at minus f which is greater than zero if it is not zero then the while loop will break so we will go out of here so see who we have added how much money we have added so much money so our answer is exactly the same If it is clear, then If it is clear, then If it is clear, then approach one is very simple. Let's quickly code approach one approach one is very simple. Let's quickly code approach one and see if it is accepted. Otherwise, and see if it is accepted. Otherwise, let's code it let's code it exactly as explained. exactly as explained. First of all, what did I say, okay, First of all, what did I say, okay, take one variable. take one variable. take one variable. which we are adding in the bank. Okay, now look, pay attention, I told you that when that person will start in the starting, then in the starting on Monday, he had the right Okay, starting on Monday, Okay, starting on Monday, Okay, starting on Monday, after that for how long will we do this until after that for how long will we do this until my number of days is over? Okay, my number of days is over? Okay, now look let's add the money of every week, now look let's add the money of every week, int money is equal to start with whom int money is equal to start with whom will we start from Monday? will we start from Monday? will we start from Monday? money is there in Monday, $ is in the beginning, okay, now let's take out this week's first day, 1 day is equal to lesson two, remember what I told you, let's take out each day of every week, The The The value of n is the value of n, if it is less than sen, value of n is the value of n, if it is less than sen, then let us assume that the value of n is th, then then let us assume that the value of n is th, then why take seven days, neither will the minimum why take seven days, neither will the minimum of of n be taken from the comma, right after that, D n be taken from the comma, right after that, D plus plus P, pay attention, result plus. P, pay attention, result plus. P, pay attention, result plus. see the value of money ok and money plus plus will keep doing it remember Monday money starting in the beginning there was one so here I added one after that next time will add again and so Are we doing it? Are we doing it? Okay, now this thing is clear, now that these days are over, so I have done it, we are going on withdrawing money for every day and seeing that we will increase the Monday money because now that So now the next week So now the next week So now the next week which will start and it will start again from Monday, which will start and it will start again from Monday, then we have made money plus plus, right, Monday then we have made money plus plus, right, Monday money was increasing by one dollar every time, in the last money was increasing by one dollar every time, in the last return result has been done, ok, it is quite simple, let's To To To pass all the pass all the cases, cases, indeed yes we have solved this question. We have passed all the indeed yes we have solved this question. We have passed all the cases. Let's move quickly cases. Let's move quickly and understand approach 2 how and understand approach 2 how it can be solved from above. Now look let's it can be solved from above. Now look let's come to our approach 2 through maths. come to our approach 2 through maths. come to our approach 2 through maths. will make it using OV approach, okay, let's assume that in OV time complex, let's take a small simple example that the value of n is 21, it is okay for 21 days and the money will be deposited in the bank, so I have It is kept 1 P 2 P 3 P 4 It is kept 1 P 2 P 3 P 4 It is kept 1 P 2 P 3 P 4 + 5 + 6 + 7 Total will be 8 That will be $8 Then + 5 + 6 + 7 Total will be 8 That will be $8 Then in the second week 2 + 3+ 4 + 5 + 6+ 7+ 8 in the second week 2 + 3+ 4 + 5 + 6+ 7+ 8 Why did it become two? Look, previous Monday it was one so Why did it become two? Look, previous Monday it was one so now it was two. now it was two. now it was two. 5 and so on I also calculated the total sum that 28 35 42 i.e. what will be the total money 28 + 35 + 42 ok it is clear till now ok So So So this is 28, after that is this is 28, after that is 35, after that is 35, after that is 42. This is doing a kind of arithmetic progression 42. This is doing a kind of arithmetic progression form. If you pay attention, form. If you pay attention, look at the common difference, what is the common difference, what is the common difference, look at the common difference, what is the common difference, what is the common difference, and this common difference was bound to come because and this common difference was bound to come because because because because it is increasing one form here from the previous Monday. Okay, after that we used to do plus and psv, so what is the reason for doing plus and and what was there in the previous Tuesday, it became plus and Gone Gone Gone Plow is here Plow here Plow here Plow is here Plow here Plow here Plow here is correct i.e. total seven has been Plow here is correct i.e. total seven has been added extra times. If extra rupee has been added extra times. If extra rupee has been added then 28 × 7 becomes 35 × 7 becomes 42. added then 28 × 7 becomes 35 × 7 becomes 42. So look at the common difference which is exactly seven. So look at the common difference which is exactly seven. So look at the common difference which is exactly seven. it a constant? Is it clear? Common difference is the same. So now that means arithmetic progression is being made and now tell you one thing. If you want to find the sum of an arithmetic progression, then it is already You can also write total number of terms You can also write total number of terms You can also write total number of terms A, but to avoid confusion, A, but to avoid confusion, I am writing terms total number I am writing terms total number of terms by two into first term, first of terms by two into first term, first term plus last term, last term means term plus last term, last term means go by the value of n term, okay this is A1 i.e. go by the value of n term, okay this is A1 i.e. go by the value of n term, okay this is A1 i.e. first term, this is the last term. Okay, so let's see if we can find out how many number of terms we have. Look at the total. Pay attention. Do you remember that the total was 21 days? Look, the days have passed here. The first term is this. After that, seven terms have come out here. This is the second term of AP. This is the third term of A. Okay, so see, it is coming out sen day after sen day. That is, what will be the total number of terms. Look, pay The number of terms will be The number of terms will be The number of terms will be from A to Ba. Total will be the same number of weeks. from A to Ba. Total will be the same number of weeks. First week, second week, third week. First week, second week, third week. Because look here, n = 21 and I have changed Because look here, n = 21 and I have changed n to 7. Okay, it is not complete yet. Wait a n to 7. Okay, it is not complete yet. Wait a little more. little more. little more. here the terms, we came to know that n is from ba, okay so here I will take out n in terms, ba is 7, so what is my n is 21, okay, so what I did, let's put it in this formula here. What is my terms n ba 7 or What is my terms n ba 7 or 21/7 21/7 is how much is 3 so I 21/7 21/7 is how much is 3 so I write this but look into it a1 is write this but look into it a1 is my first term a's my first term a's 28 ok and a what is my last term 28 ok and a what is my last term my a's my a's my a's is 42. Okay, so the last term. Do you remember how we used to find the formula of A? Do you remember what we used to do to find out any eighth term? A1 P n-1 or common difference. Okay, 28 is ok and 28 is ok and 28 is ok and what is the last term sorry a1 + n - 1 * d n what is the last term sorry a1 + n - 1 * d n What is my total number of terms What is my total number of terms Here I write the total number of Here I write the total number of terms terms -1 * d i.e. 3 - 1 * d terms terms -1 * d i.e. 3 - 1 * d total total total is n n ba 7 and the total number of terms -1 * d common difference. We know the common difference is 7. Okay, so how much is 28 plus 3 minus 14. Okay, how much is 42. Okay, so look at the last mm, we have also taken it out from simple A's formula, right, using an eighth term formula, and what is this, a sum of end terms formula, okay, so just solve it, is 70. is 70. is 70. Our answer has come, okay, it is quite simple, so what we had to do, we just had to find the sum of A. Okay, and here you know the first term, you can easily find the last term also. I have explained to you the terms and terms of the formula, here n is from ba, okay but you noticed here, this is a very simple example, I took 21, which is n ba 7, I did That is, That is, That is, if it is not divisible by sen, it is okay, let if it is not divisible by sen, it is okay, let us see its example, so now I am us see its example, so now I am taking the example, if the value of n was 25, then taking the example, if the value of n was 25, then how would we calculate it, then the first week will be the same, sen how would we calculate it, then the first week will be the same, sen days have passed, the second week is the same, seven days have days have passed, the second week is the same, seven days have passed. passed. passed. how many days have passed, 7th, 21 days, okay, now the last four days are left, okay, now I have written the last four days here, it is okay on the fourth week, so okay, this is a It is simple and you will also know how many It is simple and you will also know how many It is simple and you will also know how many days are left in the last days, you days are left in the last days, you can calculate it very easily, do it with N module, the can calculate it very easily, do it with N module, the reminder will be the same, there will be reminder will be the same, there will be so many days left in the last days, okay, that so many days left in the last days, okay, that means I am saying that remaining. means I am saying that remaining. means I am saying that remaining. that will be mine in the last week will be a middle 7, yes, as a reminder, it is okay to divide by 25, because look, if you divide 25 by 7, then 2-3 2-3 2-3 remaining module reminder i.e. remaining module reminder i.e. four days is ok then four will come 25 module 7 four comes four days is ok then four will come 25 module 7 four comes ok so ok so now what will we do, here we have now what will we do, here we have got the model, it is of four days so if we look, got the model, it is of four days so if we look, we are still using the same thing. we are still using the same thing. we are still using the same thing. formula that you learned above, but see how many weeks it is only for three weeks, 28 35 42, so even today AP is being made, is n't it 28 35 42, this is the same progress even today, so its sum even today will be the same It was okay, just It was okay, just It was okay, just in the last we know what we will do, we will take out the final in the last we know what we will do, we will take out the final week, we will take week, we will take out the final week separately, out the final week separately, how many days will be there in it, remember how many how many days will be there in it, remember how many days will be there in it, N Model will be there, there will be 7 days days will be there in it, N Model will be there, there will be 7 days in it, we will take out the final week separately in it, we will take out the final week separately and and and we will figure out the progress of the first three weeks, till now it is clear, okay, now let's see how we will figure out the final week, so see, if we talk about the final week, then So in the final week, So in the final week, So in the final week, you see how much money you see how much money he will give in the beginning, try to understand, that is, whatever he will give in the beginning, try to understand, that is, whatever happens on Monday, how much money will he give in the final week, happens on Monday, how much money will he give in the final week, okay, remember, you know that okay, remember, you know that n times 7 i.e. n times 7 i.e. 25/7. 25/7. 25/7. one two three, only after that the remaining week will come, okay, three weeks will have passed, remember, three weeks will have passed, so in the first week, one will be given on Monday, in the second week, one will be given in the third week. Okay, so remember Monday in the starting, I gave one rep in the starting, how many weeks have passed, three weeks have passed, so what is the actual number of weeks, look at the number of weeks that have passed, add one to it. Ho number of weeks, how many times have passed, three plus one, why did we give one in starting Monday, starting Monday, we have made it plus one, 3 + 4, okay, so this is how we came to know what will be the first term of the fourth week, What will be the first term of the week? It will be of What will be the first term of the week? It will be of What will be the first term of the week? It will be of 1 ps, which means the 1 ps, which means the number of weeks. I write here the number of weeks. I write here the number of weeks number of weeks passed. It is okay because Monday's passed. It is okay because Monday's money was increasing in every week. No, Monday's money was money was increasing in every week. No, Monday's money was increasing in every week. increasing in every week. increasing in every week. plus and to it. Okay, so 1 + 3 is 4. I am clear till now, now I just don't have to do anything. How many number of days is A module 7 i.e. 25 module 3 21 modules left four i.e. 3 21 modules left four i.e. 3 21 modules left four i.e. how much was the final term remember 1 plus number of how much was the final term remember 1 plus number of weeks was three 1 p is four and weeks was three 1 p is four and how many days are left only four days so I how many days are left only four days so I will start from four I started from the beginning and it has to last only four days So it will run for four days 4 5 6 Psa Then we will run the same for loop, it is ok for four days, what am I saying, we will run the for for loop, how many days does it have to run, it has to run for just four days, one day less than Remember this from N module, Remember this from N module, Remember this from N module, remember this in the last week because remember this in the last week because from A model, days only, that will run money, add money from A mud, from A model, days only, that will run money, add money from A mud, days will be plus plus, okay and here days will be plus plus, okay and here what should we do or do, what should we do or do, what was the starting term, starting money, how much money to what was the starting term, starting money, how much money to start with. start with. start with. I will write down how much is the start money na plus number of weeks how much has been passed remember n ba se was na n ba se this much money had passed ok and that's it Keep adding Keep adding Keep adding Result plus equal to whatever start Result plus equal to whatever start money is added to your result money is added to your result and will keep increasing one by one Start and will keep increasing one by one Start money plus plus We will keep adding Start money plus plus, money plus plus We will keep adding Start money plus plus, first Rs will be added then ₹ will be added then ₹ will be added then first Rs will be added then ₹ will be added then ₹ will be added then ₹ will be added right for four days ₹ will be added right for four days That's why I have told you everything in detail, so let's put the same thing in the code and finish it, so let's start its code. First of all, what did I say that how many n will be 7. Okay, now as n will be 7. Okay, now as n will be 7. Okay, now as many weeks as we can find out in this given n, many weeks as we can find out in this given n, we will find its sum from A. we will find its sum from A. Okay and remember the first term of this A will Okay and remember the first term of this A will always be 28 right because always be 28 right because I told you that I told you that I told you that so remember, the first one was 28, the sum of the first week was 35, after that it was 42, after that and so on, this is what we were getting, so the first term was 28, okay, but Right because Right because Right because we have to calculate the number of terms and number of we have to calculate the number of terms and number of weeks according to that. So weeks according to that. So remember what was the last term? How was a? How was a? Term plus n mive i.e. n is my Term plus n mive i.e. n is my number of terms so terms mive into common number of terms so terms mive into common difference remember common difference will always be difference remember common difference will always be sane right so what is my a sane right so what is my a formula for the ith term is clear till now formula for the ith term is clear till now after this it is very simple a is the sum of a after this it is very simple a is the sum of a after this it is very simple a is the sum of a okay to find the formula. Items i.e. items by two is okay. Either I would have done it like this. Items into first term plus last term byt is okay. Sum of eighth terms in NA. We have just applied the formula of A on Y. Okay, If it is the final week of remaining days If it is the final week of remaining days If it is the final week of remaining days then how many remaining days will there be, you then how many remaining days will there be, you know that here I also write e know that here I also write e equal to n module 7 will be right then int equal to n module 7 will be right then int start money how much will it start from remember start money how much will it start from remember n plus number of weeks how many weeks have n plus number of weeks how many weeks have passed as many passed as many passed as many weeks are here, that is, n ba n ba se na, so here I write the terms and for int day is equal to one day lesson is equal and for int day is equal to one day lesson is equal to one module, so many days will be the last one. to one module, so many days will be the last one. After that on the week, do day plus plus After that on the week, do day plus plus and just keep adding, result plus equal to two, and just keep adding, result plus equal to two, okay, if it is even or not, then here I okay, if it is even or not, then here I write the result as if a is even or not, and here write the result as if a is even or not, and here result plus e equal to two, whatever my result plus e equal to two, whatever my start. start. start. doing money plus plus also. In the end, what we have to do is to return the result. Let's run and see. Let's see if we are able to pass all the cases. What mistake have we made here? There will be cases. What mistake have we made here? There will be terms instead of items, won't it be total? terms instead of items, won't it be total? terms instead of items, won't it be total? terms. Item was not even a variable. Let's see the example. Test cases will pass. After that we will run and submit. completion. Look at this line, it completion. Look at this line, it is not in ov. Line number nine, look at this. is not in ov. Line number nine, look at this. is not in ov. Line number nine, look at this. o1 is simple, we have used the formula o o f Okay, now you say brother, here you are using for loop, so pay attention, it is from n module, it is a constant, it can be It It It can be one, it can be two, it can be 3, 4, can be one, it can be two, it can be 3, 4, 5, it can be six, sometimes it will be more than this, 5, it can be six, sometimes it will be more than this, otherwise it is a constant, no, this otherwise it is a constant, no, this loop will never run more than six times, loop will never run more than six times, this loop will never run more than six times, so that is this loop will never run more than six times, so that is why it why it why it This fixed number of times will run. It is always good. It will never run more than six times. This is also an oven, so it is an overall oven. Any doubt, please post in the comment section. Try Thank Thank Thank you
2024-03-20 15:22:57
1,716
https://i.ytimg.com/vi/T…axresdefault.jpg
Calculate Money in Leetcode Bank | 2 Approaches | O(n) | O(1) | Leetcode 1716
vjzVfmWjJg8
hey so welcome back and there's another daily kill problem so today it's called daily kill problem so today it's called longest palindromics substring and it's longest palindromics substring and it's medium level dynamic programming problem medium level dynamic programming problem and so essentially what you want to do and so essentially what you want to do is just find the longest uh pandoromic is just find the longest uh pandoromic substring and what that is is while a substring and what that is is while a substring is when you just take a kind substring is when you just take a kind of fixed size of a particular string you of fixed size of a particular string you can't kind of hop over them they all can't kind of hop over them they all have to be consecutive so say bab that's have to be consecutive so say bab that's a substring but you can't say take B and a substring but you can't say take B and then grab D to make a substring they then grab D to make a substring they have to be kind of all consecutive or have to be kind of all consecutive or all in a row all in a row okay and so the other part of this okay and so the other part of this definition is what is a palindrome and definition is what is a palindrome and that's just where if you read it like uh that's just where if you read it like uh from left to right or right to left you from left to right or right to left you spell it the same way and so something spell it the same way and so something like a like a B B A that's a palindrome because B B A that's a palindrome because whether you read it from left to right whether you read it from left to right or right to left it's still going to or right to left it's still going to kind of spell out the same word kind of spell out the same word uh same thing where this is an even uh same thing where this is an even number of letters you could also have number of letters you could also have something like a b a something like a b a and that's also considered a palindrome and that's also considered a palindrome okay so typically this is a very popular okay so typically this is a very popular Alico problem typically you would use Alico problem typically you would use something called like the two pointer something called like the two pointer method where you have a pointer pointing method where you have a pointer pointing on one side and a pointer pointing on on one side and a pointer pointing on the other side and you kind of just move the other side and you kind of just move them in with each iteration and once them in with each iteration and once they kind of touch each other or overlap they kind of touch each other or overlap you've proven that it's pound room as you've proven that it's pound room as long as they've always are matching as long as they've always are matching as you bring them in closer you can also do you bring them in closer you can also do it the other way where you start from it the other way where you start from the middle and then move out and that's the middle and then move out and that's actually what we're going to do actually what we're going to do and so basically what you do is you're and so basically what you do is you're going to have one function call it okay going to have one function call it okay is this is this a pound room and we're going to specify like our left and right pointer here and so we're going to be kind of iterating through for every kind of point in this string we're going to see if we can make a pound room there and so for the length of the string let's see if we can make a pound drone and we're going to return some substring here and so we're going to have to kind of take a slicing of the two sides and so we're going to need to define a left pointer and a right pointer such that this is like the maximum poundromic substring okay and so other thing in Python you have to add a plus one just because um it's non-inclusive on the right side okay and so we'll go ahead and Define these so initially our Max on the left we could see the Max on the right and we're just going to start them at index 0. so we're just basically iterating from left to right here and we're going to consider and trying to expand each of these points in this array or in this string to see if we can expand it and see what's maximum pounder we can create from going from the inside out okay and so to do that uh you have to consider those two cases where is it an odd length or an even length and so basically what that's going to look like is we just want to call this is palindrome function and you just need to specify okay we can either in this case start at the middle and that's going to be whenever it's a even or an odd number so this would be odd where we're going to start from the middle and expand out and that's kind of like a B A and so we're doing this and we point them both at B obviously that's going to be the same and we just decrement one pointer and then increment the other pointer okay but for the even length which is the second case we're going to say okay what if it's like a b b a we're basically going to have one pointer that will be on the left kind of middle and then the second pointer which beyond the kind of right side of the midpoint okay and so what that's going to look like is pretty much same thing here except we'll do I plus one that's how you kind of get the right side of the the mid okay and so that's that but what we're going to do is we have to fulfill this function here and so first thing that we're going to want to specify is just these Max left and right and so from here we're just going to and so from here we're just going to want to iterate and kind of expand from want to iterate and kind of expand from the inside out while it's still valid so the inside out while it's still valid so while the left pointer is greater than while the left pointer is greater than or equal to zero because we want to stay or equal to zero because we want to stay within range and a right pointer is less within range and a right pointer is less than the length of our string than the length of our string but then also but then also that while the left pointer is equal to that while the left pointer is equal to our right pointer and so the first two our right pointer and so the first two cases just make sure that we're kind of cases just make sure that we're kind of within the bound so that when we index within the bound so that when we index into the string it doesn't throw an into the string it doesn't throw an error and the second cause is just to error and the second cause is just to make sure that well what we're checking make sure that well what we're checking after all is that it's a palindrome as after all is that it's a palindrome as we move these pointers out they're the we move these pointers out they're the same same okay so with that so then naturally with okay so with that so then naturally with each iteration we're going to want to each iteration we're going to want to move these pointers such that our left move these pointers such that our left pointer is decremented and our right pointer is decremented and our right pointer is incremented pointer is incremented but we finally want to update our case but we finally want to update our case whenever we found a new Max like whenever we found a new Max like substring length we want to update our substring length we want to update our Max left and Max right pointers so that Max left and Max right pointers so that we kind of can continue to maintain that we kind of can continue to maintain that maximum pound dromic substring maximum pound dromic substring and so to do that what you do is you and so to do that what you do is you just say Okay just say Okay um um our Max left our Max left or we want to do that whenever if the or we want to do that whenever if the right pointer mine's the left pointer right pointer mine's the left pointer oh and what we're doing here oh and what we're doing here is while left is greater than that and is while left is greater than that and right is that right is that so we specify that here sorry I got so we specify that here sorry I got confused confused this should all be good this should all be good um we want to update okay if right minus um we want to update okay if right minus left plus one which is basically the left plus one which is basically the size of the current running uh size of the current running uh palindromic substring that we're taking palindromic substring that we're taking a look at if this is greater than a look at if this is greater than the current our largest Pounder with the current our largest Pounder with some string which is basically just Max some string which is basically just Max on the right minus Max on the left plus on the right minus Max on the left plus one one and so from here we just say okay then and so from here we just say okay then our maximum on the left and our maximum our maximum on the left and our maximum on the right we're going to want to on the right we're going to want to update these pointers so that it's now update these pointers so that it's now equal to the current pointers equal to the current pointers and that's about that uh and that's about that uh looks like there's something wrong here looks like there's something wrong here and valid syntax not sure what's going on here not sure what's going on here or i o in sorry and success so that's uh today's Lico and success so that's uh today's Lico problem so for time and space complexity problem so for time and space complexity the time will be N squared because in the time will be N squared because in the worst case you kind of expand the worst case you kind of expand um to the fullest with each iteration um to the fullest with each iteration and then for space complexity well this and then for space complexity well this is non-recursive is non-recursive um it's simply just being called and you um it's simply just being called and you expand and there's no extra data expand and there's no extra data structures that's used to store a new structures that's used to store a new memory other than just constant space memory other than just constant space variables so it would be o of one space variables so it would be o of one space but yeah I hope it helped and good luck but yeah I hope it helped and good luck with the rest your algorithms thanks for with the rest your algorithms thanks for watching
2024-03-18 11:17:12
5
https://i.ytimg.com/vi/v…axresdefault.jpg
5. Longest Palindromic Substring - LeetCode Python Solution
BSG6uTh1mp4
welcome to dab the light development done right and today I'm going to be done right and today I'm going to be solving a lead code problem number 56 solving a lead code problem number 56 merchant rules let's get started merchant rules let's get started and don't forget to Like and subscribe merge intervals given a collection of intervals merge all overlapping intervals now this is a common type of problem sometimes they call it intervals sometimes they call this meetings but basically you usually given an input of a race and you need to merge those numbers which overlap so for example if you have an interval 1 + 3 + 2 + 6 - falls between 1 & 3 so they want you to merge it into 1 & 6 how can we do that was a three-step process that you can utilize for other merge interval problems as well step one is always turning intervals into points and step three processing those points and step three processing those points all right so to process and turn this all right so to process and turn this intervals in the points you can do this can extract the first the start time the and what we can do here is either create and what we can do here is either create a class and what this class will do is a class and what this class will do is keep track off the point such as X or Y keep track off the point such as X or Y and if it's a start or end point so if and if it's a start or end point so if it started it would be true if its end it started it would be true if its end point it would be false and you need to point it would be false and you need to push all this points also into an array so we can push Nieporent X would be the time and start will be true and for y it would be the same thing except obviously it will be Y and this would be false but there's also another way to represent this without the class which will save you time on the writing code and probably easier to look at so let's get rid of this class points or ship the instead we can directly push into an instead we can directly push into an array and you can push an object so time array and you can push an object so time is X and if start it true same thing for is X and if start it true same thing for the Y except is start false let's print the Y except is start false let's print this out so you can take a look of how this out so you can take a look of how this points look like alright so don't this points look like alright so don't worry about the wrong answer because worry about the wrong answer because we're not finished I'm just showing you we're not finished I'm just showing you the output really quick so this is how the output really quick so this is how this points will look like time it this points will look like time it started true three is start false you started true three is start false you see they're separated in its own objects see they're separated in its own objects so here we need to sort by time we need so here we need to sort by time we need the stew to show up before the three and the stew to show up before the three and we need to sort by its start because we need to sort by its start because sometimes one meeting can end at the sometimes one meeting can end at the same time as another meeting is same time as another meeting is beginning but you need to have the beginning but you need to have the meeting that's beginning in front of our meeting that's beginning in front of our array if they both stop start at the array if they both stop start at the same time so how do we sort this point same time so how do we sort this point sort you should already know how sorting sort you should already know how sorting works in JavaScript if not I have a works in JavaScript if not I have a video on my channel that you can check video on my channel that you can check out so first we're gonna check if the out so first we're gonna check if the times are equal if it is we need to times are equal if it is we need to check you need to check if they're both check you need to check if they're both if they both start or end at the same if they both start or end at the same time because if they do then that's time because if they do then that's irrelevant to us it's same thing one can irrelevant to us it's same thing one can show before the other else show before the other else if they're not equal we'll return it in if they're not equal we'll return it in a way where a is start if that equals to a way where a is start if that equals to true it should show up before the one true it should show up before the one that ends and if the times are not equal that ends and if the times are not equal then just sorted by time so as you can then just sorted by time so as you can see basically at the time of this two see basically at the time of this two intervals is equal we want to sort the intervals is equal we want to sort the one that starts before the one that ends one that starts before the one that ends otherwise we return in ascending order otherwise we return in ascending order my time so we're sorting by time and by my time so we're sorting by time and by the start as well let me remove this console dot log so the next thing we need to do is process this points the way to do that is we're going to keep the counter and basically when the meeting starts we increase the counter by 1 when the meeting ends or the interval ends we decrement we decrease the counter by 1 that way we know meaning started it becomes 1 meaning in it it becomes 0 what if two meetings start so the counter will become 1 and then 2 so the counter lets us know if there's an overlap of the interval or meeting whatever you want to call it or not also let's create a new points array where they'll keep all the new intervals of your process okay and they already know if the meeting is starting or not because we use a start flag so what you can do is if point is start you know the meeting has started so as I mentioned if the counter is 0 we know it's a new interval is beginning so we need to keep track of that let's say a new start so the meeting is starting the counter is 0 it's a new interval that begins and we need that point that's why we have new start and they'll assign time to it and of course we need else means the meeting is over so we else means the meeting is over so we need to decrease the counter and that need to decrease the counter and that the counter is equal to zero meaning the counter is equal to zero meaning there's no meetings overlapping right there's no meetings overlapping right because if there was meetings because if there was meetings overlapping Connor would not be zero we overlapping Connor would not be zero we know this is the final point there's no know this is the final point there's no intervals overlapping and we need to intervals overlapping and we need to push that to new points using our new push that to new points using our new start and time so this is our Y time start and time so this is our Y time this is our x time because we tracking this is our x time because we tracking X's here start and every meeting or interval that ends will be here point that time and of course we need to return all these new points let's run this of course I made a mistake didn't add the arrow and as you can see we passed the tests and everything is working great I hope you enjoyed this tutorial subscribe if you didn't yet because there's more tutorials coming and also you can leave in a comment what you liked about the video and what other questions you want you
2024-03-20 10:32:57
56
https://i.ytimg.com/vi/B…axresdefault.jpg
LeetCode - 56 - Merge Intervals - Medium
N_X_91nqu9Y
hi today we're going to be going over the java solution for lead code 14. the java solution for lead code 14. longest common prefix write a function longest common prefix write a function to write the longest common prefix to write the longest common prefix string amongst an array of strings if string amongst an array of strings if there is no common prefix return an there is no common prefix return an empty string as empty string as i guess given here i guess given here so prefix means basically the starting so prefix means basically the starting letters of a word letters of a word so you know longest common so we're so you know longest common so we're going to try to look for basically which going to try to look for basically which starting sequence of letters to all of starting sequence of letters to all of the elements in a string array have in the elements in a string array have in common so if you're looking for the common so if you're looking for the shortest of course it's just an empty shortest of course it's just an empty string if you're looking for the second string if you're looking for the second shortest in this case it would be f so shortest in this case it would be f so all of them have f in common from the all of them have f in common from the beginning and then if we move on to l beginning and then if we move on to l all of them have f l in comment but if all of them have f l in comment but if we look on to the third letter f l o f l we look on to the third letter f l o f l o but this is f l i o but this is f l i so they don't all have three so they don't all have three um three of the beginning letters in um three of the beginning letters in common so that's why we'll just return common so that's why we'll just return the two which is the guaranteed one they the two which is the guaranteed one they have in common which is just fl have in common which is just fl um with this one we can see that you um with this one we can see that you know even the starting letter none of know even the starting letter none of them have in common so we just return an them have in common so we just return an empty string and so i think there are empty string and so i think there are two key takeaways two key takeaways from here number one is that we just from here number one is that we just need one of these need one of these to to be different than the other in order to be different than the other in order to figure out the longest common one we figure out the longest common one we could basically look at this one we can could basically look at this one we can see the fl fl and then even though both see the fl fl and then even though both of these have o and o this one has an i of these have o and o this one has an i which breaks the whole continuity which which breaks the whole continuity which means we could just break it from there means we could just break it from there and just return however many we have and just return however many we have completed thus far however many letters completed thus far however many letters we have found thus far that they have in we have found thus far that they have in common common and then the second thing is that and then the second thing is that the maximum length of en of the output the maximum length of en of the output string can ever equal is basically the string can ever equal is basically the shortest or smallest element in the shortest or smallest element in the array so let's do that let's go find it array so let's do that let's go find it so we'll do an int so we'll do an int minimum which is going to equal integer minimum which is going to equal integer integer.max value integer.max value and we'll have an index since that's the and we'll have an index since that's the thing we care about we're going to look thing we care about we're going to look for the index of the string so that we for the index of the string so that we could could basically analyze it i guess and then basically analyze it i guess and then we're just going to go through the whole we're just going to go through the whole array and now if str's of i dot length is less than our min then number one our min is going to turn that length that length and our index is going to equal that and our index is going to equal that index so after we come out of this loop index so after we come out of this loop we'll have the index of we'll have the index of the sm shortest or tied for the shortest the sm shortest or tied for the shortest element element string element so for communication string element so for communication sakes or to make um so for the case of sakes or to make um so for the case of making this a bit more clear making this a bit more clear i'm just going to store that in a i'm just going to store that in a temporary string i'll name str temporary string i'll name str and that is going to equal uh strs of and that is going to equal uh strs of index index okay great so now what we're going to do okay great so now what we're going to do is that we're going to number one do a is that we're going to number one do a double for loop and what the how the double for loop and what the how the loop is going to be structured is that loop is going to be structured is that our outer loop is just going to look our outer loop is just going to look through all the letters of our smallest through all the letters of our smallest string so str so in this example one it string so str so in this example one it would be flow and example two it would would be flow and example two it would be dog and we're just gonna look through be dog and we're just gonna look through all the letters and then our second loop all the letters and then our second loop is gonna loop through all those is gonna loop through all those elements to see do they have elements to see do they have that character in common so let's do that character in common so let's do that so four in ti is equal to zero that so four in ti is equal to zero i is less than scr dot length i is less than scr dot length i plus plus i plus plus i don't know why it doesn't okay there i don't know why it doesn't okay there we go we go um and then four and j is equal to zero um and then four and j is equal to zero and now j is less than and now j is less than um the length of the array and we'll do um the length of the array and we'll do j plus plus and j plus plus and for clarity's sake i'm gonna store the for clarity's sake i'm gonna store the character we are using as a temp character we are using as a temp a character temp and that's going to a character temp and that's going to equal str at i so when we look through all the elements it's like if they do equal are temporary then that's great if they don't that's the case we care about so if uh str's of j dot char at i is not equal to or temporary then we know we have basically found the longest common prefix and that's just going to be how many letters we have completed thus far so we can just return the substring of from zero to i of our str or really any other um element and if we go through this we go out of this for loop then we know that you know we have completed all of the letters which means that we can just return um str itself since that means that str itself is common with all the elements okay great and now let's submit it okay great so that was
2024-03-19 15:28:15
14
https://i.ytimg.com/vi/N…axresdefault.jpg
Leetcode 14: Longest Common Prefix | Java Solution
79GOxqjpLxc
hey guys what's up today's question we're going to say the three one low we're going to say the three one low the minimum high trees is that giving us the minimum high trees is that giving us the the 2d array which is uh in 2d array which is uh in edges and it will be represented by the edges and it will be represented by the connection between two nodes and connection between two nodes and it wanted us to find the minimum high it wanted us to find the minimum high tree the root of a minimum high tree tree the root of a minimum high tree uh and uh for this for example because uh and uh for this for example because you know the minimum height defined here you know the minimum height defined here will be will be the longest path from the root that you the longest path from the root that you find and find and to the leaves to the you know the leaves to the leaves to the you know the leaves node and in this path will be like node and in this path will be like the one will be zero because like the one will be zero because like whenever we whenever we uh from zero to any other nodes you will uh from zero to any other nodes you will be like have the minimus be like have the minimus last there will be one and if you see last there will be one and if you see defined here will be in a loop defined here will be in a loop and you will just receive a lens with and you will just receive a lens with two because you come from here two because you come from here to here because you want the longest to here because you want the longest path to be defined as the uh path to be defined as the uh the height right so that we need to find the height right so that we need to find the minimum you know root the minimum you know root and to be honest the first the most and to be honest the first the most intuitive idea for me is to use in intuitive idea for me is to use in pfs why is that because using the bfs we pfs why is that because using the bfs we ever because we see the keyword minimum ever because we see the keyword minimum whenever i saw the keyword like minimum whenever i saw the keyword like minimum or surveys or surveys uh in the uh in the graph question we're uh in the uh in the graph question we're just gonna just gonna use the bfs in order to get the uh the use the bfs in order to get the uh the minimum or shortest you know result and minimum or shortest you know result and for this we will actually the most for this we will actually the most infinite right there will be like infinite right there will be like first two traversal uh for every node first two traversal uh for every node for every node for every node uh node we will actually will be like uh node we will actually will be like to be fast uh like thickness for example to be fast uh like thickness for example we will first take this we will first take this and then we're just gonna go to rest of and then we're just gonna go to rest of that and find out that that and find out that if we take this for the height it will if we take this for the height it will be like if we take zero the height will be like if we take zero the height will be be like one if we take one and the the like one if we take one and the the height will be two height will be two so that we we actually to you know so that we we actually to you know compare between each other the minimum compare between each other the minimum length length uh whenever we take you know each note uh whenever we take you know each note be the root and be the root and then we're just going to return we first then we're just going to return we first will compare and will compare and return compare and return the uh to see which one which not have the minimum last or the you know pass however this method is quite time consuming hard because that first we need to go towards the node and they are going to be faster and to be effective you will just you know we'll have the complexity of one and this will be time uh square right so that we need to reduce the time complexity and this will time limit the uh online attachment for the code and uh yeah so how are we gonna you know improving that because first our most engineering idea will be like goes first from the uh root to the leaves and it is possible to get the result from the leaves to the root what do i mean by that it's like whenever we are going to rest in the trees and uh take this for example if they we here we will just get we we can actually to first to define the adjacent table right and to record it every connection situation between you know each node and for zero zero the back in the zero will be have like uh one two and three right and the one will have the band which contains like zero and the two will contain the bag which will contains like zero left and the same thing for three and what i mean by that it's like because we first we were just looking uh to enqueue because we obviously use you know vfs to solve this problem and to use in a queue and the queue will be first added the elements of nodes which have only one you know one element to edit that and we can delete it and to you know delete it in the corresponding banks which means that i was gonna delete that and this is and you can also see from here whenever and you can also see from here whenever elsa removes all the kind of elements elsa removes all the kind of elements the zero will be the final result that the zero will be the final result that we want we want you may just say it might be there isn't you may just say it might be there isn't however i will show you that however i will show you that i'm just gonna show you that it happens i'm just gonna show you that it happens uh actually it's cracked for every you uh actually it's cracked for every you know uh arrow grab know uh arrow grab and let's take this for example if they and let's take this for example if they here we will have a here we will have a like zero one two three four five right like zero one two three four five right and uh we here will actually enqueue and uh we here will actually enqueue the searching another color the searching another color into this one this boy this boy and this into this one this boy this boy and this point right because they only have one point right because they only have one connection with connection with each other notes uh four have one two each other notes uh four have one two three four three four uh four connection and the three have uh four connection and the three have two right so we're just gonna first two right so we're just gonna first include this kind of voice i'm going and include this kind of voice i'm going and then that then that and also because each node will have the and also because each node will have the adjacent table which means that adjacent table which means that each node has a crosswinding back and each node has a crosswinding back and we're just going to delete we're just going to delete the corresponding the counterpart from the corresponding the counterpart from the back so here we're just going to do the back so here we're just going to do that and you can see after we perform an optional delay and only you know the node that we left is four and a three so should we just you know go further no because actually here whenever you use four or three to be your root the minimum higher length will be the same because like wherever i just resume this situation three will be two right from here to here because it will be the longest path we defined as you know the higher tree and if you go uh take four as your loop and then go from here here and you'll also be true so that basically what i mean is that uh the result set because in because in java the result will be like the least however again and uh to be honest the real will only contains one or two elements right and uh yeah and what about certain graph what does that happen well you can see from the third graph that first we do you know the same operation we first in queue the element which has only one connection with you know other nodes which is you know this one uh this one this one this one and this one right and uh we kind of like you know talking leaves and to include it and this is our three this is a four this is five this is one this is two right and then we're just going to delete that from our graph from our whatever you want the json table after we did that we actually noticed the updated situation where it will have only one connection you know compared to before where it it had a two connection right here and here so basically here i will uh kind of fixing that and uh you only you know after we perform this operation and only here we're just gonna left uh this support we'll have one connection this will come right next and support highway connection and this will have a three connection right through connection so what are we gonna do next we're just gonna encode uh the seven eight nine and then after that the only element that we left are four right so it's actually the result that we want so basically by you know uh philippians from you know we're first uh using algorithm from top to uh from the root to the left and you will be time consuming however after we change our thinking process from you know the leaves and the kind of like surrounding surrounding where we start from the leaves and then we just finally reach the root and yeah that's kind of what we want and and now let's see how the code to implement that and we first need to write some you know instructions in order to follow it smoothly so we first will construct the uh the json table red and then we are just gonna to using the bfs using the queue to add the leaf nodes and to remove that uh only until the end will be uh and will be like r2r1 right so yeah and then we're just gonna return that and turn that so yeah no that's we're just gonna write our record we first of all just write a uh uh adjacent table right here i was just gonna use that as a hashtag in order to find it quickly right and the decision table you have as released right and uh here we will actually to construct it and uh for i equals zero and less than our i plus class and the edg they'll added our new headset right integer uh and also we need to construct the adjacent table right we only just initialize that and flow in edges to our edges and we will adg that get e h zero uh edit our h1 there and it happens you know opposite and to edit that and we need a zero right and uh here we will uh see because we constructed it as successfully and then we're just gonna using the bfs so we first will need to new a q right otherwise zero is just gonna know where to perform that and uh there will be like integer uh q q u a real q right and uh yeah to be honest we need to go first to resolve that and to find out whether or not it has only one connection because that's the least that we want right so we're just going to say if c i actually get all that size equals zero which means that this is a leaves that we want and we're just gonna enqueue that uh right and uh yeah specifically the uh point and let's say well it's greater than two because uh the result set will be like two or one elements uh in our results over here we're just gonna this can actually new here at at the end of the code and result [Applause] per list and say well per list and say well qr is empty and we're just going to qr is empty and we're just going to include that include that because the only elements that are left because the only elements that are left are are cues that we want right so we're just cues that we want right so we're just going to edit our going to edit our say code up call professor per say code up call professor per call last version of file right and call last version of file right and we're just gonna return result we're just gonna return result and this is a key part where we should and this is a key part where we should you know keep notice on so we here we you know keep notice on so we here we all all this is kind of classic model of bfs and this is kind of classic model of bfs and so you guys can so you guys can you know remember that and union you know remember that and union standard was just you know standard was just you know creating that and uh here we actually we creating that and uh here we actually we need to uh pull the current number which need to uh pull the current number which means that means that we need to see and uh which bag that i we need to see and uh which bag that i want to you know remove want to you know remove q dot c uh pole q dot c uh pole pull first and then what are we going to pull first and then what are we going to do we need to do we need to for because in the uh in the set for because in the uh in the set the current number contains we need to the current number contains we need to eliminate the connection between the eliminate the connection between the current number and maybe other number current number and maybe other number who have the connection between each who have the connection between each other right so integer num to our other right so integer num to our adjacent docket current number which is adjacent docket current number which is a hash set and a hash set and we're just going to using fourier to we're just going to using fourier to transfer that and the error time we're transfer that and the error time we're just going to just going to remove our current number right and uh remove our current number right and uh yeah that's basically the point yeah that's basically the point and after that we uh and minus our size and after that we uh and minus our size right right this is uh we're in our code and uh yeah this is uh we're in our code and uh yeah i believe that i believe that that's it and let's see how this is that's it and let's see how this is going uh it says array d going uh it says array d q d q u e q d q d q u e q d q u e u right the uq tq q u e u right the uq tq and uh the q oh we don't have the last two characters right and uh here we also need to you know do a adjective judgment if they equal that one and we will directly use this result set and uh to you know result i added our one right and we're just gonna return that right and nope the turret is all right and we can see it was uh what's going on and uh we here we will get this this point oh here we will get this boy and uh see here right and this one can say oh there's the uh while n is greater than two we will actually let's see what's going on we first added a headset for every you know table and we got that zero one one zero right and uh we here knew the dq and every time we actually to pull oh i just forgot one thing which is you know we need to add the z uh we need to find out whether or not this adjacent number will have you say adj dot gas now the our size is equal to our one we are actually to you know added the cube otherwise you're just gonna be nothing right so that's my you know error for this and you can see from here and all right the last right at the last to capitalize and see how things going up and let's test this one to you know and yeah that's basically the whole idea for this question we're gonna and let's go back and trust it again and let's go back and trust it again first we're just gonna construct the first we're just gonna construct the adjacent table adjacent table and then to uh get the leaf nodes and then to uh get the leaf nodes because we want because we want the connection to be only one and the connection to be only one and whenever you know the loop condition whenever you know the loop condition will be like if say will be like if say there will exist uh two more elements there will exist uh two more elements we're just gonna we're just gonna continue deleting that because you say continue deleting that because you say there are three elements there are three elements you definitely can you know you limit you definitely can you know you limit that again that again however if only it has two or one however if only it has two or one element you're just gonna okay and we're element you're just gonna okay and we're just gonna edit that so yeah that's just gonna edit that so yeah that's basically the idea for this three one basically the idea for this three one oh the time consum the time complexity oh the time consum the time complexity will be uh this is one and uh this will will be uh this is one and uh this will also be also be on so yeah that's basically the point
2024-03-24 10:12:26
310
https://i.ytimg.com/vi/7…axresdefault.jpg
leetcode 310 Minimum Height Trees English Version
NobAOk9CnP8
hey everyone today we are going to solve the little question sign of the product the little question sign of the product of an array so there is a function sine of an array so there is a function sine func X and that returns one if x is func X and that returns one if x is positive a minus 1 if x is negative zero positive a minus 1 if x is negative zero if x is equal to zero so you are given if x is equal to zero so you are given integer array nouns let product be the integer array nouns let product be the product of all values in the array nouns product of all values in the array nouns return the sign Funk with product return the sign Funk with product so let's see the example U are given so let's see the example U are given minus 1 minus 2 minus 3 minus 4 3 2 1 minus 1 minus 2 minus 3 minus 4 3 2 1 and the output D is one because uh and the output D is one because uh um If I multiply all values so that um If I multiply all values so that should be um should be um 144 so that means this is a positive 144 so that means this is a positive number so that's why we should return number so that's why we should return one before I start my explanation so let one before I start my explanation so let me introduce my channel so I create a me introduce my channel so I create a lot of videos to prepare for technical lot of videos to prepare for technical interviews I explain all the details of interviews I explain all the details of all questions in the video and you can all questions in the video and you can get the code from GitHub for free so get the code from GitHub for free so please subscribe my channel hit the please subscribe my channel hit the right button or leave a comment thank right button or leave a comment thank you for your support you for your support okay so let me explain with this example okay so let me explain with this example so I copy this inventory from example so I copy this inventory from example one so the product of all values in the one so the product of all values in the array should be 144 so we should return array should be 144 so we should return one in this case one in this case so to solve this question so important so to solve this question so important thing is that we don't have to return thing is that we don't have to return the specific product number the specific product number um so if the product number is positive um so if the product number is positive we should return one we should return one if the number is negative we should if the number is negative we should return minus one if zero we should be return minus one if zero we should be done zero so done zero so to solve this question to solve this question um I use a one variable so let's call um I use a one variable so let's call like a sign initialized with one and like a sign initialized with one and basically we get it through all values basically we get it through all values one by one one by one and then if we find a negative number and then if we find a negative number um um we multiply we multiply minus one minus one to sign variable because a negative to sign variable because a negative number affects like a Plus or a minus number affects like a Plus or a minus right if we multiply like a positive right if we multiply like a positive number it doesn't affect like a plus or number it doesn't affect like a plus or minus minus so that's why when we find the negative so that's why when we find the negative number we multiply minus one and the number we multiply minus one and the Divas we get like a Divas we get like a number like a number like a um like a from positive to negative or um like a from positive to negative or negative to positive negative to positive so let's begin so let's begin um first of all we find the negative one um first of all we find the negative one so in that case we multiply negative one so in that case we multiply negative one to sine variable so now sine variable is to sine variable so now sine variable is -1 and then move next we find the minus two so this is a negative number so we should multiply minus one two assign variables so now a sign variable is one in the move next again we find the minus three so negative number so we should multiply minus one so now minus one and I move next we find that minus four so we should multiply minus one so now sine is one and move next so 3 is a positive number so we don't do anything for sine variable and uh move next we find two so this is a positive number we don't do anything we'll be next we find one so positive number we don't do anything and then finish iteration and then all we have to do is just return sign variable and then one more thing um if we have zero in input array we should immediately return zero right so that's a mathematics yeah so that is a basic idea to solve a description without being said let's get into the code okay so let's write the code code is very easy so sine initialize sine always minus one and start looping for n in nums and if in the case we immediately written zero in the case we immediately written zero and the if n is less than zero and the if n is less than zero in the case in the case um um multiply minus one to sign variable so multiply minus one to sign variable so in Python asterisk equal minus one in Python asterisk equal minus one and then after that and then after that just return sign yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be called out of n where n is the length of input array so this is a because this is called iterate over entire array once so that's why I ordered so space complexity is o1 because the amount of extra memory used by algorithm does not depends on the size of input array so it only use a constant amount of memory to store sign variable so that's why order of one yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I will see you in the next
2024-03-22 17:39:06
1,822
https://i.ytimg.com/vi_w…xresdefault.webp
Sign of the Product of an Array - LeetCode #1822 - Python, JavaScript, Java, C++
_uz30nQEoPw
hey hey everybody this is larry just me going with q3 of the weekly contest 233 going with q3 of the weekly contest 233 uh maximum value at a given index in a uh maximum value at a given index in a bounded array bounded array um so this is a binary search problem i um so this is a binary search problem i had a lot of struggles of this mostly had a lot of struggles of this mostly because of a typo that i didn't catch because of a typo that i didn't catch uh and also i had some debugging code uh and also i had some debugging code that i actually left in the submission that i actually left in the submission whoopsy daisies um as you can see but whoopsy daisies um as you can see but yeah hit the like button hit the yeah hit the like button hit the subscribe button join me subscribe button join me on discord let me know what you think on discord let me know what you think about this farm it's tricky it's hard about this farm it's tricky it's hard it's it's it's fun um but yeah um it's fun um but yeah um so basically the idea is that and i so basically the idea is that and i actually misread this problem a bit all actually misread this problem a bit all during the contest i don't know if you during the contest i don't know if you have the same have the same but uh but i thought that um this thing but uh but i thought that um this thing i thought that it had to be um exactly i thought that it had to be um exactly one so what i mean one so what i mean is that i thought that it would um i thought like it could be a step ladder i thought like it could be a step ladder which makes it really harder which makes it really harder um but because it doesn't it basically um but because it doesn't it basically is a strategy right i is a strategy right i end up doing this binary search and what end up doing this binary search and what happens happens with this binary search is that there's with this binary search is that there's a greedy algorithm for a greedy algorithm for let's say you have an answer and you're let's say you have an answer and you're trying to figure out if there's a greedy trying to figure out if there's a greedy way of doing it way of doing it and the answer is that okay jeff um you and the answer is that okay jeff um you know let's say you have some index know let's say you have some index um you know you let's say you you have um you know you let's say you you have some some index like here and you know you have index like here and you know you have you know numbers to the left numbers to you know numbers to the left numbers to the right and you try x is equal to 20 the right and you try x is equal to 20 right well what happens is that right well what happens is that uh if x is 20 then by definition the uh if x is 20 then by definition the left left let's just focus on the right side for let's just focus on the right side for now um it's the same to the left now um it's the same to the left but you have to look at 20. okay 20 is but you have to look at 20. okay 20 is too big but um too big but um okay fine let's just join anyway 19 in okay fine let's just join anyway 19 in 18 18 17 dot dot dot all the way down to one 17 dot dot dot all the way down to one and then it's just one and then it's just one one one one one one one one right so one one one one one one one right so that's basically the minimum that you that's basically the minimum that you can do can do um and the idea here is that um and the idea here is that um if if and you know and you do the um if if and you know and you do the left left side as well the idea is that okay let's side as well the idea is that okay let's say you have a max sum say you have a max sum that is really big really big um then that is really big really big um then can you can you salvage using this right um and the salvage using this right um and the answer is that answer is that you can always add numbers to the right you can always add numbers to the right or left or left to to meet max sum you can do it you to to meet max sum you can do it you know you then a lot of different ways know you then a lot of different ways you could even make you know you could even make you know um you could do 20 21 22. um you could do 20 21 22. you know whatever right all the way to you know whatever right all the way to max sum i don't know max sum i don't know some numbers so that it adds up um and some numbers so that it adds up um and you can always do this you can always do this so that um so that um because it could be you know you can because it could be you know you can imagine this to be a bigger number and imagine this to be a bigger number and then then on another thing and then it adds on another thing and then it adds together right so that's the together right so that's the general idea um and general idea um and and conversely though if if this number and conversely though if if this number you know if this number is really small you know if this number is really small or at least really small compared to our or at least really small compared to our sum sum uh then it you cannot um you cannot uh then it you cannot um you cannot reach max sum that's the only impossible reach max sum that's the only impossible case because case because there's no wiggle room right you cannot there's no wiggle room right you cannot decrea like every number here decrea like every number here is set so that this sum is set so that this sum is the smallest it can be given is the smallest it can be given x is equal to 20. so that's basically x is equal to 20. so that's basically the idea and from that the idea and from that um you you can notice that it is um you you can notice that it is monotonically increasing monotonically increasing uh so it becomes binary search uh so it becomes binary search and this the way that i do it is um and this the way that i do it is um uh yeah and and there's a couple of uh yeah and and there's a couple of mathematical formulas here mathematical formulas here uh but that's basically it this is uh but that's basically it this is binary search if this is good we go to binary search if this is good we go to the left the left uh or so we go to the right we set left uh or so we go to the right we set left as you go to mid otherwise we as you go to mid otherwise we you know narrow the bounce um i'm gonna you know narrow the bounce um i'm gonna do uh do uh i've been getting this request a lot i've been getting this request a lot lately so i'm gonna do a separate binary lately so i'm gonna do a separate binary search search tutorial um so i'm not gonna focus on tutorial um so i'm not gonna focus on this part right now this part right now um let me know in the comments whether um let me know in the comments whether you want to see it you want to see it if you want to see it you know it if you want to see it you know it motivates me a little bit more so hit motivates me a little bit more so hit that like button that like button and leave a comment um but yeah but and leave a comment um but yeah but basically basically these are just all mathematical formulas these are just all mathematical formulas from that point try to up solve it and from that point try to up solve it and derive it if you have time pause the derive it if you have time pause the video if you like video if you like um but yeah but this is just the number um but yeah but this is just the number that of ones that we have on the left that of ones that we have on the left and numbers of ones in the right and and numbers of ones in the right and that's basically what i have extra that's basically what i have extra because they're just ones and we're because they're just ones and we're forced to take those ones forced to take those ones um and then this is just the left count um and then this is just the left count and this is um you know this this and this is um you know this this formula is just you know formula is just you know you know you can imagine one plus two you know you can imagine one plus two plus three plus four plus five plus three plus four plus five dot dot dot that's the formula um and dot dot dot that's the formula um and so that's the format for one part of it so that's the format for one part of it and from start to end and from start to end you know if you if you kind of look at you know if you if you kind of look at um um you know dot dot plus seven plus eight you know dot dot plus seven plus eight um you can think about this as uh um you can think about this as uh you know to do that plus say oh just you know to do that plus say oh just plus four plus four right and then to get from five right and then to get from five to eight this is how you do it you you to eight this is how you do it you you know from five to eight you take the know from five to eight you take the suffix which is from five to eight um or suffix which is from five to eight um or from one to eight from one to eight and then you subtract it from one to and then you subtract it from one to four right so that's basically the idea four right so that's basically the idea behind here you could work out the behind here you could work out the formula you know formula you know at home or later and this is the left at home or later and this is the left side and this is the right side and side and this is the right side and that's pretty much that's pretty much it um and you know uh from here it um and you know uh from here this will have all of log you know like this will have all of log you know like h algorithm where h is the h algorithm where h is the the bound or u say u is to you know the bound or u say u is to you know where u where u is 10 to the 10 apparently um is 10 to the 10 apparently um and and for here you can see that this and and for here you can see that this is o of one is o of one operation more or less um you know operation more or less um you know yeah i mean yeah this is just all yeah i mean yeah this is just all arithmetic and math and this is all arithmetic and math and this is all one so this is going to take all of log one so this is going to take all of log u u times in total um so yeah so this is times in total um so yeah so this is actually independent of the in actually independent of the in kind of in the number of bits i guess kind of in the number of bits i guess but yeah uh that's all i have for this but yeah uh that's all i have for this problem problem let me know what you think and in terms let me know what you think and in terms of space this is all of one because we of space this is all of one because we only have wearables i guess i have to only have wearables i guess i have to mention that explicitly but yeah you mention that explicitly but yeah you could watch me stop it live during the could watch me stop it live during the contest next contest next i had a numerous a lot of silly mistakes i had a numerous a lot of silly mistakes so you know uh call them out see what so you know uh call them out see what you think uh you think uh and yeah let me know uh this was such an and yeah let me know uh this was such an annoying hard problem for me i would annoying hard problem for me i would also say also say that if you struggled uh don't feel so that if you struggled uh don't feel so bad bad because i know that my explanation and because i know that my explanation and other people's explanation and other people's explanation and that's why you watch their videos they that's why you watch their videos they make it seem easy um make it seem easy um but that's why i want to show how i did but that's why i want to show how i did it in the contest it in the contest and i did relatively okay i finished and i did relatively okay i finished 69th 69th um and and i took 20 minutes on this um and and i took 20 minutes on this prom and i prom and i give more 20 like 22 23 minutes because give more 20 like 22 23 minutes because i i took a couple minutes i skipped q3 i i took a couple minutes i skipped q3 and then i came back to it and then i came back to it um so yes so jim though the explanation um so yes so jim though the explanation is is easy this i think this is a hard problem easy this i think this is a hard problem so don't feel so bad and definitely so don't feel so bad and definitely you know work at it and break it down you know work at it and break it down to pieces and yeah look see if you can to pieces and yeah look see if you can learn from my learn from my you know whatever messed up ah silly silly silly silly that was dumb length m where is okay so the thing is less than where is okay so the thing is less than i i and adjacent value is one okay i mean so and adjacent value is one okay i mean so this is always going to be true anyway this is always going to be true anyway as long as it's positive number the sum of the okay okay hmm indexes too i mean this is just math but math environment and maybe binary search maybe i'll come back to it let's let's see if there's a minor type oh i just didn't think it through all the way all right now we have to think about q three my ranking is pretty slow but i am one of the few people who's getting q4 so okay let's think about this this is a weird math problem i'm annoyed about uh maybe not annoyed about per se just um can we do binary search on this i feel can we do binary search on this i feel like it's brian i research like it's brian i research but what does it mean right that means the what does it mean right that means the love love let's say we want to try and answer let's say we want to try and answer that means that the love yeah i spent way too long in q4 yeah i spent way too long in q4 i don't know how to do this one i don't know how to do this one so you have a step function i need paper six numbers oh i misread this i thought this was oh i misread this i thought this was constrained constrained by i no numbers of i can be anything oh then this is much different than what i was thinking okay i've totally misread this uh because it doesn't have to start with i think for some reason i thought you i think for some reason i thought you have to start with one so then now we have to start with one so then now we can do a binary search much can do a binary search much easier that way so we have a stir how do i oh god it's uh i mean i still need a paper because i'm bad at this so this should have been a tip away so this should have been a tip away because they're indexed once so because they're indexed once so let's see what does three look like right okay we what does three look like right okay we number i has to be a positive number so number i has to be a positive number so it's at least it's at least one but it could actually so we just one but it could actually so we just have have okay so it is binary search i think okay so it is binary search i think um so you just have decrementing all the um so you just have decrementing all the way to once in the left and the right way to once in the left and the right and then and all the way to and then and all the way to once left um good enough i also for some reason thought that this has to be one and not zero or one so i was thinking about step that i i should stop explaining this self default but uh okay the end is inside then um okay it has to be positive i messed that up it has to be positive i messed that up before if this we want the maximum so if this if this we want the maximum so if this is is good then b1 left is equal to good then b1 left is equal to else y is equal to mid minus one left is equal to index left is equal to index and y is equal to n minus index minus and y is equal to n minus index minus one target um the num the map is hot so the num the map is hot so it's uh plus one or minus one that was fun get how which one it is five times um um now let's just add a function oh this is such an annoying problem oh this is such an annoying problem a lot of people got it so so this is if left if we have zero so this is if left if we have zero numbers then this is just numbers then this is just zero on the left okay that makes sense okay well right minus so right is the number of items okay okay okay i don't i don't know this is this is i don't i don't know this is this is okay so okay so if we have some plus right if we have some plus right some press and i might be off by one greater than max sum this is the minimal greater than max sum this is the minimal thing and we return first thing and we return first otherwise we return true maybe because otherwise we return true maybe because if it's so we can always go up maybe i'm off by one though i don't know this is so awkward i don't think i mean this is already this is still not right but um 20 left let's see right see extra okay let's at least take a quick look uh just these numbers are ridiculously big so let's do a for loop to sing okay so if the max number is one okay so if the max number is one the left c is negative one which is the left c is negative one which is probably not what we want what are the inputs four so for index two and max six of six uh if the first number is one then maybe this is then we and we want this to that means that we and we want this to that means that we want this to be want this to be zero so this means this should not be negative one for sure that's just awkward but if this is one this should ideally for when i return negative one so that's for when i return negative one so that's awkward [Music] okay so if okay so if i can't focus this is tough i can't focus this is tough um okay so let's say we're index two the two numbers to the left we start at one so this actually should return zero numbers um so how do i so how do i force that to be zero so t so how do i force that to be zero so t c so t because extra would be what is this two minus one two numbers on the left minus one so this is actually just this um and then now we wanna go to what is the starting point now starting point is the number of steps to get to one so the number of steps to get to one so it's t minus left it's t minus left plus one maybe so if left why am i so bad at counting okay um so if t is one then we want to go zero steps to the left so actually we want the min of this and t minus so okay let's say red one why am i so so okay let's say red one why am i so bad at this bad at this red one so then we won red one so then we won to use zero numbers so z okay to use zero numbers so z okay so it's t minus so it's t minus this thing okay i mean this is better but the the okay i mean this is better but the the extra stuff is wrong clearly extra stuff is wrong clearly i don't know how that happened good i don't know how that happened good got the wrong answer because that's just got the wrong answer because that's just weird um okay weird um okay so one two so one two what is the two this was symmetry maybe but that still should be wrong yeah because okay so now i think that's why i had this i already had the t minus left okay so the starting point is t minus left or one right yes why is this wrong right right okay this part is right the extras now okay this part is right the extras now well well maybe well definitely but why is extra wrong uh so in that case we have t minus left so yep left numbers in the right so yep left numbers in the right right um right um okay so if left is zero okay so if left is zero then this is awkward it's actually really awkward why am i so bad at this maybe this was right overall maybe this was right overall uh nope be be we want this to be at least one maybe we want this to be at least one maybe yeah yeah [Music] [Music] there's no numbers to the left then this there's no numbers to the left then this is this should let out to zero is this should let out to zero so left is equal to zero so that's t so left is equal to zero so that's t and this should be zero why is this oh and this should be zero why is this oh no no because left is not equal to zero um so we should go [Music] so so if left is one we go from four to okay now this should be y why am i negative one is here only if this negative one is here only if this is t what another left is one then this would be another left is one then this would be four four three two one okay yeah no that makes three two one okay yeah no that makes sense sense why is this negative one then why is this negative one then do i print something else anywhere do i print something else anywhere because i get confused because i get confused no because i am just very confused oh what because i am just very confused oh what ah that's why because i'm dumb ah that's why because i'm dumb yes okay yes okay i had to dumb it down for myself and print out everything literally okay so this is better and also this has the same issue that's why i mean it may still be wrong but it should be slightly better three and four still okay um so this is now slightly better um okay so one we get the total sum of three is that um it's an array of four elements so the um it's an array of four elements so the answer should be answer should be four so this should be this plus t four so this should be this plus t actually oops no plus t is here i can't believe i i don't know this is i can't believe i i don't know this is but it's gonna take me a long time to but it's gonna take me a long time to debug anyway so i'm gonna yellow submit debug anyway so i'm gonna yellow submit okay good okay good oh my sounds silly like oh my sounds silly like yeah thanks for watching uh let me know yeah thanks for watching uh let me know what you think about this farm it was what you think about this farm it was good good bad i don't know uh this was a bad i don't know uh this was a interesting contest interesting contest uh let me know what you think uh hit the uh let me know what you think uh hit the like button hit the subscribe button like button hit the subscribe button join me on discord join me on discord ask me questions here there wherever you ask me questions here there wherever you like and like and and yeah have a great week have a great and yeah have a great week have a great time uh stay good stay healthy stay well time uh stay good stay healthy stay well and to good mental health i'll see you and to good mental health i'll see you next time bye
2024-03-22 16:03:09
1,802
https://i.ytimg.com/vi/_…axresdefault.jpg
1802. Maximum Value at a Given Index in a Bounded Array (Leetcode Medium)
jnQ91suTcp8
hi guys welcome to algorithms made easy today we will go through the day 31 today we will go through the day 31 problem from july lead coding challenge problem from july lead coding challenge climbing stairs please like the video climbing stairs please like the video and if you are new and if you are new don't forget to subscribe to our channel don't forget to subscribe to our channel so that you never miss any update so that you never miss any update suppose you are climbing a staircase and suppose you are climbing a staircase and it takes n steps to reach to the top it takes n steps to reach to the top each time you can either climb one or each time you can either climb one or two steps so two steps so in how many distinct ways can you climb in how many distinct ways can you climb to the top to the top for example one we can see we have two for example one we can see we have two ways to ways to climb two stairs we either climb one climb two stairs we either climb one stair at a time stair at a time or we climb two stairs at once for or we climb two stairs at once for example two example two we can have three ways to climb three we can have three ways to climb three stairs we can either climb one stair stairs we can either climb one stair at a time or climb two stairs followed at a time or climb two stairs followed by one for the climb one stair followed by one for the climb one stair followed by two by two if we look closely to the pattern we if we look closely to the pattern we observe one can reach observe one can reach ith step in one of the two ways taking a ith step in one of the two ways taking a single step single step from i minus one step or taking a step from i minus one step or taking a step of two from i minus two step so of two from i minus two step so we can say one can reach ith step by we can say one can reach ith step by adding adding the steps from i minus one and i minus the steps from i minus one and i minus two two if you have noticed this is nothing but if you have noticed this is nothing but the fibonacci series the fibonacci series using the previously calculated value is using the previously calculated value is the concept of dynamic programming the concept of dynamic programming let's see it with an example let's take let's see it with an example let's take ns5 ns5 initially we know we can climb one stair initially we know we can climb one stair in one way only in one way only while to climb two steps we can use while to climb two steps we can use either of these two ways shown either of these two ways shown now we can make use of the previous two now we can make use of the previous two values to calculate the next value values to calculate the next value so number of ways to climb three steps so number of ways to climb three steps will be the addition of previous two will be the addition of previous two that will give us three similarly for that will give us three similarly for the fourth step the addition is five the fourth step the addition is five and for fifth the addition is eight as and for fifth the addition is eight as now we have the value at n equal to five now we have the value at n equal to five we just return it let's summarize we just return it let's summarize this process into an algorithm if n is this process into an algorithm if n is less than 3 less than 3 that is for value 0 1 and 2 we will that is for value 0 1 and 2 we will simply return simply return n or else we will initialize a dp array n or else we will initialize a dp array of length n plus 1. of length n plus 1. store the first three values that is dp store the first three values that is dp of 0 1 and 2 of 0 1 and 2 and then iterate through the rest of dp and then iterate through the rest of dp array and fill it using a formula array and fill it using a formula at the end we return the dp of n the at the end we return the dp of n the time and space complexity for this time and space complexity for this approach is of n approach is of n here's the actual code snippet for the here's the actual code snippet for the method you can also find a link to this method you can also find a link to this code in the description below code in the description below we can reduce the time and space we can reduce the time and space complexity of the solution by applying complexity of the solution by applying the formula to find the nth fibonacci the formula to find the nth fibonacci number number the formula is given as follows you can the formula is given as follows you can find the link to the wikipedia page for find the link to the wikipedia page for a detailed explanation and proof of a detailed explanation and proof of formula in the description below with this formula the time complexity becomes of log n and space complexity becomes one here's the actual code snippet for this method you can also check out the link to all the codes in the description below thanks for watching the video please like share and subscribe to the channel also let me know in the comments what
2024-03-20 11:23:42
70
https://i.ytimg.com/vi_w…xresdefault.webp
Climbing Stairs | Day 31 | [ July LeetCoding Challenge ] [ Leetcode - 70 ] [ 2020 ]
2Q8NnTKkySc
all right I'll be solving continuous sub array sum and I think it's not medium it array sum and I think it's not medium it it's going to be hard the level because it's going to be hard the level because yeah the logic here it's highly yeah the logic here it's highly mathematical so let's take step by step mathematical so let's take step by step and and take for example this so basically the take for example this so basically the question is if you can find a sum question is if you can find a sum a sum of sub array that is a multiple of a sum of sub array that is a multiple of K so K so 6 is a multiple of K rate for example 6 is a multiple of K rate for example all this 42 is a multiple of K all this 42 is a multiple of K if you can find such a sub array then we if you can find such a sub array then we return true return true so let's say starting from the first so let's say starting from the first element to index I let's say 0 to 3. we element to index I let's say 0 to 3. we call it sum I if we Mo if we modulus K call it sum I if we Mo if we modulus K so sum the sum mod K it would be some K so sum the sum mod K it would be some K times some integer like times some integer like K times 1 plus whatever value that's K times 1 plus whatever value that's remaining let's call it mod K1 remaining let's call it mod K1 and same from the first element to index and same from the first element to index J J every mod it by K it would be K times every mod it by K it would be K times some kind of integer value y plus some some kind of integer value y plus some remaining value mod k remaining value mod k divided by three uh mod K2 sorry divided by three uh mod K2 sorry and if this value and this value is the and if this value and this value is the same okay if same okay if if the modulus value is the same then if the modulus value is the same then subtracting subtracting Formula One Formula One and formula 2 we get some I minus some i and formula 2 we get some I minus some i j on the left side j on the left side and this gets canceled because it's the and this gets canceled because it's the same value right and K we just get x same value right and K we just get x minus y in bracket times K which is a minus y in bracket times K which is a constant times k constant times k so effectively the difference is the sum so effectively the difference is the sum of elements between index I and J and of elements between index I and J and the value is a multiple of K which is the value is a multiple of K which is what we're looking for okay that's the pure mathematical explanation so basically what do you want to do is get a get a running sum of this array and the remainders that we get so we're gonna um once we calculate this running sum we're going to divide um we're going to modulus it by K so I think this is what's modulus six yeah so modulus six five model six one one five zero Etc so we get remainder 5 at index 0 and 3 right so this means that these running values right if we minus it so whatever values we have inside that sub array is a multiple of K because here we have said that some I minus some J okay if the modulus is the same that would result and in these in a sum difference in these in a sum difference that is a multiple of K that is a multiple of K okay so if uh index 3 0 1 2 3 35 minus okay so if uh index 3 0 1 2 3 35 minus 23 that's 12 right so um the summary in between it has a value that uh that is a constant of K so that's what we're looking for and we have to um consider a edge case should we just uh run it first okay so should we just uh run it first okay so not considering the edge case first so not considering the edge case first so in future okay and for okay and for and it's I equals zero and it's I equals zero I less than non-stop length I less than non-stop length Plus Plus okay equals zero so remember we're gonna equals zero so remember we're gonna add up add up our values our values okay and we're gonna model set by K okay and if oh and we're gonna get whatever value um map.get so basically if we miss certain so basically if we miss certain condition condition and else what we are storing in our map and else what we are storing in our map is is the running sum which was the modulus of K okay um the running Sun and we're storing the modulus of the running sum and the index in the map and if so if we have not seen such a and if so if we have not seen such a index index that has the same modulus value that has the same modulus value then we just put that modulus value and then we just put that modulus value and that index that index but if we have seen that modulus value but if we have seen that modulus value somewhere before so if oh no so if we have not seen such an oh no so if we have not seen such an index um then we know that oh then we just put it but if there's such an index that oh sorry then and if so sub array has to be a length of two or more right so I minus per has to be greater than one um um and else if we have and else if we have done everything done everything and then we know it's false okay that works so just I'll come I'll cover the edge case first so the edge case is when the running sum is exactly equal to the multiple of K then after we calculate the modulus of K running some becomes zero right because it's exactly equal to n times k so actually if we try to get a map dot get zero actually we don't have such a value we don't have such yeah a key or a value set so that's why we have to add um 0 and -1 to handle this case and it's value -1 because salary has to be at least two so I like for example I is like uh one and one minus minus one that's two right one plus one so that's that means that it's true so yeah it's I don't think it's medium it's highly highly mathematical and we use a double bracelet initialization you can just uh look at this um um do it but put do it but put 0 and 0 and -1 -1 okay and we do it okay yeah so this question is really not medium at all I think the mathematical Logic Let me just summarize it okay so we're gonna add the running sum with the values in our array and calculate the modulus of the running sum modulus it by K and if we found the same modulus somewhere in two indexes and if those indexes difference is greater than one then it can form a sub array and this mathematical logic is when there's a difference between this and when modulus is the same like five oh where is it yeah five equals five then there must be a difference the difference would be the sum of elements and between I and J and that difference is also the value that also proves that value is a multiple of K so this is a constant of K so basically if the models is the same then we know that the difference in some would uh mean that it's a modulus of K so yeah the logic is first oh yeah I didn't get it at first I took quite a while to understand it but that's all and I'll see you guys next
2024-03-22 16:42:02
523
https://i.ytimg.com/vi_w…c/sddefault.webp
Leetcode 523 Continuous Subarray Sum
yhCCsfonQ0g
[Music] [Applause] [Applause] [Music] so [Music] [Music] [Music] foreign foreign [Music] [Music] [Music] um [Music] [Music] [Music] so [Music] so me so so [Music] oh hmm [Music] [Music]
2024-03-25 11:27:20
1,870
https://i.ytimg.com/vi/y…0g/sddefault.jpg
1870. Minimum Speed to Arrive on Time Binary Search Leetcode Weekly Contest Medium Problem (IITG)
phNDYf1xzco
okay guys let's solve top K frequent elements number 347 on leak code so elements number 347 on leak code so given an integer array of nums and given an integer array of nums and another integer K we need to return the another integer K we need to return the K most frequent elements and you may K most frequent elements and you may return the answer in any order so that's return the answer in any order so that's pretty simple it's just the top K most pretty simple it's just the top K most occurring elements so for example with occurring elements so for example with the numbers of 1 1 1 2 2 and three well the numbers of 1 1 1 2 2 and three well we know that one occurs the most at we know that one occurs the most at three times two occurs the second most three times two occurs the second most at two times we just want the top two at two times we just want the top two and so we can return one two or two one and so we can return one two or two one is the same answer and of course if you is the same answer and of course if you had just one number and you wanted the had just one number and you wanted the top one well then that's going to be the top one well then that's going to be the same number it's actually guaranteed same number it's actually guaranteed that the answer is going to be unique so that the answer is going to be unique so if you had three 1es two twos and we'll if you had three 1es two twos and we'll say two 3es with k equals 2 well that's say two 3es with k equals 2 well that's a scenario you wouldn't have because you a scenario you wouldn't have because you would run into three ones you would want would run into three ones you would want to have the one there but then between to have the one there but then between the two twos and two threes you don't the two twos and two threes you don't know which one you want to pick well know which one you want to pick well that's not a scenario you would have so that's not a scenario you would have so the first example that would come to my the first example that would come to my mind is getting a dictionary of the mind is getting a dictionary of the frequency so we'd have well one there's frequency so we'd have well one there's going to be two of those for all of the going to be two of those for all of the twos there's going to be three of those twos there's going to be three of those and for all the threes there is going to and for all the threes there is going to be four of those so now that we have be four of those so now that we have this frequency dictionary we can this frequency dictionary we can basically just sort it by its values basically just sort it by its values because we want the highest frequencies because we want the highest frequencies so for example if we sorted that in so for example if we sorted that in descending order by the values we would descending order by the values we would have Well we'd have three we have four have Well we'd have three we have four of those we'd have two we have three of of those we'd have two we have three of those and at the end we'd have one and those and at the end we'd have one and two of those so now that we've sorted two of those so now that we've sorted This Bites values we just need to pick This Bites values we just need to pick up the top two things at the beginning up the top two things at the beginning that's going to bring us three and two that's going to bring us three and two and that would be a final answer so the and that would be a final answer so the runtime of this would be while getting runtime of this would be while getting this step getting the counter that's this step getting the counter that's just going to be o of n we're just just going to be o of n we're just adding to a hashmap while going through adding to a hashmap while going through the array and then the other step of the array and then the other step of sorting it well we know sorting anything sorting it well we know sorting anything is going to be Big O of n log n and n in is going to be Big O of n log n and n in this case is basically the same n as the this case is basically the same n as the array because if you had all unique array because if you had all unique elements if this was 1 2 3 for 5 6 7 8 elements if this was 1 2 3 for 5 6 7 8 well you'd be sorting that many things well you'd be sorting that many things and so this would be an O of n log n and so this would be an O of n log n answer it turns out we can use a heap to answer it turns out we can use a heap to get an answer of n log K where again K get an answer of n log K where again K is the number of things you need to pick is the number of things you need to pick up because if you use a heap we can up because if you use a heap we can store up to K things in the Heap and so store up to K things in the Heap and so it's going to be a log of K interaction it's going to be a log of K interaction to move around the objects in that heap to move around the objects in that heap if you take an element out of it that is if you take an element out of it that is going to be log of K and if you put an going to be log of K and if you put an element back into it that will also be element back into it that will also be log of K so to show you that answer we log of K so to show you that answer we would actually use a Min Heap okay so it would actually use a Min Heap okay so it stores the minimum element so to get the stores the minimum element so to get the Heap we would actually need that same Heap we would actually need that same dictionary from before of the dictionary from before of the frequencies so we'd again have one two frequencies so we'd again have one two we'd have two of three and we would have we'd have two of three and we would have three there's four of those after we three there's four of those after we have that these are now basically have that these are now basically topples of the frequency and the number topples of the frequency and the number that exists so we don't want to sort that exists so we don't want to sort this thing we'll just go through its this thing we'll just go through its keys and values so here we would get a keys and values so here we would get a tupple two and one we would put the tupple two and one we would put the value first because we we want the Heap value first because we we want the Heap to be organized by the minimum frequency to be organized by the minimum frequency okay so if we put 21 onto this Heap okay so if we put 21 onto this Heap thing okay this is just going to be my thing okay this is just going to be my Heap over here it's going to organize it Heap over here it's going to organize it by the minimum frequency the first item by the minimum frequency the first item in this Tuple and then if the in this Tuple and then if the frequencies were the same it would then frequencies were the same it would then organize it by this but that doesn't organize it by this but that doesn't really matter now the point of our Heap really matter now the point of our Heap is to hold the K most frequent elements is to hold the K most frequent elements on here and it's always going to have on here and it's always going to have the minimum frequency at the top since the minimum frequency at the top since the size of the Heap here the Heap is the size of the Heap here the Heap is just one element well if we look at 2 just one element well if we look at 2 three we'd have the topple of 32 we're three we'd have the topple of 32 we're just going to immediately put that on just going to immediately put that on the Heap cuz we want it to have the K the Heap cuz we want it to have the K most frequent and this is going to be a most frequent and this is going to be a log of K interaction with the Heap we'd log of K interaction with the Heap we'd have 32 here and 21 is going to be above have 32 here and 21 is going to be above it because this has a smaller frequency it because this has a smaller frequency than three okay now things get than three okay now things get interesting with this tupple cuz we'd interesting with this tupple cuz we'd have we have four threes that's the have we have four threes that's the highest frequency we want this in the highest frequency we want this in the Heap and we'd say Boop put it in the Heap and we'd say Boop put it in the Heap that is a log K interaction and we Heap that is a log K interaction and we have four and three that's going to be have four and three that's going to be at the very bottom and then we need to at the very bottom and then we need to pop this off so this is basically a heap pop this off so this is basically a heap push pop operation we push it on and push pop operation we push it on and then we pop off the topmost so that gets then we pop off the topmost so that gets popped off we don't really care about popped off we don't really care about that and we are through the array and that and we are through the array and notice that we have the things that we notice that we have the things that we want here because remember the frequency want here because remember the frequency is the first thing the keys are over is the first thing the keys are over here we wanted the answer to be two and here we wanted the answer to be two and three and so that is our answer so three and so that is our answer so that's one way to do it which is using a that's one way to do it which is using a Min Heap there's actually another Min Heap there's actually another solution where you could use a Max Heap solution where you could use a Max Heap and that is going to be an operation of and that is going to be an operation of n because we're going to go through n n because we're going to go through n times putting stuff potentially on the times putting stuff potentially on the Heap and N times we are going to do at Heap and N times we are going to do at most a log K interaction because we're most a log K interaction because we're going to have K things on the Heap now going to have K things on the Heap now you might be wondering why this is even you might be wondering why this is even any better because n log n and n log K any better because n log n and n log K are very similar it's still n log are very similar it's still n log something except if you can assume that something except if you can assume that K is significantly smaller than n which K is significantly smaller than n which is actually kind of safe because if you is actually kind of safe because if you had a million elements in here you're had a million elements in here you're probably not going to have K as like a probably not going to have K as like a million if K is even just like 10% of million if K is even just like 10% of what n is you're probably going to ask what n is you're probably going to ask the question of like what's the topmost the question of like what's the topmost element what are the two most top what element what are the two most top what are the three most top you can kind of are the three most top you can kind of make that Assumption of course in the make that Assumption of course in the very worst nlog n and nlog K are the very worst nlog n and nlog K are the same but still you would kind of prefer same but still you would kind of prefer n log K although it turns out there's n log K although it turns out there's actually a big O of n solution so first actually a big O of n solution so first I want to show you the Heap solution in I want to show you the Heap solution in code and then we'll come back and do the code and then we'll come back and do the o n answer so for the Heap solution o n answer so for the Heap solution we're going to need two Li we definitely we're going to need two Li we definitely need to import Heap Q in Python that's need to import Heap Q in Python that's going to let us use a Min Heap and we going to let us use a Min Heap and we are also going to do from collections are also going to do from collections we'll import counter which just makes we'll import counter which just makes getting a count of the elements as a getting a count of the elements as a dictionary a little bit faster so we'll dictionary a little bit faster so we'll immediately get a counter which is equal immediately get a counter which is equal to a counter with a Capital C of the to a counter with a Capital C of the nums so that just gets a count of all nums so that just gets a count of all the elements and then we will get a heap the elements and then we will get a heap is initialized as an empty list okay so is initialized as an empty list okay so then what we can do is save for each key then what we can do is save for each key and vow in the counter. items we know and vow in the counter. items we know that the key is going to be the number that the key is going to be the number and the value is going to be its and the value is going to be its frequency and we can just say if the frequency and we can just say if the length of the Heap is actually less than length of the Heap is actually less than K many things well then we can do a heap K many things well then we can do a heap q. Heap push so we don't need to worry q. Heap push so we don't need to worry about popping things because we want K about popping things because we want K elements on the Heap we can just do a elements on the Heap we can just do a heap push with you give it the Heap as heap push with you give it the Heap as the first argument and then we put the the first argument and then we put the Val and the key okay cuz we want it Val and the key okay cuz we want it organized by the minimum frequency which organized by the minimum frequency which is the value and we also want the key is the value and we also want the key which is the number stored in it as well which is the number stored in it as well and then otherwise at this stage the and then otherwise at this stage the Heap must be exactly K things because Heap must be exactly K things because we're only going to let K things in we're only going to let K things in there due to this statement here we do there due to this statement here we do Heap q. Heap push pop I know it looks Heap q. Heap push pop I know it looks kind of funny but we push something on kind of funny but we push something on and we immediately pop it off we give it and we immediately pop it off we give it the Heap and it's the same thing it's the Heap and it's the same thing it's going to be the vow in the key even if going to be the vow in the key even if that vow or its frequency is very very that vow or its frequency is very very small it's still going to try and put small it's still going to try and put that on the Heap and it's just going to that on the Heap and it's just going to immediately pop it off and if this TPP immediately pop it off and if this TPP did belong we had a very high frequency did belong we had a very high frequency we put that at the bottom of this and we put that at the bottom of this and then it's going to pop off whatever that then it's going to pop off whatever that minimum was at this stage all of the minimum was at this stage all of the stuff we need is stored in the Heap and stuff we need is stored in the Heap and that's actually just a python list you that's actually just a python list you interact with it with the heapq library interact with it with the heapq library but it's still just a python list and so but it's still just a python list and so we can return the list of H at one for H we can return the list of H at one for H in the Heap we're just going through and in the Heap we're just going through and getting all of the value and key tles getting all of the value and key tles and the thing we want is the key that's and the thing we want is the key that's the number itself and this is going to the number itself and this is going to be K things because we're going through be K things because we're going through the entire Heap and the Heap is always the entire Heap and the Heap is always going to have at least after it's done going to have at least after it's done this part it's going to have K many this part it's going to have K many things so if you were to submit that things so if you were to submit that that actually is going to work and we that actually is going to work and we would write down that the time would write down that the time complexity well it's n because we're complexity well it's n because we're going through we're getting a counter going through we're getting a counter but that's actually going to be but that's actually going to be dominated by we're going to go through dominated by we're going to go through the counter so that's and many things the counter so that's and many things potentially what are we going to do at potentially what are we going to do at each step we're going to do at most a each step we're going to do at most a log K interaction there's K many things log K interaction there's K many things in the Heap it's a log to push it's a in the Heap it's a log to push it's a log to pop making it also a log to push log to pop making it also a log to push popop and so we'll do o of n * log K is popop and so we'll do o of n * log K is going to be the time complexity for that going to be the time complexity for that answer and the amount of things we'll answer and the amount of things we'll store while we're storing potentially o store while we're storing potentially o of n we're definitely storing o of K of n we're definitely storing o of K except n is going to be bigger than K except n is going to be bigger than K and so we'd say that the space and so we'd say that the space complexity is dominated by just o of n complexity is dominated by just o of n okay but that was the N log K answer and okay but that was the N log K answer and as we said we can get an O of n answer as we said we can get an O of n answer basically the idea is that of all the basically the idea is that of all the elements here well if this is length if elements here well if this is length if this has a length of nine there's no way this has a length of nine there's no way that any element in here could appear that any element in here could appear more than nine times once twice up to more than nine times once twice up to nine many times you could have just the nine many times you could have just the same element every single time but same element every single time but there's no way that that's going to be there's no way that that's going to be bigger than the length itself so since bigger than the length itself so since we have a minimum number of times which we have a minimum number of times which is going to be well zero times or one is going to be well zero times or one time either is fine you could have at time either is fine you could have at most nine many times well then we can most nine many times well then we can make an array where the index is make an array where the index is actually the frequency or the number of actually the frequency or the number of times that something is going to occur times that something is going to occur and we don't really need these spots but and we don't really need these spots but they would exist so we get our they would exist so we get our frequencies and we see well one appears frequencies and we see well one appears two times and so we would put one at the two times and so we would put one at the frequency of two okay remember this is frequency of two okay remember this is the frequency so we're going to put the the frequency so we're going to put the list of one here because multiple list of one here because multiple elements could have the same frequency elements could have the same frequency and then we also have two and three here and then we also have two and three here so we'd say okay well at the three so we'd say okay well at the three frequency we're going to have the number frequency we're going to have the number of two and at the four frequency that is of two and at the four frequency that is going to have the number of three and going to have the number of three and notice something very interesting if you notice something very interesting if you go backwards through the array from the go backwards through the array from the end well you're going to have this end well you're going to have this organized by the top elements because organized by the top elements because this is the frequency you'll have the this is the frequency you'll have the three first and then you'll have the two three first and then you'll have the two and you'd have whatever you'd have over and you'd have whatever you'd have over this way but we only want the top K from this way but we only want the top K from going this way through the array and going this way through the array and just to be clear why we actually need just to be clear why we actually need these as lists we'd have four threes these as lists we'd have four threes suppose we also had four fours well then suppose we also had four fours well then in the four spot we would also need this in the four spot we would also need this to have three and four in the four to have three and four in the four frequency three we have four threes and frequency three we have four threes and we also have four we have four fours so we also have four we have four fours so they both belong there so we'd go they both belong there so we'd go backwards through the array and we'd backwards through the array and we'd have like some new array where we're have like some new array where we're picking stuff up we'll get three we'll picking stuff up we'll get three we'll get four in there and you do this up get four in there and you do this up until K which is actually two and so until K which is actually two and so this would be our answer so the code to this would be our answer so the code to do this is actually pretty cool we'll do this is actually pretty cool we'll just get n is the length of the numbers just get n is the length of the numbers and then we'll again we'll import our and then we'll again we'll import our counter so we'll do from collections counter so we'll do from collections we'll import Port counter and then we we'll import Port counter and then we will get a counter is equal to a counter will get a counter is equal to a counter of all the numbers that's again just the of all the numbers that's again just the keys are the number and the value is the keys are the number and the value is the frequency and we're going to get these frequency and we're going to get these things I'm going to call that array things I'm going to call that array basically buckets cuz it's kind of like basically buckets cuz it's kind of like a bucket sort if you know what that is a bucket sort if you know what that is if not really don't worry about it so if not really don't worry about it so we're going to set them all just to be we're going to set them all just to be zeros at first so we're going to get n zeros at first so we're going to get n plus one of these things what this is is plus one of these things what this is is basically saying if we had the array of basically saying if we had the array of we'll say 1 2 and three well then the we'll say 1 2 and three well then the thing that we would produce here 0 0 0 thing that we would produce here 0 0 0 and Zer okay it's n + 1 3 + 1 is 4 so and Zer okay it's n + 1 3 + 1 is 4 so they're all going to be initialized to they're all going to be initialized to zero just saying that we don't have any zero just saying that we don't have any stuff there and this frequency is for stuff there and this frequency is for things that occur zero times we'll things that occur zero times we'll actually never use that it just helps actually never use that it just helps the math this is for stuff that occurs the math this is for stuff that occurs once this is for stuff that occurs twice once this is for stuff that occurs twice and this is if you had something that and this is if you had something that occurred all three times so then similar occurred all three times so then similar to before we'll get for each number and to before we'll get for each number and the frequency that we have in the the frequency that we have in the counter. items and we'll say hey if the counter. items and we'll say hey if the buckets at the frequency okay remember buckets at the frequency okay remember the frequency is the index so if the the frequency is the index so if the bucket's at the frequency if that is bucket's at the frequency if that is still equal to is zero we don't have still equal to is zero we don't have anything there yet but we want to place anything there yet but we want to place the number there because it has this the number there because it has this frequency so we'll set buckets add the frequency so we'll set buckets add the frequency we'll make that equal to the frequency we'll make that equal to the number but the list of that number number but the list of that number otherwise if it wasn't a zero that means otherwise if it wasn't a zero that means we've already done this because we we've already done this because we already have a list of you know one already have a list of you know one number there or two numbers there and so number there or two numbers there and so on and so we would need to do buckets on and so we would need to do buckets add frequency same thing except it's a add frequency same thing except it's a list so we will append with the number list so we will append with the number We'll add one more number that has that We'll add one more number that has that frequency okay now after we've built up frequency okay now after we've built up this buckets array we just need to go this buckets array we just need to go backwards through it and pick up what we backwards through it and pick up what we want so we'll get a return list of stuff want so we'll get a return list of stuff that we want and we'll say go backwards that we want and we'll say go backwards through the array you do that by saying through the array you do that by saying for I in the range of so start at n for I in the range of so start at n inclusive because again we have n+ one inclusive because again we have n+ one things you can think about the last things you can think about the last index is actually n so n inclusive we go index is actually n so n inclusive we go down to -1 basically this is exclusive down to -1 basically this is exclusive so it actually goes down to zero and so it actually goes down to zero and we'll do it as a step of going down one we'll do it as a step of going down one now we can say if the buckets at I if now we can say if the buckets at I if that is not equal to zero okay that that is not equal to zero okay that means it is a list and it's stuff that means it is a list and it's stuff that we want to pick up so we will return. we want to pick up so we will return. extend not sure if you've seen extend extend not sure if you've seen extend before but basically if you had say a before but basically if you had say a list of just one two and you called do list of just one two and you called do extend on that so if you extended that extend on that so if you extended that of say four five and so that would make of say four five and so that would make it the list of 1 two 4 five okay so it the list of 1 two 4 five okay so that's extending the list okay so we that's extending the list okay so we want to return. extend with buckets at I want to return. extend with buckets at I and yes you want to pick up all of the and yes you want to pick up all of the stuff that's in there now because we stuff that's in there now because we have the case over here that it's have the case over here that it's guaranteed that the answer is unique you guaranteed that the answer is unique you can pick up all of what's in buckets at can pick up all of what's in buckets at I cuz you're never going to hit K I cuz you're never going to hit K elements in the middle of this bucket elements in the middle of this bucket okay it's going to be either before or okay it's going to be either before or after one of these buckets because the after one of these buckets because the answer is going to be unique so if the answer is going to be unique so if the length of return is equal to K if we've length of return is equal to K if we've picked up K many things then we can just picked up K many things then we can just immediately well we'll just do a break immediately well we'll just do a break so that it's pretty clean we will return so that it's pretty clean we will return R out here and if we were to submit that R out here and if we were to submit that then that would work just fine okay so then that would work just fine okay so as we said this has a Time complexity of as we said this has a Time complexity of Big O of n why is that well we pick up Big O of n why is that well we pick up the counter in linear time we can go the counter in linear time we can go through all the stuff in linear time and through all the stuff in linear time and all of this is a constant operation and all of this is a constant operation and then we just go backwards through the then we just go backwards through the array and we pick up at most K things so array and we pick up at most K things so the time is going to be a big O of N and the time is going to be a big O of N and the space complexity well we are going the space complexity well we are going to store maybe N Things over here we'll to store maybe N Things over here we'll have end things in the bucket and that's have end things in the bucket and that's really all we're going to store here we really all we're going to store here we also have return but that's just going also have return but that's just going to be at most pay things and so the to be at most pay things and so the space is going to be dominated by o n so space is going to be dominated by o n so that's our answer and that's the fastest that's our answer and that's the fastest possible algorithm I hope this was possible algorithm I hope this was helpful guys and have a great day
2024-03-24 11:08:33
347
https://i.ytimg.com/vi_w…xresdefault.webp
Top K Frequent Elements - Leetcode 347 - Explanation + Python Solution
2Gh5WPjAgJk
hey guys welcome to algorithms made easy i am khushboo i am khushboo and in this video we are going to see and in this video we are going to see the question binary tree cameras the question binary tree cameras given a binary tree we install cameras given a binary tree we install cameras on node of that tree on node of that tree each camera at a node can monitor its each camera at a node can monitor its parent parent itself and its immediate children itself and its immediate children calculate the minimum number of cameras calculate the minimum number of cameras needed to monitor needed to monitor all the nodes of the tree so here we are all the nodes of the tree so here we are given a few examples given a few examples in the example one if we place the in the example one if we place the camera in the middle camera in the middle node it would be able to monitor both node it would be able to monitor both its children and parent and so its children and parent and so with a single camera we can monitor the with a single camera we can monitor the whole tree in the second example we whole tree in the second example we would need two cameras to monitor would need two cameras to monitor all the nodes the note attached with all the nodes the note attached with this question this question says that the number of nodes would be says that the number of nodes would be in the range of 2000 in the range of 2000 and every node has a value of 0. so we and every node has a value of 0. so we are not considering the values of the are not considering the values of the nodes over here we only need to know nodes over here we only need to know where we want to place the camera so where we want to place the camera so that that all the nodes can be covered so let's all the nodes can be covered so let's see see how we can solve this question so let's how we can solve this question so let's take this tree considering that all the take this tree considering that all the nodes have value as nodes have value as 0. now let's start from the top and see 0. now let's start from the top and see how many cameras would be required if we how many cameras would be required if we start from top we know that the parent start from top we know that the parent is going to be covered so we don't put is going to be covered so we don't put the camera in the parent but we'll put the camera in the parent but we'll put it in the it in the lower notes so over here we put both the lower notes so over here we put both the cameras and so cameras and so these nodes are covered after that these these nodes are covered after that these are uncovered so we'll put the camera are uncovered so we'll put the camera over here over here and so in this case we are going to need and so in this case we are going to need five five cameras but is this optimized we can see cameras but is this optimized we can see that we have added cameras in all the that we have added cameras in all the lower levels lower levels and in a tree we know that as we go and in a tree we know that as we go deeper into the tree deeper into the tree the nodes start increasing we have one the nodes start increasing we have one node in the root node in the root then two and then it would be four nodes then two and then it would be four nodes and so on and so on in a case of complete binary tree so we in a case of complete binary tree so we need to need to avoid adding cameras to our leaf nodes avoid adding cameras to our leaf nodes and so what we are going to do is we are and so what we are going to do is we are going to start from the going to start from the bottom so let's see what happens if you bottom so let's see what happens if you start from bottom start from bottom in this particular case so let's put the in this particular case so let's put the cameras in the cameras in the second last level and over here we can second last level and over here we can see that the see that the leaf nodes would be covered with that leaf nodes would be covered with that and the parent of that particular node and the parent of that particular node would also be covered with this camera would also be covered with this camera and with this two cameras we see that we and with this two cameras we see that we are covering a large are covering a large range of nodes now we are left with only range of nodes now we are left with only two nodes two nodes and so we can cover these nodes by and so we can cover these nodes by adding one more camera adding one more camera we can either add a camera at the root we can either add a camera at the root or at this leaf level over here or at this leaf level over here so now you see that instead of five so now you see that instead of five we are only using three cameras when we we are only using three cameras when we started from the lowest level started from the lowest level and that's the intuition behind this and that's the intuition behind this particular problem that we need to start particular problem that we need to start from from the lowest level to reduce the number of the lowest level to reduce the number of cameras that we would require cameras that we would require by not adding the camera at the leaf by not adding the camera at the leaf level which level which have the tendency of having the highest have the tendency of having the highest number of nodes number of nodes now that we know that we are going to now that we know that we are going to start from the bottom let's see start from the bottom let's see how we are going to start so let's take how we are going to start so let's take this particular tree and start from the this particular tree and start from the bottom bottom so we are adding this camera for this so we are adding this camera for this particular node which is particular node which is covering the child and the parent so we covering the child and the parent so we need to store somewhere that need to store somewhere that what are the nodes that are being what are the nodes that are being covered by the camera that i have added covered by the camera that i have added because i do not want those nodes to be because i do not want those nodes to be covered again covered again that is i can ignore those nodes in my that is i can ignore those nodes in my further traversal further traversal and so with this information i can and so with this information i can minimize the number of minimize the number of cameras that i would need now that i cameras that i would need now that i have these nodes covered i'll add a have these nodes covered i'll add a camera over here to cover this camera over here to cover this particular node which was particular node which was uncovered by the camera which is already uncovered by the camera which is already covering its parent node so there is no covering its parent node so there is no chance chance this node could ever be covered if i am this node could ever be covered if i am not adding a camera over here not adding a camera over here so this node would also cover this so this node would also cover this parent node parent node 2 but that is already covered so we need 2 but that is already covered so we need a data structure which would store the a data structure which would store the unique values to mark our covered nodes unique values to mark our covered nodes now going further above we know now going further above we know that we have these two nodes left so i that we have these two nodes left so i am adding a camera over here to cover am adding a camera over here to cover its child and since its child and since it does not have a parent that means it does not have a parent that means this was the last node that we needed to this was the last node that we needed to cover cover and now that we have covered all the and now that we have covered all the nodes i can count how many cameras nodes i can count how many cameras i have added in this process which is i have added in this process which is three three so let's try to code this particular so let's try to code this particular approach out wherein we'll go from approach out wherein we'll go from bottom to top and keep on adding the bottom to top and keep on adding the cameras cameras wherever needed and store all the wherever needed and store all the covered nodes in a data structure covered nodes in a data structure that stores a unique value so over here that stores a unique value so over here first thing that we need first thing that we need is the count of cameras and the second is the count of cameras and the second thing that we need thing that we need is a data structure to store all the is a data structure to store all the covered nodes and that data structure covered nodes and that data structure should store should store unique value so we will take a set of unique value so we will take a set of tree node now let's initialize these data structures initial count would be 0 and this would be new hash set now what i need to do is call the dfs function so i'll call dfs on my root node and its parent being null now why do i need the parent over here i need the parent because i need to cover the parent of that particular node while adding a camera to it so in that case i need to know who was the parent for this particular node and so i'll mark parent of the root as null because it does not have any parent finally just return the cameras over here we can add an initial condition that if my root itself is null i can return 0 because i do not need cameras in that case because i do not have any node in my tree now let us write the dfs function it would be a void function and it is going to take the node and its parent over here i'll check if my node is null if it is null i do not need to do anything but if it is not null then and only then i will be processing the node if the node is not null i am going to go deeper in that tree because i want to start from the very end of the tree so i'll call dfs on left with node as the parent and on its right with node as the parent once i have done this i am on the bottommost node now i need to check whether i need to add a camera over here so that would only be possible if the parent is null and this particular node is not covered so that condition would be if parent is null and my node is uncovered or if any of its so this is the condition wherein i'll be so this is the condition wherein i'll be adding the camera so let's write this so this is the case when we'll encounter the root of the tree which is not covered and the other case is that either of its left or right child are not covered so we need to add the camera over here to cover its left and right now what happens over here with our code is that when we go to the deepest node its child nodes would not be covered because it would not contain the child nodes for the leaf that is the null nodes in the hash set and so we need to add that in my set so i'll do cover dot add null so that i can add the children of my leaf nodes into the covered category so now this code would not go and add the cameras on the leaf node but would start from one level above the leaf nodes now in this case i need to add a camera so i'll increase the count of it and i'll add all of its parent and children into the covered hash set so i'll add the node i'll add its parent i'll add its left and right child and that's it and it's giving a perfect result let's and it's giving a perfect result let's submit this submit this and it got submitted the time complexity and it got submitted the time complexity over here would be o over here would be o of n because we are going to go to each of n because we are going to go to each and every node and every node and the space complexity would also be o and the space complexity would also be o of n because we are taking a of n because we are taking a set to store all the covered nodes and set to store all the covered nodes and the maximum nodes that the cameras would the maximum nodes that the cameras would cover cover is the entire tree now let's see if we is the entire tree now let's see if we can do this without using the set can do this without using the set so in a tree at a time you can have one so in a tree at a time you can have one of the three states of the three states that is either it is not covered by the that is either it is not covered by the camera camera either it has a camera or either it is either it has a camera or either it is covered with a camera but does not have covered with a camera but does not have a camera itself a camera itself for that particular node so these three for that particular node so these three states states can be returned and can be used to find can be returned and can be used to find whether i need to put a camera or not whether i need to put a camera or not for that particular for that particular node so let's see how we can do this and node so let's see how we can do this and we'll we'll try to understand the code itself by try to understand the code itself by doing it doing it the only thing that we need to remember the only thing that we need to remember over here is the three states over here is the three states so i'll be marking the states as 0 so i'll be marking the states as 0 1 and 2 2 wherein i have the camera 1 and 2 2 wherein i have the camera one wherein the node is covered with the one wherein the node is covered with the camera and 0 camera and 0 wherein the node is not covered so i'll wherein the node is not covered so i'll still need still need a variable which would store the number a variable which would store the number of cameras that i'm installing of cameras that i'm installing and i'll need a dfs function and over and i'll need a dfs function and over here i am going to return the state of here i am going to return the state of that particular node that particular node and i'll take the tree node now if and i'll take the tree node now if the node is equal to null which is the node is equal to null which is going to happen for the child node of going to happen for the child node of the leaf node i am going to return the leaf node i am going to return that it is covered by my camera so let's that it is covered by my camera so let's quickly write down what are the states quickly write down what are the states meaning meaning so 2 means has camera one would depict so 2 means has camera one would depict that it is covered with the camera and that it is covered with the camera and 0 means no camera is covering 0 means no camera is covering this node so over here in this null case this node so over here in this null case i am going to say that this node is i am going to say that this node is covered by the camera because i don't covered by the camera because i don't want to start with the leaf node now want to start with the leaf node now since i want to since i want to go to the bottom i'll take dfs of go to the bottom i'll take dfs of node dot left and dfs of node dot node dot left and dfs of node dot right and since it is returning a value right and since it is returning a value i'll take it in left and i'll take it in left and right now i need to check whether i want right now i need to check whether i want to add a camera or not to add a camera or not the camera will only be added if my left the camera will only be added if my left has returned 0 or my right has has returned 0 or my right has returned 0. that is these are not returned 0. that is these are not getting covered by the camera so i'll getting covered by the camera so i'll add a camera over here so that my child add a camera over here so that my child are covered with this camera and so i'll are covered with this camera and so i'll do a cam plus plus do a cam plus plus to add the count in it and i'll return to add the count in it and i'll return 2 because i have added the camera over 2 because i have added the camera over here and this node now here and this node now has a camera otherwise if any of my has a camera otherwise if any of my children node children node has a camera it means that my current has a camera it means that my current node is covered with the camera node is covered with the camera and so i'll be returning one in that and so i'll be returning one in that particular case particular case and so i'll write if left has a camera and so i'll write if left has a camera or right has a camera then or right has a camera then i can return one because this particular i can return one because this particular node is node is covered with the camera or otherwise i covered with the camera or otherwise i can return 0 because this can return 0 because this wasn't covered with the camera over here wasn't covered with the camera over here i'll be i'll be calling dfs on my root node calling dfs on my root node and since it is returning something and since it is returning something let's take it in let's take it in a variable calling it as answer for now a variable calling it as answer for now now now what can i get into answer i can get what can i get into answer i can get either a 0 either a 0 1 or 2. that is whether my root was 1 or 2. that is whether my root was covered with the cameras that i have covered with the cameras that i have attached in the tree attached in the tree what if the root was covered in that what if the root was covered in that case i can simply case i can simply return the number of cameras that i have return the number of cameras that i have added for the tree added for the tree and what if the root wasn't covered in and what if the root wasn't covered in that case that case i need to add a camera over here so i need to add a camera over here so i'll return camera plus 1 so we'll be i'll return camera plus 1 so we'll be returning returning if answer is equal to 0 in that case can if answer is equal to 0 in that case can plus 1 or else cam itself so plus 1 or else cam itself so i can simply write dfs of root instead i can simply write dfs of root instead of this of this answer and this will be going so that's answer and this will be going so that's it let's try to run this code and it's it let's try to run this code and it's giving a perfect result giving a perfect result let's submit this and it got submitted let's submit this and it got submitted the time complexity over here still the time complexity over here still remains of n because we are going to remains of n because we are going to cover cover all the nodes and the space complexity all the nodes and the space complexity for this particular problem would be for this particular problem would be equal to the height of the tree to store equal to the height of the tree to store the recursion stack the recursion stack for the call of dfs function so that's for the call of dfs function so that's it for this video guys i hope you like it for this video guys i hope you like the video and i'll see you in another the video and i'll see you in another one so till then keep learning one so till then keep learning keep coding
2024-03-25 14:06:52
968
https://i.ytimg.com/vi/2…axresdefault.jpg
Binary Tree Cameras | Live Coding with Explanation | Leetcode - 968
iLfiGrvkheE
hello everyone this is yosando today let's talk about lit code yosando today let's talk about lit code 1168 1168 optimized water distribution village if you like my videos please support me by subscribing my channel you can find the code of this program and [Music] the complete code list new video description link below we are given a house in a village we are given a house in a village then basically we want to supply water then basically we want to supply water to other houses let's directly jump into the uh first examples to explain better so here we have three house uh we have uh the cost to uh build the wells for each house so the first one means we build the wales for house one it costs one we build another well for class two because two and also if we don't build wells we can also build the pipes between two house so first elements one two one means if we build the pipes connect house one house two it costs one then if we build the pipes between two and three it was class one so in the end we need to return the minimum total cost to supply the waters to our house so for this example the minimum cost is three um so the best strategy is to build a well in the first house with one cost and connect one two and so to solve these problems we can so to solve these problems we can convert convert the whole problem into a minimum the whole problem into a minimum spanning trees problems spanning trees problems what's a minimum spanning tree this is a what's a minimum spanning tree this is a graph concept so graph concept so this tree is a subset of the edge of this tree is a subset of the edge of connected and connected and on directorygraph that connect all the on directorygraph that connect all the vertex vertex and also without any cycles then after doing that we need to achieve the minimum possible total edge rate so basically this is the uh minimum explanatory concept then how to solve a minimum spiritual problems um so usually we can use a priority queue plus a union fight so this problem is not a typically minimum spanning tree because we have two options like pipes and the wells so here we need to convert problems into a minimum expansion problems by using a so i'm going to show how to convert the so i'm going to show how to convert the problems problems for using the example shows in the for using the example shows in the description so here we given description so here we given three house as well three house as well then we create a new uh virtual node then we create a new uh virtual node zero zero such that we make pipes as such that we make pipes as edge then we want to convert the wells edge then we want to convert the wells and to another edges by using virtual and to another edges by using virtual node so the way we convert rails to the pipes is we think uh generate the pipes to the target node [Music] by using the causing valves for examples if we're given the wells cost is one two two which means we want to connect node one to virtual node as cost 1 something like this and if also for the second one is we connect vertical node 0 to node 2 as cost 2. the same thing for this is means we are connected edge for virtual node 0 to node 3. such that after we convert well into the pipes we put both pipes and the wells edge into a priority queue and sort by the the cost so that we have the priority queue like as follows one two one is the pipes here we swept the last elements caused into into the first one to be compatible with our code later so one two one is still one to one after swap then here means we connect virtual node zero to one and the cost is one which is responding to the first element for wells same thing for the next we connect the virtual node 0 to 2 as cost 2. same thing for this and the 232 is the pipes as this one when we swap the first elements last time instead of the on the same tuple all right so then now we have all the uh edges being put to the priority queue and sort by the cost fundament minimum to the maximum then we need to iterate the edge from the top of priority queue to the end until we union all the notes okay then i i'm going through the whole okay then i i'm going through the whole solution step by step solution step by step so i initial step we don't use so i initial step we don't use any edge yet so any edge yet so we sign the parents we sign the parents for each node is its own parents right for each node is its own parents right so zero parents so zero parents zero one parents one two parents two zero one parents one two parents two three four three three four three here we don't use any edge so the cost here we don't use any edge so the cost is still zero is still zero so next we get the top of the practical edge which is the 2 2 1 so now we're doing union find so of course not 1 and 2 will have same parents we can sign each one so here i assign the two as the common parents for node one and two then we use the edge two and one and it's cost one so next we use the second one in the priority queue we connect zero and one um [Music] since one's parents is already two so we assign zero parent also to two um then two co2 three twos two three then we increase the cost to two uh by using this edge cost so the next one is zero two zero two h uh since zero and the two are all beyond two same trends parents right now actually we won't do anything in the unified step here we still came the same cost so since zero doesn't already be so since zero doesn't already be assigned to two we can assign the assigned to two we can assign the three appearances two so at this step three appearances two so at this step all the nodes have the same parents as all the nodes have the same parents as two two so eventually we will end up here and we so eventually we will end up here and we get our one solution get our one solution uh which cost total cost will be four uh which cost total cost will be four we want you you want to going to we want you you want to going to integrate the rest of the edge here integrate the rest of the edge here um so as you may noticed um so as you may noticed for all those edges have same cost for all those edges have same cost can be uh inserted into the arbitrary can be uh inserted into the arbitrary orders in the priority queue orders in the priority queue so it can happen we so it can happen we visit three two before the zero two visit three two before the zero two three three right because they have same cost right because they have same cost uh in here uh in here we can we will do same thing basically we can we will do same thing basically because two parents is because two parents is is already two so we assign the three is already two so we assign the three depends to two depends to two so here we will obtain the second so here we will obtain the second solution solution they share the same cost so it doesn't they share the same cost so it doesn't matter which one matter which one is going first now is going first now let's see how how these two solutions let's see how how these two solutions will will we're given of the graph of our problems we're given of the graph of our problems so first solutions uh we connect two and so first solutions uh we connect two and one one two and twenty one and zero and the one two and twenty one and zero and the one zero one which means we zero one which means we build a wells for horse one build a wells for horse one um then we don't do anything to we don't um then we don't do anything to we don't connect connect zero and two we connect zero to three zero and two we connect zero to three zero two three okay so right now zero two three okay so right now if this is solutions we are uh building if this is solutions we are uh building a a minimum entry here we connect all the minimum entry here we connect all the vertex vertex by the ads and also we don't have any by the ads and also we don't have any cycles cycles in this graph and we achieve the minimum in this graph and we achieve the minimum cost cost for solution two we connect zero one we for solution two we connect zero one we connect to one connect to one and then eventually we connect two and and then eventually we connect two and three uh three uh we also connect all the vertex uh and we also connect all the vertex uh and this node cycle here this node cycle here so this is a also um acceptable solution so this is a also um acceptable solution all right let's go into the code um so here um i'm assuming the the the length of wells uh is w and the length of pipes is p uh here we have a prior q squared here uh taking a tuple uh first is cost [Music] and upcoming is this the north uh kinetic by the edges uh we got greater operator here's um to make sure our top is the the minimum one make wells to adds by using a virtual make wells to adds by using a virtual node node 0 and we are inserting the priority 0 and we are inserting the priority queue queue uh so this step will take big of w uh so this step will take big of w log w is like we sorted array right log w is like we sorted array right on the second we add in the pipes on the second we add in the pipes also into priority queue here i think i also into priority queue here i think i made a typo here so made a typo here so here should be uh something here should be uh something w plus p log w plus p because right now w plus p log w plus p because right now the particle the particle lens will be the w plus p eventually lens will be the w plus p eventually a serve for loop we a serve for loop we [Music] [Music] put the the parents list we create a put the the parents list we create a paris list here paris list here um yeah the parents are is defined by the private function here um so it's using its own index as parents so next we are going to the the unifying templates um we get the edge from the top of priority queue and we find the two parents um and also doing the path compression here in the help function here um then if the two parent cells that are different we we are using this edge we do n minus minus which means um the total parent numbers are getting equipment by one and we add in the the cost to the total cost so we will finish these loops until we have one common parent here so eventually we'll return the the minimum total cost um so for the total computations we get a computation as uh omega multiply fn and means the uh the total null number sorry so this should be n as well uh it's kind of confusing uh yeah so um and the most we are doing the an iteration right and uh multiply the um the past searching computation so each uh find parents cost a function of n so this should be much greater than the w log w or w plus p log with p in previous then the space we are using then the space we are using our priority queue to store all the edge our priority queue to store all the edge so with the so with the w plus p so w plus p so actually here we also need to pass actually here we also need to pass on the space to start the parents on the space to start the parents uh speaker of n right uh speaker of n right um yeah you can find the the runtime the um yeah you can find the the runtime the memory usage affiliate code here memory usage affiliate code here in the left for this uh solution in the left for this uh solution all right so yeah i think you can find all right so yeah i think you can find the the complete code in the videos below
2024-03-25 18:46:41
1,168
https://i.ytimg.com/vi/i…axresdefault.jpg
Leetcode 1168. Optimize Water Distribution in a Village | C++ | English
uYKn11mHY_k
[Music] [Music] [Music] [Music] foreign [Music] [Music] what [Music] [Applause] [Music] what what [Music]
2024-03-24 11:48:19
378
https://i.ytimg.com/vi/u…axresdefault.jpg
378. Kth Smallest Element in a Sorted Matrix | java solution