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
|
---|---|---|---|---|---|
9lEkqOezpWw | in the given string the words are separated by separated by spaces so we will split the strings by spaces so we will split the strings by white white spaces now we will reverse these words empty words will be ignored and at last we will join them back with spaces between them now let's code the solution we can use the split function to split the string by white spaces this fun function ignores empty strings if any we will then reverse the resulting list and at last we will join the words it let's run the solution it's working see you in the video | 2024-03-21 13:09:50 | 151 | 151. Reverse Words in a String | LeetCode 75 #6 | Array / String |
|
zYPW3n7JoZ4 | hey guys welcome back to another video and today we're going to be solving the leak code question smallest range 2. all right so in this question we're given an area of integers a okay so for each integer a i we need to choose either x equals negative k or x equals k and add that x value to a i and we're only going to do this one time after this process we still we have some area b okay okay so what's going to happen is that we're going to go to our area a which has integers in it we're going to go to each of the elements or values and we're either going to add negative k or we're going to add positive k to it and after this we're going to end up with a completely new area and let's call this b so what we're going to do is we're going to return the smallest possible difference between the maximum value of b and the minimum value of b okay so i think the question is a little bit confusing the way it's worded so let's just go through a simple example so let's go through this example over here so which is a equal to 136 and k is equal to three okay so just ignore whatever is up top and let's just do it from here so a is equal to one comma three comma six and we know that k is equal to three again just ignore the top part sorry okay so over here we have two options okay and let's write down what these options are so we know that our k value is equal to three so at each number okay so at each of the numbers inside of the array we have one of two options so let's go to option one so in option one we're going to be adding the k value which in this case is three and in option two we're going to be subtracting the k value which in this case would be negative three right so what exactly is the main goal of our question over here so the end goal over here is we have to make this operation so either operation one or operation two and after doing it we want to find what is the range between the maximum number and the minimum number so let's take an example right just for the sake of an example let's say we do one plus three so now that gives us a number of four let's do three minus three giving us zero and let's just do six plus three and that gives us a value of 9. so before we calculate what the range over here would be what is the range of the original value so in the uh for the original thing the range over here is going to be the smallest value which is 1 and the maximum value which in this case is six and the difference between them which is six minus one giving us a value of five so in the beginning we have a range of five but now when we did these operations we actually ended up with the range of the smallest value being zero and then nine so nine minus zero giving us the range of nine so obviously a range of nine is square so that's not going to be our ideal solution so hopefully you understood what our main goal over here is and um so i'm not gonna go through how we're finding the solution yet so let's just see what is the answer they got so in this case they had p equals to four six and three okay so they got four so they did one plus three then they got six so they did three plus three and the other value they got was three so that's six minus three okay so this is their new area over here so what is the difference of this area over here so the difference of this area is nothing else but the maximum minus the minimum which is nothing else but three so this over here gives us a difference of three or a range of three and as you can see that is already smaller than what we had originally so in this case we're going to output the difference over here which is three and also make sure we're not outputting the b value here we're only going to be outputting the difference which in this case is three so that over there is the question and hopefully you understood what is uh the main idea behind it and another example let's just say so we have zero and 10. so in this case what they did is it's 0 plus 2 and 10 minus 2 giving us a 2 and 8 and the difference between them is going to be 6 so that's what we output okay so hopefully you understood what the question is asking for and now let's kind of talk about how can we solve this question okay so to understand how we can solve this question let's go back to uh this question here okay the first one so a is equal to 1 3 6 8 12 and 13. so over here we're going to be making an assumption and that assumption is that a is sorted okay so to solve this question we're going to be sorting a beforehand but before we actually go to the actual solution uh let's just understand what's impossible of ways we could solve this question are so at each uh point we have two options and the two options that we have are going to be either plus k or actually let me just change this into plus three minus three let's just make it plus k or minus k right so over here uh i can either do plus k or i could do minus k right pretty simple so at each number we have two options so one thing we could do is we could kind of have like a recursive backtracking solution where we try out each and every possibility so but so that actually sounds pretty good for smaller numbers right but when you look at bigger numbers this is going to increase exponentially so the time complexity would be 2 to the power of n and let's say we had something with the length of 100 we would have a greater than so we would have i think more than 10 to the power of 30 uh possibilities so that's quite a bit right so that will be taking up a lot of time and that's probably not the best solution so now let's think of another solution so the backtracking solution is going to take too much time so now what we want to do in this solution over here is we're going to go through these elements one by one and we're gonna make another assumption so let's just say we're iterating through these elements and let's just call this a i uh or actually no let's just call it a i okay so a i refers to each of the indices or each of the elements inside of area a and over here the assumption that we're going to make is that this over here so whatever a i is um okay so this over here is the max value okay so we're going to assume that whatever is at a i is the maximum value and based upon that assumption we are going to find its minimum and maximum value so how exactly is this going to work so the reason this works over here is because we don't need to output the array b instead we just want to output what is going to be the smallest range that we are going to have we just care about the smallest range so let's see how this is going to work so we want to find the minimum value and we also want to be finding a maximum value okay now what exactly do these minimum and maximum values correspond to so when i say minimum value i mean the minimum value with respect to a i again remember we're taking the assumption that a i is the maximum value so let's just start off with the maximum value and actually before we actually go to this part here uh since we know that our area is sorted what is going to be the smallest value so we know beforehand it is sorted so whatever is at the zeroth index is going to be the smallest value no matter what simultaneously the largest or the biggest value is going to be whatever is at the very ending which in this case is 13. so that is going to be the smallest and the biggest value of that we have so that is something that we want to keep in mind okay and before we actually go through this uh i just wanted to say one last thing and this is kind of a very intuitive thing right so let's just say we're assuming so we don't care what these numbers are okay so let's just say it's some sort of area with numbers okay so let's just assume that whatever is over here is the maximum okay that's the assumption that we are making so uh again remember that this list over here is sorted okay so we're assuming that this is maximum so how exactly can we make it the maximum when our list is sorted and there's stuff on the right of it so to make it a maximum we're going to take this and we're going to add k to it that way it could possibly uh just make sure how i'm saying possibly be a maximum it doesn't have to be but it could possibly be a maximum value so let's say we make this plus k in that case let's just assume that this is now a maximum value over here so now let's see what is going to be the minimum value for this over here so the minimum value assuming that this is a maximum is going to be whatever our smallest value is plus k and why are we going to add k to our smallest value and the reason we're adding k to our smallest value is because we want to be as close as possible to this value over here so that is one possibility right so we could go to our smallest value and add k to it and that could be a possible value for being the smallest of value assuming that this element over here is the maximum now what is some other possibility so another possibility is that we could go to one value to the right so over here so this whatever values over here and subtract k by that so those are two possibilities of finding the minimum the minimum value that we have now why does this make sense so let's just look at a and let's take it six for an example so at six what is going to be the smallest value so over here we have the number six and we're going to assume that six is our largest number uh again this might not work out for some reason but let's just assume that it is okay so we're gonna add three to it since we're assuming it's the largest so now it's going to become nine so now we want to find what is going to be the smallest number so since it is sorted the smallest number is going to be whatever is at the zero index which in this case is one but remember we want to be able to make the smallest range possible so for the smallest range we're going to go to one and we're gonna add k so in this case we're going to get one plus three giving us a value of four so four is going to be one possible possible value now what is an other possible value so another possibility is that we go to 8 over here and we do 8 minus k so that's nothing else but 8 minus 3 giving us a value of 5. so those are going to be the two values four and five and what exactly are we going to end up choosing between four and five well in this case we're going to end up choosing the value four because we have to choose the minimum value over here okay so uh that's how we want to choose the minimum possible value and those are going to be the only two possibilities for getting a minimum value so now doing the same keeping the same thing in mind what is going to be our maximum value now remember that the assumption we're trying to make is that this over here the current element we're on is the maximum value so let's say that this is the maximum value so in that case one of the possible solutions that we have is that we go to this over here and add k to it so this could be a maximum value but it doesn't have to be and in order for this to be a maximum value everything to the right of it we're going to subtract it by k and the basic reasoning behind that is that we want it to be as close as possible to this value and we know everything to the right is greater than it okay so instead of looking at each and every one of the elements we're just going to look at whatever is at the very ending so in this case we're just going to go to this value which is at the very ending so this is going to be the greatest value and over here we're going to subtract whatever this value is by k and by subtracting it by k what's going to happen is we're going to choose the maximum between this value over here so whatever element we're on plus k and the maximum value minus k so if this element over here even after adding k to it is not the maximum when compared to going to the largest value and subtracting it by k then in that case this is never going to be a maximum so when that condition happens so let's say this over here is the larger number so then even after subtracting k let's say it is the larger number so what we're going to end up choosing is we're going to choose the maximum so in this case we're going to end up choosing this okay so um let's just go through this uh more specific to this example in terms of the values that we have so we have to start off by finding a value to start off with so we're going to have a results value and in the very beginning result is going to be uh whatever we start off with so that's just going to be 13 minus 1 the largest minus the smallest and that is going to give us a difference of 12. now why does this uh and you might be like we're not doing anything to it so doing 13 minus 1 is the same as just adding k to everything or subtracting k to everything the difference is not going to change so in this case we're starting off with the value of 12 and again our goal is to minimize the result okay so now let's start off with our minimum value again the assumption is that a i is the maximum value so for our minimum value we're going to be taking the minimum between whatever the smallest value is plus k right because we want to get as close as possible to the maximum value and the other possibility is going to a i plus one right and doing minus k and you saw an example of this when i took six as the maximum and then uh tried it out with eight and one right so this is another possibility going to the next value and subtracting it by k okay so those are we're going to choose the minimum between those two and for the maximum value we're going to take the maximum between a of negative 1 and the reason we're going to negative 1 is because that's the very ending and to that we're going to subtract k and the other value that we're going to be looking at and again the reason that we're subtracting is uh because let's say a i is at 6 everything to the right of it we want to get it as close as possible to six and the best way to do that is subtract everything to the right of it by i that's the basic idea so that's what we're doing we're doing 13 minus i uh in other words the greatest value minus minus k not i sorry k not i okay so the that's what we're doing so going to the greatest value and subtracting it by k and the other option that we have is we're assuming that a i is the largest and since we're assuming it's the largest to make it the largest we're going to add k to it okay and we're going to choose the maximum between these two and at each time our result is going to be equal to the maximum value minus the minimum value okay so this is going to give us one answer but what we're going to be doing is we're going to comparing it we're going to be comparing it with our original result at each point okay so uh in this case with the previous result and we're going to compare our new result and each time we're going to be taking the minimum between those two so let's just look at this exact same example and see what our result values will look like and which one we actually end up choosing so over here we have this the exact same area 1 3 6 8 12 13 and k is equal to 3. so in the beginning our difference is going to be 12 and each time we're going to be choosing the minimum difference so let's just look at one iteration so let's say we go to our very first value over here so that is going to be equal to one and over here the two options for the maximum is going to be between one plus three which is four and thirteen minus three so which is ten so we end up choosing ten so the maximum value we have is going to be ten which is nothing but 13 minus 3 and now let's look for the minimum values the minimum value over here could either be 3 minus 3 which is going to be about 0 and another possibility for the minimum value is going to be the smallest value so this is one plus three which is going to be four so we take the smallest between those two which in this case is zero so ten minus zero gives us a result of ten so that is going to be the result at that iteration so each time we're going to be doing the same calculations and we're going to be having the smallest range at that by performing those calculations so at this point so at the next iteration uh we get 7 and after getting 7 we end up with 6. so at these points we might have gotten different values but we're still sticking with the number six because well so far six is smallest and at the ending of this we end up outputting the value six and that is exactly what the expected answer is so now let's see how we can translate the same algorithm that we just talked about in terms of code okay so i'm just gonna go through this because i think that's pretty simple once you understand what's going on so the first thing is that we're sorting our area a and after doing that we're going to start off by defining our result and in the beginning it's just going to be the maximum value minus the smallest value and in simple words the maximum is whatever is at the very ending and the minimum is going to be whatever is at the zero with the index so that is going to be our result now what we're going to do is we're going to go inside of a for loop and we're going to be going through the indices and we're going to start off at the zeroth index and we're going to go all the way up to the last but one value so that's where we do length a minus one right so we don't want to go up to the very ending and the reason for that is because we have to account for the index plus one value over here okay perfect so over here uh we have to find the minimum value and it's the same thing that we talked about earlier and this is over here the maximum value and we calculate that and then we're going to take our result and for the result we're going to choose the minimum between the previous result and the currently formulated result that we got and that's nothing else but maximum value minus minimum value and the previous result which is uh well just res okay and we're going to do this for all these iterations and at the very ending we're going to return whatever result value we have okay and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and yeah don't forget to like and subscribe thank you | 2024-03-25 10:39:43 | 910 | Smallest Range II | Leet code 910 | Theory explained + Python code |
|
SpPeKqsATKk | [Music] hey everyone you're watching Tech hey everyone you're watching Tech timeout and in today's video we will timeout and in today's video we will solve this problem that's called solve this problem that's called students and examinations the link to students and examinations the link to the problem is in the description so the problem is in the description so feel free to check it out feel free to check it out now we have a table that's called now we have a table that's called students it has columns student ID and students it has columns student ID and student name student name in SQL student underscore ID is the in SQL student underscore ID is the primary key for this table each row of primary key for this table each row of this table contains the ID and the name this table contains the ID and the name of one student in the school of one student in the school and in the table subjects we have and in the table subjects we have columns subject name columns subject name in SQL subject name is the primary key in SQL subject name is the primary key for this table for this table each row of this table contains the name each row of this table contains the name of one subject in the school of one subject in the school and finally we have the table and finally we have the table examinations examinations it has columns student underscore ID and it has columns student underscore ID and subject name subject name this table may contain duplicates in this table may contain duplicates in other words there is no primary key for other words there is no primary key for this table in SQL this table in SQL each student from the students table each student from the students table takes every course from the subjects takes every course from the subjects table table each row of this table indicates that a each row of this table indicates that a student with ID student underscore ID student with ID student underscore ID attended the exam of subject underscore attended the exam of subject underscore name name final number of times each student final number of times each student attended each exam attended each exam return the result table ordered by return the result table ordered by student underscore ID and subject student underscore ID and subject underscore name underscore name the result format is in the following the result format is in the following example example so we have four students Alice pop John so we have four students Alice pop John and Alex the student IDs are 1 to 13 and and Alex the student IDs are 1 to 13 and 6. then we have the subjects math 6. then we have the subjects math physics and programming physics and programming and finally we have the exams and finally we have the exams now in the output we observe that now in the output we observe that for student ID and student name for student ID and student name each student has attempted all the three each student has attempted all the three subjects and that goes for student ID 1 subjects and that goes for student ID 1 then 2. then 2. 6 and 13. 6 and 13. and the result table should contain all and the result table should contain all students of all subjects Alice attended students of all subjects Alice attended the math exam three times the physics the math exam three times the physics exam two times and the programming exam exam two times and the programming exam one time Bob attended the math exam one one time Bob attended the math exam one time the programming exam one time and time the programming exam one time and did not attend the physics exam did not attend the physics exam so for Bob the physics exam attended so for Bob the physics exam attended exams value is zero because there is no exams value is zero because there is no record in examinations table such that record in examinations table such that student ID corresponds to Bob's student student ID corresponds to Bob's student ID and subject name corresponds to ID and subject name corresponds to physics physics now to solve this problem now to solve this problem one can easily tell that first we are one can easily tell that first we are going to have to cross join student going to have to cross join student stable and subject stable because stable and subject stable because apparently all the students took all the apparently all the students took all the subjects subjects it's only the matter whether they it's only the matter whether they attended the examinations or not attended the examinations or not so let us write select so let us write select student student underscore ID underscore ID then student then student underscore name subject underscore name and some count value from students as cross join say SB say SB all right and then we are going to left all right and then we are going to left join this join this with examination stable e on and what would be the joining condition well it's supposed to be e Dot student underscore ID equals to s dot student underscore ID and subject subject underscore ID underscore ID equals equals SP Dot SP Dot subject underscore subject underscore it's actually supposed to be name sorry it's actually supposed to be name sorry so so e dot subject underscore name right e dot subject underscore name right then the value has to be grouped by then the value has to be grouped by these columns and finally a test errors also order by statements yep order by student underscore ID then now what would what should be the count now what would what should be the count okay so it should be e Dot okay so it should be e Dot student underscore ID student underscore ID and what if it is null well if it is and what if it is null well if it is null null then the value should be zero and aliased as right right let's see if we have anything pending let's see if we have anything pending oh we should oh we should use the Alias here before the column use the Alias here before the column names so it should be students.ie names so it should be students.ie [Music] [Music] student's name student's name s p s p dot subject name because subjects as dot subject name because subjects as Alias SP Alias SP and similarly here and similarly here let's start B Dot can s dot s b Dot right they should do it let's see okay it worked great um if we see the results for the previous queries the performance wasn't so bad um yep so this is how I solve the problem if you have any alternate Solutions please feel free to comment in the comment section below and I might check it out thanks for hanging out with me have a great day goodbye thanks for watching this video don't forget to like this video and drop your thoughts in the comment section below also subscribe to the channel and press the Bell icon to get instant updates | 2024-03-20 10:24:54 | 1,280 | 1280. Students and Examinations| Leetcode SQL Easy |
|
hJFi0kxGQPM | Hello Hello Everyone Laddu Solve Question No. 326 Power of Trade Today To Give Shape No. 326 Power of Trade Today To Give Shape In This Question Were Given And Interior In This Question Were Given And Interior For Example Shesh 9n Vs To Determine Weather Its For Example Shesh 9n Vs To Determine Weather Its Power Of Tree Not To Not Considered To Power Of Tree Not To Not Considered To Power 2012 Similarly Saffron Represents Power 2012 Similarly Saffron Represents Power Will Return Force Power Will Return Force Okay So Okay So Okay So problem solution which can extend to the prime numbers the show for example 357 2100 ok straight forward solution first effigy in this list and one should not power will return for a key and what will do is will give dividing Will Give It And It's Divisible By Three Look And Have Or Face Divide Rocky Dividing Road Visual Methane And Indra And Will Check If N Is Equal To One Which Will Stop At One Of Its Difficult Acids Bases 512 MB View It's Okay Okay Subscribe 15053 Vikram A Pipe Notice For This Not Divisible By Three Little Pigs Is Look And Will Get In This Will Check This Condition Is Indicative And Tennis Request 510 Will Return For Us Map Combustion Of Glucose To 9 Vacancy Date Individual Life In This Look first will make any query Look first will make any query Look first will make any query for ok from which in which country li for ok from which in which country li that your after in this view divisible by this vital and mental figure main course to one ok no vendors not divisible by three most welcome on air at will check weather and Solution with which we have Solution with which we have Solution with which we have controlled that Lakshmi this election that Lakshmi this election 123 walking lets check and 5 123 walking lets check and 5 one by one it has one by one it has happened that this shift in all states walking as well as city was walking Lakshmi decor a city was walking Lakshmi decor a that avoid of youth summit submissions and tried to different that avoid of youth summit submissions and tried to different things things things is a solution so let's say solution avikal solve this ok so 500 index solution what we will do it is will take the patay sisai the problem description what we will do it will take to the greatest number withdrawal which is the power Of This 231 - Subscribe For Example Jo Sudur Power 31.22 The Power That's Even And The Jo Sudur Power 31.22 The Power That's Even And The Great Is In Which Is The Power Of Three Great Is In Which Is The Power Of Three Languages In This Is To The Power Languages In This Is To The Power Notification Printed Spelling OK Suggestion Notification Printed Spelling OK Suggestion From Shiv 1000 Prime Number VPN Se Data 119 From Shiv 1000 Prime Number VPN Se Data 119 Is Oil Divisible By Value Research Center Is Oil Divisible By Value Research Center Power 04023 The Power Of Power 04023 The Power Of That 19th Correct Too Difficult Eminem Which That 19th Correct Too Difficult Eminem Which Is A Word To Successfully Divide Into Is A Word To Successfully Divide Into Power - 01 2010 To Reduce Power Of Three Okay Power - 01 2010 To Reduce Power Of Three Okay Let Me Tell You One Second Sisakti Let Me Tell You One Second Sisakti Is The Prime Number 90 Power Is The Prime Number 90 Power Is The Prime Number 90 Power by values from there power 0232 power 900 withro power in the middle east and solution and similarly solution to the prime numbers where given the power to two things on a wick in this way can find the greatest Acid rain for Acid rain for Acid rain for example in more just not example for this is the example in more just not example for this is the correct way we will take and correct way we will take and difficulties with this book will be with us difficulties with this book will be with us one person one and any possible to divide and rule se one person one and any possible to divide and rule se edit ok decide solution edit ok decide solution so let's 1000 solution show will return map so let's 1000 solution show will return map Race and MP3 that you power 9900 value filter power known from Google fennel to the power 99 from it spoon or fragrant liquid is reduced so is three to the power 90 is divisible by In In them which will give 0 fall flexis getting chapter 10 minutes that gas so this is this is also getting submit should you can solve this problem ok n you can extend second solution 2nd power of prime number solidification more ok thank for watching a | 2024-03-24 10:32:06 | 326 | Leetcode #326 Power of Three | April LeetCoding Challenge 2021 - Day 27 | Java |
|
xsnAlMknB9o | hey guys we are going to discuss a hard problem problem and this problem is basically an and this problem is basically an application of tries so the problem is application of tries so the problem is known as known as design search autocomplete system the design search autocomplete system the description of this problem is quite description of this problem is quite long i'm not going to go through all of long i'm not going to go through all of this this but i will explain you the main problem but i will explain you the main problem we can read we can read the first few paragraphs and i will give the first few paragraphs and i will give you the explanation after then you the explanation after then i will place this text in the i will place this text in the description or the link to the lead code description or the link to the lead code that you can later that you can later have a look at if you want to have a have a look at if you want to have a further look so we need to design further look so we need to design a search autocomplete system for a a search autocomplete system for a search engine and users may input search engine and users may input the sentence in at least one word and the sentence in at least one word and end with the special character end with the special character which is hash and we are given a string which is hash and we are given a string array of sentences array of sentences and an integer array of times and both and an integer array of times and both have have the same then if you see over here in the same then if you see over here in the example so for we have we have here the example so for we have we have here is the array of the sentences so we have is the array of the sentences so we have different sentences like island different sentences like island iroman i love lead code and i love you iroman i love lead code and i love you then we have the times area which is 5 3 then we have the times area which is 5 3 2 2 so this basically represents 2 2 so this basically represents the frequency of each sentence so the frequency of each sentence so let's say the first sentence has a let's say the first sentence has a frequency of 5 let's say 5 minutes frequency of 5 let's say 5 minutes and then the second sentence has which and then the second sentence has which is island is island takes let's say three three minutes and takes let's say three three minutes and so on so on and for each input character uh except and for each input character uh except for the hash we need to return the top for the hash we need to return the top three historical hot sentences that have three historical hot sentences that have the same prefix as part of the same prefix as part of the sentence is already typed okay let's the sentence is already typed okay let's see the example so first prefix is i see the example so first prefix is i we check that the first keyword is i so we check that the first keyword is i so we need to check we need to check we need to return over here when the we need to return over here when the input is input is i then we we have the search results i then we we have the search results would be everything which is starting would be everything which is starting from i right so we have four from i right so we have four all four sentences are starting from i all four sentences are starting from i over here we saw that we have to over here we saw that we have to to to return the top three historical to to return the top three historical hot sentences that have the same prefix hot sentences that have the same prefix as part of the sentence which is already as part of the sentence which is already typed okay top three we have to return typed okay top three we have to return so that and that would be based on based so that and that would be based on based on the time on the time the priority of the time as well as if the priority of the time as well as if and if in this case for example two of and if in this case for example two of them have the same frequency them have the same frequency so in this case what we gonna do is that so in this case what we gonna do is that we are going to take we are going to take for example iron main and i love lead for example iron main and i love lead code code have the same frequency right or the have the same frequency right or the same time so same time so we will see the next word after i which we will see the next word after i which is is r over here and the next word in i love r over here and the next word in i love lead code after i which is space over lead code after i which is space over here here and we know that space has the ascii and we know that space has the ascii character value character value of 32 and r has the ascii character of 32 and r has the ascii character value of value of 114 and because of that 114 and because of that i love lead code will be higher priority i love lead code will be higher priority because the time is the same for because the time is the same for most of both of them so the first three most of both of them so the first three sentences would be sentences would be i love you i learned and i love lead i love you i learned and i love lead code code okay and that is shown over here in the okay and that is shown over here in the example example and then the next word we have i and and then the next word we have i and space space so everything which is starting from the so everything which is starting from the space space so space is basically the next extension so space is basically the next extension so let's say you are typing it so let's say you are typing it into into the search engine first you into into the search engine first you type i so you have those three type i so you have those three possibilities and now you type space possibilities and now you type space so i in space your search results are so i in space your search results are reduced to reduced to i space love space u and then i space i space love space u and then i space love lead code okay so we have two of love lead code okay so we have two of these sentences because these sentences because after i there is a space in two of the after i there is a space in two of the sentences sentences right and then we have a so if we have a right and then we have a so if we have a we do not have anything with i space a we do not have anything with i space a so that's why so that's why it will return empty list and then we it will return empty list and then we have hash have hash and they they tell us over here that and they they tell us over here that hash hash for each input character except for hash for each input character except for hash so when there is a hash so when there is a hash then we have like then we have like it returns an empty array if c is equal it returns an empty array if c is equal to hash to hash and stores the inputted sentence in the and stores the inputted sentence in the system system okay so when there is a hash okay so when there is a hash okay then whatever was the input okay then whatever was the input sentence which was i space a sentence which was i space a this is this is this sentence you are this is this is this sentence you are going to store it into the system so going to store it into the system so this will this will become part of this list okay so now we become part of this list okay so now we will have five words and this would be i will have five words and this would be i space a space a would be the next one so we need to would be the next one so we need to implement this uh this logic implement this uh this logic we need to come up with this output when we need to come up with this output when we are we are applying when we are when we have the applying when we are when we have the input i input i when we have the input space and so on when we have the input space and so on so i think you got so i think you got you got the idea so so let's you got the idea so so let's start with the implementation so as a start with the implementation so as a first step first step we need to initialize our data we need to initialize our data structures okay so we can take one structures okay so we can take one let's say lookup table and we can say let's say lookup table and we can say lookup and we can say that this lookup and we can say that this we can define it as our dictionary right so this dictionary will basically contain the elements let's say that it will contain all the sentences along with their frequencies okay so we can say for so for each sentence we can store so for each sentence we can store it into the dictionary along with its specified time right in order to keep the time over here we can say let's say i of sentences of sentences and here now i can give times of and here now i can give times of of i okay so this is the first step so of i okay so this is the first step so now we have now we have our for each sentence we have something we have its corresponding times okay so the next thing would be to define and let's say this self.lookup so we can define self thought so we can define self thought to try this is our try data structure to try this is our try data structure and we will implement the class of try and we will implement the class of try okay all right and now okay all right and now we must also define some some function we must also define some some function inside our class inside our class try our try must be filled with try our try must be filled with it must be initialized with all the it must be initialized with all the elements elements in our sentences okay so we can once in our sentences okay so we can once again call this loop again call this loop and let's say for s in sentences and then we can say uh self.try dot insert and we will write our insert function and then insert of s okay so that would just insert for each sentence for each letter we are going to create our try data structure right so this would be something like so we have i and then we have l and then we have l and then we have po and then so on right and then we have po and then so on right so something like this it will so something like this it will the dry data structure will be will be the dry data structure will be will be formed formed right all right the next thing is is our right all right the next thing is is our keywords okay so keywords okay so currently our keyword is empty and in currently our keyword is empty and in our keyword we will our keyword we will we will keep these values like i we will keep these values like i or space or whatever the keywords the or space or whatever the keywords the user types user types right so we have to have we need to have right so we have to have we need to have a variable for keyword okay so this is a variable for keyword okay so this is also something we are going to also something we are going to initialize initialize okay great all right so now we are over here at our our user function so that would be the user input and we can say that okay so now we have now we we need to check over here so what is our our c so first we also have a condition of hash if it's it's hash then we just need to return 0 and we need to store this element into dictionary right so we can just say we can just check over here that if c is equals to hash in that case we can say so self.lookup keyword and this will be so self.lookup keyword and this will be updated updated and we will say cell dot keyword self dot lookup dot get so we will say self dot keyword because we need to get its frequency first comma zero okay and then we will also update and if it doesn't exist we are just and if it doesn't exist we are just going to place one over there going to place one over there and if it exists then we are just going and if it exists then we are just going to increase to increase its frequency right the second thing its frequency right the second thing what we can do what we can do is we need to insert this element is we need to insert this element into 3a because uh because we into 3a because uh because we talk about as the question says that talk about as the question says that if it's hash we need to save it into our if it's hash we need to save it into our system system right so that would be cell.tree a dot insert and then we can say self.keyword right and then what we could do is that we can say self thought keyword so now we can empty this keyword okay so it's nothing like you can say uh we can say that this word this keyword is empty now and then we can return the empty list as it's mentioned in the question and what would be the else part so the else part would be that we can say self dot keyword keyword and then this would be plus equals to c okay so we can just add into into this one and then we can define a list right in this list basically we need to contain the sentences so whatever was the the search results so our when we search when we search some some some keyword so that would return us what sentences it would return okay so it will give us some sentences so when you say i then it gives us four four of these and then we can it will give us four letters or four sentences which are starting with i and then we can cut down to three okay so that would be a list right so it would be a list of four words right so we can say that self.try dot search and then we can say or we can say self self.keyword right and then we can say over here this list would be we can sort this list okay and how so this will be key is equals to lambda and that would be lambda x and we can say look up because we need to get the time for it so look up of of x so for each element inside inside ts then we can say that we search for the lookup and then we can say comma this would be x right to order it by the this would be x right to order it by the descending time because five is the descending time because five is the biggest one right biggest one right it's not in ascending order so this will it's not in ascending order so this will be minus okay be minus okay what else we can then return our list what else we can then return our list and that would be the three elements so so three so zero one and two okay and this would be self.lookup so now let's try to implement let's start implementing our 3a class okay so this will be class try i'm sorry for the wrong pronunciation it's try it's not 3a great so let's say defined our init function say self say self comma okay and here we can just uh we can just initialize let's say the root element or the dictionary so this will be our dictionary that will contain the elements of try and then define our insert function and this will be self and what else we are passing over here that would be let's say we have a sentence okay so this would this would be so we are passing into an insert we are we are passing a sentence over here right so this would be a sentence so okay so what we can do now so let's define a local variable over here which will be equal to self dot root for each word in sentence for each word in sentence right so for each word in sentence like right so for each word in sentence like now we have now we have i there is face then love then you i there is face then love then you so for each word in sentence so for each word in sentence or each character in sentence let's say or each character in sentence let's say we will say we will say current of w current of w and i think we can you can also call it and i think we can you can also call it as c but i'm also as c but i'm also using c over here so i will call it w so using c over here so i will call it w so this would be for each each let's say this would be for each each let's say letter letter okay let's say letter so this would be current of letter and this will be equivalent to a dictionary okay and we can also put a condition over here first so if l not in current then current of l is equal to dictionary and current of l is equal to dictionary and then we can say current then we can say current is equals to current of l is equals to current of l okay so by this what we are going to okay so by this what we are going to define define is that so we have something like this is that so we have something like this now now let's say i and let's say i and i have a dictionary initialized for it i have a dictionary initialized for it right so that's our idea and right so that's our idea and in the next one i have a space over here in the next one i have a space over here so i will place it inside this so i will place it inside this space and that would be space space and that would be space and i have another dictionary inside it and i have another dictionary inside it like this and i'll create another like this and i'll create another for the other word which is l then i for the other word which is l then i have have another dictionary so this is basically another dictionary so this is basically nested dictionaries that i'm creating nested dictionaries that i'm creating for o for o it will be another one it will be another one and so on okay so it will it will and so on okay so it will it will continue continue something like this so this is how i'm something like this so this is how i'm implementing the tri data structure implementing the tri data structure i can say now that current i can say now that current of hash because it will reach to the end of hash because it will reach to the end of the sentence of the sentence okay and when it will reach the end of okay and when it will reach the end of the sentence the sentence what i'm gonna do is that in the end what i'm gonna do is that in the end the hash so current hash the hash so current hash so at the key hash i can store the whole so at the key hash i can store the whole sentence okay so i know that the sentence has ended over here okay so this is the insert function and now we can define our search function as well so the search function would be define and we can say self and we can say self and then we have also a prefix and then we have also a prefix which is which is this i which is which is this i right so all the words that you are right so all the words that you are typing so that would be the prefix typing so that would be the prefix and then we can say current is equal to and then we can say current is equal to none none over here initially and over here initially and if let's say current because initially current is null over here so we can just say current is equals to self self dot self.root great for every every character great for every every character in prefix so we can say that if [Music] c not in current then we can say we can return an empty list okay because it doesn't exist over there and if not c so current will be equal to current of c so current will be equal to current of c all right we can define c all right we can define our list let's call it answer our list let's call it answer and here we are going to append the and here we are going to append the sentences sentences that are starting with i for example so that are starting with i for example so we started with we started with the prefix i and now we can check like the prefix i and now we can check like for okay so we can say for k for okay so we can say for k in current so we can say in current so we can say if k equals to hash if k equals to hash so in that case we can append to our so in that case we can append to our list the sentence list the sentence and otherwise answer and otherwise answer plus equals to and we can recursively plus equals to and we can recursively call this function call this function self dot search and we can pass an empty self dot search and we can pass an empty string string so for the first time you have i and so for the first time you have i and when you are going to call the next time when you are going to call the next time so we are going to so we are going to to pass the rest of the string so for to pass the rest of the string so for example i is there example i is there and then the next one would be the space and then the next one would be the space okay so okay so we will pass this part part of the we will pass this part part of the string okay so we are going to string okay so we are going to recursively call so this will be current recursively call so this will be current of k of k okay and then it will go nested until it okay and then it will go nested until it reaches the hash reaches the hash and then it will return the sentence it and then it will return the sentence it will add the sentence will add the sentence sentence into our answers and then we sentence into our answers and then we can return can return we can return answer we can return answer and i think that's it um let's try to and i think that's it um let's try to run this code run this code let's try to run this okay so we say it let's try to run this okay so we say it says that lookup is not defined says that lookup is not defined so this so the problem is self.lookup so this so the problem is self.lookup here okay it seems to be accepted here okay it seems to be accepted the solution is accepted let's try to the solution is accepted let's try to submit this solution great so it works so i hope you guys understand this problem thank you very | 2024-03-20 14:32:10 | 642 | LeetCode 642. Design Search Autocomplete System , Python |
|
RV0QeTyHZxo | very special to make that Jan and also not with the thing I screen the web both not with the thing I screen the web both on the day before the leak chill the trip on the day before the leak chill the trip first be the tree sees the folding bike first be the tree sees the folding bike graphing yes yes malic acid and the number graphing yes yes malic acid and the number of the stinks and confused Marcus is of the stinks and confused Marcus is vinkt vinkt vinkt of spring is your blubber the program sing the square okay then not modular long Brazil fewer problems I praise yes that is our country who the listing who the listing substrings soy in is under duress substrings soy in is under duress this was a means let's get it again this was a means let's get it again sam policy ii baby sam policy ii baby zo lions in the substrings old town with zo lions in the substrings old town with i had my baby baby baby baby and in full i had my baby baby baby baby and in full mouth tim schmoyer is the goldie for mouth tim schmoyer is the goldie for assisting assisting assisting next in order to pick everything already sphinx that city with whom the throne bibi bibi bibi of your neck and see all those also via the sting just as thick oh the substrings that start i and ii neck you are already quite big i and ii neck you are already quite big i and ii neck you are already quite big looks like a baby oh yes well knowledge that is tim knol big as i lay low baby that is so negative that is already 10 such things which is the sun this is 10 samsung shirts and plus one taken this machine to put it taken this machine to put it taken this machine to put it yes I think ms upstream me so the yes I think ms upstream me so the thorium desk testing substrings is thorium desk testing substrings is naughty but oh yes pull now harry naughty but oh yes pull now harry will just oh my partner she can wash will just oh my partner she can wash blood for sweden will so the pants blood for sweden will so the pants Muslims weresepe Muslims weresepe what a scary kennel anyway what a scary kennel anyway what a scary kennel anyway state oil very effective bye oh yes then last index there is one thing the rich and last index there is one thing the rich and poor definitely do next to do something poor definitely do next to do something which you alone sonia by picking dikkie which you alone sonia by picking dikkie dik so wrong with that I am really there dik so wrong with that I am really there the mystery and the economic mission the mystery and the economic mission beebe beebe brakes euh who and baby who enter b&b brakes euh who and baby who enter b&b the IBM who they musically the IBM who they musically strikes the articles that and and roy strikes the articles that and and roy costs and and I something looks of interest to me costs and and I something looks of interest to me and I know a man look is that they news and I know a man look is that they news absolutely so I have to it is on those LEDsky absolutely so I have to it is on those LEDsky substrings substrings and those and those and try to get a lead on the station and try to get a lead on the station rai and coolest and meineszlaan rai and coolest and meineszlaan dixons dixons and look lets do because I s that article and look lets do because I s that article also sti-r plus s okay let's do this also sti-r plus s okay let's do this and the enormous can the listing franky and the enormous can the listing franky effect mitch effect mitch downs the so then I am in the set eliza downs the so then I am in the set eliza and so only and so only the 16 the 16 the 16 now what we do the sportier code in Egypt and that the bird black bull the dog that of his friends sd by size with pin the is not dead size this would bring the number of the sting soft drinks it turned out to be true heaven just to of complex ones of complex ones of complex ones using a using a beagle and google plus oh no robic or and beagle and google plus oh no robic or and maybe there is baby and square healing maybe there is baby and square healing so they have to start a war I am to so they have to start a war I am to reach and one is also in the spring the reach and one is also in the spring the jumps like that and see there is a square jumps like that and see there is a square in the lungs in the lungs in the lungs elements in the set the wax is break in the the pain complex which is just examples party of flashes that are already too sports glow blood led undefined index hi I sell I can from the Jean-Luc is you now finally deminor be you now finally deminor be you now finally deminor be your listing was quite a bit for the your listing was quite a bit for the cherokee swimming cherokee swimming o you now think it stinks photo o you now think it stinks photo substrings jquery arne sting generating see everything you will see me who we who at who am I am I am not work is also old sap century to the stuc just old sap century to the stuc just old sap century to the stuc just see that is so crazy rising to the a see that is so crazy rising to the a minimum substring lent will be one minimum substring lent will be one to the max substring glenn 2be to the max substring glenn 2be and the minimum sat freeland only look and the minimum sat freeland only look helmets that around station and the cheek and the helmets that around station and the cheek and the market sometimes have absurd things and market sometimes have absurd things and market sometimes have absurd things and undertook bridge healing and way to be that plan of the city frink's song name bridge something on a [ __ ] mix endless summer not included because without now mean such an area wiesel hug ribbon and so arena baby and at the physio committee is committee is committee is arrest arrest lars as fix what you together linear lars as fix what you together linear effort rooms humorous advice effort rooms humorous advice with suddenly quest absolutely with suddenly quest absolutely like imam like imam and square and square substrings in the set substrings in the set such a square touchscreens in the set such a square touchscreens in the set I want my Swiss quality I want my Swiss quality and every substring and sap pi and we and every substring and sap pi and we wandering I wandering I wandering I blog myspace you always offer beagle puppies your family you always beagle trees with like Jim and who string in the self wants us on nothing wrong with and my goal the snow globe and audience and qbuzz antink the class Sweden linear nutrition bacon Sweden linear nutrition bacon Sweden linear nutrition bacon his child not lab pension pots his child not lab pension pots it is not the case that I am not too hard it is not the case that I am not too hard so that is my IP and will therefore be a problem you so that is my IP and will therefore be a problem you see that is promising it was nothing so see that is promising it was nothing so [ __ ] gardens [ __ ] gardens I have a new swimming hardly myself I have a new swimming hardly myself spring hare in Brussels so this is the spring hare in Brussels so this is the price if we are different with the problem price if we are different with the problem in shock well I understand I shouted from the closet in shock well I understand I shouted from the closet when you finished couple of strings line when you finished couple of strings line baby baby baby baby baby baby so instead in order to abbey and abby so instead in order to abbey and abby abby music by people of old and new abby music by people of old and new book for spaceback book for spaceback you in advance for you along PSV you in advance for you along PSV offer your arm from earlier that warm air offer your arm from earlier that warm air and write and for that reason your and write and for that reason your answers for price is for the answers for price is for the statement statement mbh skin and other drivers and a mbh skin and other drivers and a set this is welcome preventive and beagle 2 set this is welcome preventive and beagle 2 so it can be turned out that or so it can be turned out that or so it can be turned out that or foundation rescue they leek beer the specie use baby can be used by ebay and so not barbie I didn't know that fingers to prime me this is a blog mango and project so that we will be using place the chair-back the sensor space complex ones that are also in HD I understand costs furniture her eyes stations and foundation them a week and on and north and blood the reader space lab this is a cue other I finally say the glow computers and seemed to keep the distinct element slept her a simple plan and the a simple plan and the a simple plan and the import okay I think with about wheel import okay I think with about wheel sublimo the night to get started at if so sublimo the night to get started at if so if you I so articles if you I so articles scream and do really be taking everything a scream and do really be taking everything a square well how do you know who who who who square well how do you know who who who who all audio ghibli is roof jumping all audio ghibli is roof jumping all audio ghibli is roof jumping is in the cinema and so I think that I am on the train and in inserter and vortex and there I think now cloud and you thought that is how I should do it literally now absolutely sammy baby bottle of whiskey and radio system and the six the cuffs was who storms in the the cuffs was who storms in the the cuffs was who storms in the stem cells red so if I got the slot so wifi coverage so private friends baby baby bottle bottle in a box like that touchscreens in google play they we learned so they still have energy they win the post like ring state oil that's it that's food without your 0 sorry point pins from and clients from now st cia in so does and clients from now st cia in so does and clients from now st cia in so does sama you see that I still industry is not so aroma next before never amphibian baby baby so your voice not berlioz the lift a spray oil in surrey and created in there in there in there will be no bioland and us soccer will be no bioland and us soccer she could catch for this then she could catch for this then next classic baby next classic baby think so 0 in so expensive think so 0 in so expensive end googling raven's cry end googling raven's cry or I only miss in such or I only miss in such losses losses who that I so 0 the the string is then peter string is then peter now now now the goal now one thing off biebels like a Turkish one more and those areas and we there's a for business at Vincent a nixons the closet hey this is Tim from a business English English so full nothing license for you your mechanical beasts the sander witjes in durbuy and ang ang next i did i know is a sorry to next i did i know is a sorry to save my thread hi mom the greenhouse for who gets wet who you who I so no reason sorry so so so and miceli long with if you only go to the and miceli long with if you only go to the tame or on such a weekend you have slightly tame or on such a weekend you have slightly older eyes hole sphinx that stands with who older eyes hole sphinx that stands with who they who wins who is a sugar and beer they who wins who is a sugar and beer who will sink brings so who your goal who will sink brings so who your goal is number pico is number pico is number pico which i you will see the golden hole sphinx there with platy that is the yes noomi puzzle i already ritual lemmings people of flip level louise's with me nothing who those beers yes players oil never comes took never comes took never comes took the baby the baby let's call the stallion ambi that who rests yes never from google are the ankle 3 with this can actually be done for plus one 5 the chairs service and there with a and b one side and the other one i am the juice profit i am the juice profit i am the juice profit is the thing sorry in bordeaux and ni zoë is the thing sorry in bordeaux and ni zoë barrel i this team barrel i this team city frink's city frink's that it is a complex that i want that it is a complex that i want harley day in you will be in such things harley day in you will be in such things now look at them like and see that a now look at them like and see that a purchase slightly dim libido and square purchase slightly dim libido and square decision to live in such a thing for a long time decision to live in such a thing for a long time and 3d and 3d the new house can do things in you so the new house can do things in you so you do this is to offer that the stocking is not you do this is to offer that the stocking is not a piece biseswar before I see the internet a piece biseswar before I see the internet you on my the pain complex that you on my the pain complex that toe and square and the toe and square and the toe and square and the those ends plinius video for price you can not measured I was this I have a link could make everything price make sure that it 3 users to be with peace but that was choose you can see I quarrels that I do in the queries xps all Buddhist no that criticism old Russian no thick 20 but this is he knows that I have a bit of what your mustache is going to happen this week and I still have to climb that space lab I am I think the wheels in the switch are a clock okay like that or a clock okay like that or a clock okay like that or it's pretty cool so a typical signals it's pretty cool so a typical signals like that engine the typing lesson plus cores bing do like that engine the typing lesson plus cores bing do you on the line of the you chord is you on the line of the you chord is another kingdom straight out of the cooling so live another kingdom straight out of the cooling so live in twice in the string articles s in twice in the string articles s now require is I know now require is I know now require is I know app download to a that the rod so that we can be your audience and so your goals they acted Klaas or emergency select the class or still and the symbolism what a trillion was ready to things so then I think water hole in place so week and just click in that doubling place but that's and those members are the that's not dead yet pool in flex oil in I never try I were witjes don't go check if I think that's how a ski his his his so rigorous well then on the left see is my family he knows his here in shock and new price his week in a church budget shelby chickens and north star never we are like a healing other articles dikes now in such the does will be the tenth does will be the tenth does will be the tenth ready in terms of and I and I was the next long ready in terms of and I and I was the next long side in nootdorp stargate know side in nootdorp stargate know yes I see it yes I see it and I combine I do through the left and I combine I do through the left siege my energy and the things will siege my energy and the things will survive survive about 100 public water glass and about 100 public water glass and donk collection is justo kan donk collection is justo kan donk collection is justo kan substrings swiping type can the I orders that on yes and I a keymission room and that is already who is required a new the sole and saki within a new nut and roofing black end some see that acid and more dock size in the score close to bike plus in the score close to bike plus in the score close to bike plus plus and I am right okay this is the thyme plus and I am right okay this is the thyme and I had a semi a note and I had a semi a note I hear the call I hear the call for a moment it seemed like it took in the breed all the for a moment it seemed like it took in the breed all the stops lecture by Jelle his own is stops lecture by Jelle his own is by by size g plus plus size g plus plus and and and need is best Norton agree so private words and he wants me to find the northern point never one this so niro and I want okay and because again shorter and not giving a night product then I got x man I am so in that neck tube and yes you can do I and rather than the connection and that's how I learn can the bottle cheek wine glass wine glass from him that man once has can she can I want to see so obvious this is far from it can be plastic that are new others in shock and you so we can is is is teasing that his turn leek and yes do teasing that his turn leek and yes do n't you do they are DVD shop Charles n't you do they are DVD shop Charles anti-glare or not actually is that you anti-glare or not actually is that you can put those clothes on can put those clothes on them this is the they of the adults them this is the they of the adults in chance or interviews I my pias is in chance or interviews I my pias is a child so upload a child so upload a child so upload willoughby smoothly hp she flows on your cheeks already cycle process wants that your welcome just in case your it takes place a little lagg the video and I now know that the shadow Facebook and the subscribe I have the chance to Google or and after oh [ __ ] is jeshua points day and oh [ __ ] is jeshua points day and oh [ __ ] is jeshua points day and the subscribe button the subscribe button well yes I had that and you are crazy dead so well yes I had that and you are crazy dead so finance is digicore a week full will be in finance is digicore a week full will be in the description ethnic chic and apricot the description ethnic chic and apricot alarm people and using that and I look alarm people and using that and I look into the wielelei kenny things from sex into the wielelei kenny things from sex stories stories stories their parents that they have stories of people using to services that you know those things that google microsoft and all those had the hairdresser the most then preece bless and check all the links we within discussion cloth cloth cloth and sisters subscribing and sisters subscribing so this is the video lesson none of this so this is the video lesson none of this but with that team but with that team yes first okay start killing you | 2024-03-20 14:37:31 | 1,698 | L4. Number of Distinct Substrings in a String | Trie | C++ | Java |
|
xfkr5ADk1HQ | hello today we'll be solving the problem today we'll be solving the problem number 80 of Lee code remove duplicates number 80 of Lee code remove duplicates from sorted array to from sorted array to give it an integer array nums sorted in give it an integer array nums sorted in increasing order remove some duplicates increasing order remove some duplicates in place such that each unique element in place such that each unique element appears at most twice the relative order appears at most twice the relative order of the elements should be kept the same of the elements should be kept the same since it is impossible to change the since it is impossible to change the length of array in some languages you length of array in some languages you must instead have the result be placed must instead have the result be placed in the first part of the array nums more in the first part of the array nums more formally if there are K elements after formally if there are K elements after removing duplicates in the first K removing duplicates in the first K elements of nums should hold the final elements of nums should hold the final result it does not matter what you leave result it does not matter what you leave beyond the first K element return K beyond the first K element return K after placing the final result in the after placing the final result in the first K Slots of num first K Slots of num do not allocate extra space for another do not allocate extra space for another array you must do this by modifying the array you must do this by modifying the input array in place with o of constant input array in place with o of constant time memory time memory so to explain my solution I will use the so to explain my solution I will use the example provided by the question the example provided by the question the array one one one two two three array one one one two two three we'll solve this using a two pointer we'll solve this using a two pointer approach approach to start we'll move through all the to start we'll move through all the elements of nums we'll keep track of the elements of nums we'll keep track of the loop using I and we'll keep track of our loop using I and we'll keep track of our second pointer under the name of index second pointer under the name of index and we'll keep track of the number of and we'll keep track of the number of times a number has appeared under the times a number has appeared under the name count name count we'll begin the loop at the first index we'll begin the loop at the first index of the array and the second pointer at of the array and the second pointer at the beginning of the array count will the beginning of the array count will also start with a value of 1 because we also start with a value of 1 because we will always read in at least one number will always read in at least one number in this Loop we will compare the values in this Loop we will compare the values found at num's I and nums f as noted found at num's I and nums f as noted here if the two values are equal then we here if the two values are equal then we will increase the count then we'll check will increase the count then we'll check if we have exceeded the number of if we have exceeded the number of duplicates if not then we increased the duplicates if not then we increased the second pointer finally we'll replace second pointer finally we'll replace nums f with nums I with nums F uh nums f with nums I with nums F uh denoting num's fintex denoting num's fintex if a num's i does not equate to nums F if a num's i does not equate to nums F then we will increase the second pointer then we will increase the second pointer and reset the count then we will and reset the count then we will substitute numbers f with nums I substitute numbers f with nums I will continue doing this for the entire will continue doing this for the entire array and as you can see we end up with array and as you can see we end up with findex equals three findex equals three as you can see it is lacking by one as you can see it is lacking by one since we instantiated it with a value of since we instantiated it with a value of zero so you will simply return this zero so you will simply return this Value Plus 1. to begin coding this we'll Value Plus 1. to begin coding this we'll first Define our counter and our pointer first Define our counter and our pointer which will look like this which will look like this to begin coding this then inside the to begin coding this then inside the loop we will make our comparison and loop we will make our comparison and check to see if there are more than two check to see if there are more than two of the same elements and act accordingly of the same elements and act accordingly finally we'll simply return the second finally we'll simply return the second pointer plus one pointer plus one as you can see in my code I also added a as you can see in my code I also added a line that checks for an array with a line that checks for an array with a size of two this line isn't really size of two this line isn't really needed as the loop will still take care needed as the loop will still take care of arrays of this size of arrays of this size but it does give some Assurance but it does give some Assurance regarding an edge case for this problem regarding an edge case for this problem so if we press submit | 2024-03-20 12:11:54 | 80 | Leetcode 80: Remove Duplicates from Sorted Array || | SOLUTION and EXPLANATION |
|
7womRtj_HHA | in this video we'll be going over square root of x given a non-negative integer x root of x given a non-negative integer x compute and return the square root of x compute and return the square root of x since the return type is integer the since the return type is integer the decimal decimal digits are truncated and only the digits are truncated and only the integer part of the result is returned integer part of the result is returned so in our first example we have x is so in our first example we have x is equal to four the square root of four is equal to four the square root of four is equal to two so equal to two so we just return two and our second we just return two and our second example we have example we have x is equal to eight so output is two x is equal to eight so output is two because the square root of eight because the square root of eight is two point eighty two so we remove the is two point eighty two so we remove the decimal part decimal part um we should we can also think of this um we should we can also think of this as we have two times two is equal to as we have two times two is equal to four four and four is still less than eight but and four is still less than eight but with the next number three with the next number three we have three times three we get nine we have three times three we get nine and nine is greater than eight so we and nine is greater than eight so we cannot pick three cannot pick three so let's first go through a thought so let's first go through a thought process the square root of x is in the range of 0 to x divided by two plus since our range is sorted in ascending since our range is sorted in ascending order order we can implement a binary search we can implement a binary search approach approach a binary search approach so for each of the mid value and square just means mid times mid so and square just means mid times mid so square let's go to mid times mid square let's go to mid times mid so if square is equal to x so if square is equal to x then we have found a target value then then we have found a target value then mid is our mid is our is the target value if square is the target value if square is less than x then square may or may not may or may not be the largest square that is less than x so so we will need to search rightward with mid if square is greater than x then we will need to search leftward for example if you have three and then three times three is equal to nine nine is is greater than search leftward from mid minus one now let's go over the code so create two variables left the current so create two variables left the current left boundary and write the current right boundary and write the current right boundary initially x initially x divided by two plus one divided by two plus one and then while and then we're going to and then while and then we're going to perform our binary search perform our binary search while left is less than right while left is less than right calculate the mid index so mid is equal to left plus right minus left divided by two and plus one the plus one just picks the upper mid value so example we have the current elements is one and two we will pick two instead so calculate the square squares go to mid times mid x then we can return mid x then we can return mid else if square is less than x we will need to search right word with mid inclusive right here if square is less than x then square may or may not be a larger square that's less than x so when you search right so left is go to mid else we need to and then we can return left which will and then we can return left which will be be the largest square that the largest square that is which is which f times left will be the largest square f times left will be the largest square that is less than that is less than x let's go do the time and space so time complexity is equal to o of log so time complexity is equal to o of log of x of x where x is the input value minor search and our space complexity is load of one now let's go through the code bring our boundaries we're going to cast it to long to and while left is less than right and while left is less than right calculate the mid calculate the square this is the part where we prevent our overflow because so if square is equal to x then we can so if square is equal to x then we can return return our current mid value but cast it back our current mid value but cast it back to int to int then else if square is less than x then else if square is less than x and we search right word mid inclusive and we search right word mid inclusive else research leftward else research leftward and then we can return let me know if any questions in the let me know if any questions in the comments section below comments section below you | 2024-03-20 11:17:11 | 69 | Sqrt(x) - Leetcode 69 - Java |
|
eJIsVSe0-MI | hello there so today's legal challenge question is called a delete node in a question is called a delete node in a linked list so we have a singly linked linked list so we have a singly linked list and we have access to a node that list and we have access to a node that we want to do a deletion we need to you we want to do a deletion we need to you know write a function to perform this know write a function to perform this operation so as an example we have a operation so as an example we have a linked list for five one nine we've been linked list for five one nine we've been given a pointer points to the node five given a pointer points to the node five so we want to achieve a go that the end so we want to achieve a go that the end result link list will look like for one result link list will look like for one night so so think about this we we are night so so think about this we we are working with singly linked lists and we working with singly linked lists and we only have a pointer to pointer points to only have a pointer to pointer points to node 5 node 5 so since it's a single living list so since it's a single living list there's no way we can go back to the there's no way we can go back to the floor and ask a note force to point to floor and ask a note force to point to node 1 instead of five - you know to node 1 instead of five - you know to perform the actual deletion of this perform the actual deletion of this particular node there's no way we can do particular node there's no way we can do that because it's a single linked list that because it's a single linked list and we couldn't go back so to achieve and we couldn't go back so to achieve the same effect what we will do is to the same effect what we will do is to copy the nodes value the next knows copy the nodes value the next knows value you know change this file into one value you know change this file into one and have this next pointer instead of and have this next pointer instead of pointing to one it will points to nine pointing to one it will points to nine so you will look like if the you know so you will look like if the you know the original node file has been deleted the original node file has been deleted from the linked list but in reality it from the linked list but in reality it just copies the next nodes value and just copies the next nodes value and short the next node instead of the node short the next node instead of the node itself because there is just no way that itself because there is just no way that we can physically delete this node that we can physically delete this node that have been given to us you know unless we have been given to us you know unless we have a pointer that's - in the previous have a pointer that's - in the previous node since that this is singly linked node since that this is singly linked list there is no way we can do that so I list there is no way we can do that so I guess this is where the confusion comes guess this is where the confusion comes into play when you look at that the into play when you look at that the description is called delete node but description is called delete node but we're in fact in reality you couldn't we're in fact in reality you couldn't really delete this object yeah I guess really delete this object yeah I guess that's some question you can ask her to that's some question you can ask her to clarify do we really want to delete this clarify do we really want to delete this physical object or physical object or want to achieve the goal as if it looks want to achieve the goal as if it looks like this thing has been deleted yeah so like this thing has been deleted yeah so with that the code is pretty simple with that the code is pretty simple we're just going to you know copy the we're just going to you know copy the next notes value and then have this note next notes value and then have this note points to the next the next so this show points to the next the next so this show work it's a void so it doesn't return work it's a void so it doesn't return anything all it does is still copy the anything all it does is still copy the next notes value and then Shore to the next notes value and then Shore to the next note so that's the question for next note so that's the question for today all right | 2024-03-22 11:29:37 | 237 | Leetcode 237 Delete Node in a Linked List |
|
UQrhbXNBKk4 | everyone in this video we will be solving a lead called medium level solving a lead called medium level problem number 39 combination sum problem number 39 combination sum the problem statement is we are given an the problem statement is we are given an area of distinct integer candidates area of distinct integer candidates and a target integer target and a target integer target we need to return all the unique we need to return all the unique combinations of the candidates where the combinations of the candidates where the total of all of the numbers total of all of the numbers is equal to the target is equal to the target we can return the combination in any we can return the combination in any order order in example number one the candidates are in example number one the candidates are 2 3 v 6 and 7 2 3 v 6 and 7 and the target is 7. and the target is 7. so based on these numbers we can build a so based on these numbers we can build a total of two arrays or two combination total of two arrays or two combination of numbers which will give us the total of numbers which will give us the total seven seven one is two two three one is two two three and the other is just seven and the other is just seven we are allowed to repeat the same number we are allowed to repeat the same number multiple times multiple times hoping that you understood this problem hoping that you understood this problem statement let's switch to whiteboard and statement let's switch to whiteboard and talk about how this can be solved talk about how this can be solved now thinking from the simple solution to now thinking from the simple solution to solve this problem the first simplest solve this problem the first simplest approach is a brute force approach is a brute force where you will start with a tree and try where you will start with a tree and try to add each number and see if the to add each number and see if the combination adds up to the total for combination adds up to the total for example example starting with an empty array starting with an empty array because we have three combinations or because we have three combinations or three inputs given we will split it into three inputs given we will split it into three parts three parts first is two three and five first is two three and five so with two so with two we can either add two we can either add two either at three either at five similarly either at three either at five similarly at each layer you will keep on checking at each layer you will keep on checking for all the possible combination that is for all the possible combination that is given to us in the candidates array so given to us in the candidates array so let's try one example over here so let's try one example over here so starting with empty starting with empty when we are at this first two my total when we are at this first two my total is 2 is 2 then if i'm going to this leg i might then if i'm going to this leg i might new total will be 4 new total will be 4 if i'm navigating it down to the next if i'm navigating it down to the next layer or the next leg my total will be layer or the next leg my total will be 6. 6. similarly i will continue the next leg similarly i will continue the next leg and now i got my total eight and now i got my total eight because this matches to my target i will because this matches to my target i will add add these four or these legs to my result these four or these legs to my result as you can imagine this iteration is as you can imagine this iteration is going to be a lengthy one and we will going to be a lengthy one and we will definitely end up doing some duplicate definitely end up doing some duplicate calculations for example calculations for example when i am at this 3 position when i am at this 3 position my array contains my array contains 2 comma 2 comma 3 2 comma 2 comma 3 because my path is starting from this 2 because my path is starting from this 2 to this 2 and then this 3 to this 2 and then this 3 if i go a different way so from this 2 if i go a different way so from this 2 let's say i'm going to this 3 let's say i'm going to this 3 so my array will have 2 comma 3 so my array will have 2 comma 3 from this 2 i can go to 2 from this 2 i can go to 2 3 or 5. if i go to this leg with the 3 or 5. if i go to this leg with the value 2 value 2 my new array will have 2 comma 3 comma 2 my new array will have 2 comma 3 comma 2 which is same as what we have already which is same as what we have already iterated hence there are several iterated hence there are several duplicate combination that we will end duplicate combination that we will end up doing if we go by a traditional or a up doing if we go by a traditional or a simple approach simple approach coming up with an algorithm that would coming up with an algorithm that would run this brute force approach is simple run this brute force approach is simple the challenge is to identify the the challenge is to identify the duplicates duplicates so let's think about how we can optimize so let's think about how we can optimize the solution a bit better so that we can the solution a bit better so that we can solve the problem efficiently solve the problem efficiently the first solution to minimize the the first solution to minimize the number of iterations is to order the number of iterations is to order the input into ascending order input into ascending order let me give you an example to prove why let me give you an example to prove why this will be useful this will be useful let's say while we are building an array let's say while we are building an array this is the combination that we built this is the combination that we built 2 2 2 and 3 so the total is 2 2 2 and 3 so the total is so the last element that we added to the so the last element that we added to the array is 3 array is 3 now because this is greater than the now because this is greater than the target we cannot add the solution but if target we cannot add the solution but if i can say that my array is sorted so any i can say that my array is sorted so any number after phi number after phi is also going to give me a sum which is is also going to give me a sum which is going to be greater than t going to be greater than t so in that scenario i can completely so in that scenario i can completely break out of my loop break out of my loop and go to the next combination so and go to the next combination so instead of adding any more values to instead of adding any more values to this place i can switch to the previous this place i can switch to the previous position and start updating that position and start updating that adding this logic to our solution is adding this logic to our solution is going to improve the solution and avoid going to improve the solution and avoid unnecessary calculations unnecessary calculations one way to avoid the duplicates array one way to avoid the duplicates array we will set a rule of we will set a rule of one one one flow will add the previous number one flow will add the previous number to the sum to the array to the sum to the array and the other approach or the other leg and the other approach or the other leg will be not to add it will be not to add it when i'm adding the previous number when i'm adding the previous number so my array will have array will be 2 so my array will have array will be 2 comma 2 comma 2 if i don't add the same number and if i don't add the same number and instead add the next number instead add the next number my array will be 2 comma 3 my array will be 2 comma 3 similarly similarly from this position if i break it into from this position if i break it into two sections two sections i will have i will have 2 comma 2 comma 2 and from this position 2 comma 2 comma 2 and from this position i will have 2 comma i will have 2 comma 2 comma 3 2 comma 3 and if i and if i dive deeper from this position and break dive deeper from this position and break it into 2 legs i will have it into 2 legs i will have 2 comma 3 comma 2 comma 3 comma the last leg that i added is 3 the last leg that i added is 3 and on the right hand side and on the right hand side i will have i will have 2 comma 2 comma 3 comma phi 3 comma phi so we are always going to increment our so we are always going to increment our index or look at the index or look at the number that is on the right number that is on the right we will never look back we will never look back or look at the numbers to the left or look at the numbers to the left with this approach of having a rule to with this approach of having a rule to split the next leg into two parts split the next leg into two parts we will not be running into the issue of we will not be running into the issue of having duplicate arrays because our having duplicate arrays because our parents are going to be different and we parents are going to be different and we are only going to be looking to the are only going to be looking to the right hand side of the array right hand side of the array and also all of the numbers to the right and also all of the numbers to the right of the current value on the current of the current value on the current number is going to be greater because number is going to be greater because it is given in the problem statement it is given in the problem statement that all numbers are unique or distinct that all numbers are unique or distinct hence we will not be having the same hence we will not be having the same number again and the other cases we are number again and the other cases we are doing ascending on our candidates array doing ascending on our candidates array let's apply the same logic for 3 i just let's apply the same logic for 3 i just use this empty space over here so for 3 use this empty space over here so for 3 the first is going the first is going the left leg is going to be to add the the left leg is going to be to add the same number so i will have 3 comma 3 same number so i will have 3 comma 3 and the right side will have three comma and the right side will have three comma the next value which is five three comma the next value which is five three comma three three the total is six which is less than the the total is six which is less than the current target so we can continue current target so we can continue further so on the left hand side of further so on the left hand side of three comma three i will have three three comma three i will have three three three because we are adding the three three because we are adding the same number again and on its right we same number again and on its right we will have three three and five this will have three three and five this total is nine total is nine this is greater than our target there's this is greater than our target there's no point of continuing or moving forward no point of continuing or moving forward so we will break the loop so we will break the loop on the right leg the total is 11 again on the right leg the total is 11 again it is greater than t it is greater than t no point moving forward so we will break no point moving forward so we will break the loop the loop similarly if you look at the right hand similarly if you look at the right hand side we have 3 comma 5 side we have 3 comma 5 the total is a which matches the target the total is a which matches the target we will add this to our result we will add this to our result so with this solution so with this solution our time complexity is our time complexity is 2 raised to the power t 2 raised to the power t where t is the target where t is the target the reason for this 2 is we are the reason for this 2 is we are splitting or we are having 2 legs after splitting or we are having 2 legs after each calculation and the maximum depth each calculation and the maximum depth of this tree is going to be equal to of this tree is going to be equal to the value of t the value of t because we won't be going deeper than because we won't be going deeper than that that i hope you are able to understand this i hope you are able to understand this explanation to solve the problem explanation to solve the problem efficiently let me show you how we can efficiently let me show you how we can implement the same logic using c sharp implement the same logic using c sharp here is my c sharp solution in the main here is my c sharp solution in the main method i first organize or sort my array method i first organize or sort my array in the ascending order in the ascending order then i am initializing a result variable then i am initializing a result variable which will hold all of the array then i which will hold all of the array then i call this helper method call this helper method if index is less than candidates.length if index is less than candidates.length only then we will go into this if only then we will go into this if condition condition then i am calculating this new sum or then i am calculating this new sum or the temp sum by adding the sum that we the temp sum by adding the sum that we have calculated so far the current have calculated so far the current position that index is pointing position that index is pointing if the temp sum is greater than the if the temp sum is greater than the target it means we cannot do anything we target it means we cannot do anything we don't need to iterate forward so we will don't need to iterate forward so we will do nothing if the temporary sum is equal do nothing if the temporary sum is equal to the target then i am adding the to the target then i am adding the number index is pointing to the number index is pointing to the temporary list temporary list adding the temporary list or array to my adding the temporary list or array to my result and then removing it so i can use result and then removing it so i can use it later on it later on this is the concept that we usually use this is the concept that we usually use in backtracking in backtracking let's say my temporary value is let's say my temporary value is less than target then we will go inside less than target then we will go inside the else condition the else condition here's where we are splitting the flow here's where we are splitting the flow into two sections into two sections the first one is the first one is we are adding the same number to the we are adding the same number to the nums nums and continuing the calculation and continuing the calculation once this helper method execution is once this helper method execution is complete we will return the value that complete we will return the value that we have added and then i will call the we have added and then i will call the helper method but this time i will not helper method but this time i will not be adding the current number instead i be adding the current number instead i will be incrementing my index will be incrementing my index to the next value to the next value once the helper method execution is once the helper method execution is complete i will have all of the arrays complete i will have all of the arrays in this result variable and i'm in this result variable and i'm returning it on line 9. returning it on line 9. thank you for watching this video i hope thank you for watching this video i hope you are able to understand my you are able to understand my explanation and this source code this explanation and this source code this source code is available on my github source code is available on my github repository i'll be adding the link to repository i'll be adding the link to the description below feel free to check the description below feel free to check that out and i will see you in the next that out and i will see you in the next video till then stay tuned and keep video till then stay tuned and keep coding | 2024-03-20 09:08:41 | 39 | LeetCode 39 | Combination Sum | Medium | C# Solution | |
|
KZQCvq2dUY8 | hello friends now that solves a maximum square problem as I expand this problem square problem as I expand this problem as a comparison and the maximum as a comparison and the maximum rectangle problem and you see before rectangle problem and you see before given to the binary matrix filled with given to the binary matrix filled with zeros and ones find the largest square zeros and ones find the largest square containing only ones and returnees area containing only ones and returnees area so what's the difference between the so what's the difference between the maximum Square and the maximum rectangle maximum Square and the maximum rectangle why we will use stack when we try to why we will use stack when we try to find the maximum root angle find the maximum root angle what's the difference when we try to what's the difference when we try to find the max find the max Moe maximum square well as in the square Moe maximum square well as in the square the case had being much simpler because the case had being much simpler because the square has the same the same length the square has the same the same length always side which means they're their always side which means they're their height and the width should be the same height and the width should be the same so we just needed to find the max length so we just needed to find the max length of its height and the width so we of its height and the width so we iterated this matrix if current of iterated this matrix if current of charge is 1 we will try to find the charge is 1 we will try to find the laughter and it's up and it's an empty laughter and it's up and it's an empty dialog and they will kick as a minimal dialog and they will kick as a minimal dance and +1 so so we did use the idea dance and +1 so so we did use the idea of the dynamic programming because we of the dynamic programming because we want to cache the maximum maximum length want to cache the maximum maximum length it can be in the same place so basically it can be in the same place so basically the idea you can use this address of the the idea you can use this address of the range some query QD immutable range some query QD immutable we also catch the since again an extra we also catch the since again an extra already so ali scheduie first to that already so ali scheduie first to that educates check if the matrix equal to educates check if the matrix equal to naught or the mass balance equal to 0 naught or the mass balance equal to 0 will return 0 then we get the rows which will return 0 then we get the rows which is the magic is the magic yes and the colors will be the matrix yes and the colors will be the matrix the zero tolerance so we will use a two the zero tolerance so we will use a two TDP array as usual TDP array as usual so what's the size it shouldn't be Rose so what's the size it shouldn't be Rose that's one and the : that's one and the : why because you see even if we are at why because you see even if we are at index zero zero we want you know it's index zero zero we want you know it's left and it is up and anti dialogue see left and it is up and anti dialogue see so if we let's the tip he has same side so if we let's the tip he has same side of the matrix in a will auto bounder so of the matrix in a will auto bounder so for simplicity we just lessen these for simplicity we just lessen these metrics have one more Colin and one more metrics have one more Colin and one more Rose that's the reason so we just Rose that's the reason so we just iterate it and it started from one and I iterate it and it started from one and I will less or you go down the rows that will less or you go down the rows that process and the for J will start from 1 process and the for J will start from 1 J and less oil hose end up : j plus plus J and less oil hose end up : j plus plus so if the mattress I minus one because so if the mattress I minus one because you see we let the this inj destiny is you see we let the this inj destiny is the index in the deep here ray so we the index in the deep here ray so we shoulda less the I and the J minus 1 if shoulda less the I and the J minus 1 if it is equal to 1 we miniature calculate it is equal to 1 we miniature calculate so to know okay we need that you save so to know okay we need that you save the max plan so if if a coat you want we will the current DP IJ will be the minimum of the three values the one value will be the TP I minus 1 J minus 1 which means it anti dialogue which me this place maximum and minimum DP I minus 1 J and if he I J minus 1 in the plus 1 because current L is 1 we catch their minimum length like if all these are one we plus 1 the maximum less will beat you so every time we pair the mass mass and there's a pIJ so in the end though we returned their max chance max okay thank you for watching | 2024-03-22 10:52:11 | 221 | LeetCode 221. Maximal Square Explanation and Solution |
|
itiX24VyGZo | all right so this is 674 and it's called longest continuous increasing longest continuous increasing subsequence so subsequence so it's an easy level question i would say it's an easy level question i would say it's a very easy question it's a very easy question and and here we're given a nums array along with here we're given a nums array along with an output that we need to an output that we need to return which is an integer return which is an integer and what we want to do is we want to and what we want to do is we want to iterate through this array and just find iterate through this array and just find the longest the longest kind of increasing subsequence so kind of increasing subsequence so exactly what the the title says and what exactly what the the title says and what that would be is that would be is this here so this here so it goes from one to three and three is it goes from one to three and three is greater than one and then it increases greater than one and then it increases to five to five and then it decreases to four and then and then it decreases to four and then increases to seven increases to seven so the longest number of times that it so the longest number of times that it was increasing in a sequence four is was increasing in a sequence four is three so one two then three three so one two then three and then here it decreases so it kind of and then here it decreases so it kind of breaks that sequence breaks that sequence and then here it only increases one so and then here it only increases one so that would be one and well that would be one and well a sequence of three is longer than a a sequence of three is longer than a sequence of one sequence of one and so in this case and so in this case it's just going to be one so we know it's just going to be one so we know that a one's kind of the default output that a one's kind of the default output that we would output so even if you have that we would output so even if you have an array of size 1 an array of size 1 we would want to output 1 in that case we would want to output 1 in that case and so yes why don't we go ahead and and so yes why don't we go ahead and implement that so implement that so what we would need for this question is what we would need for this question is a couple of integers so we would want a couple of integers so we would want the max which would set to zero the max which would set to zero we would want the previous value so we would want the previous value so we'll keep a pointer we'll keep a pointer to the previous value that we visited to the previous value that we visited and let's see a count and that would be and let's see a count and that would be set to zero so the count would be set to zero so the count would be the current the current um um number of times this sequence is number of times this sequence is increasing increasing so with each iteration that's increasing so with each iteration that's increasing we'll we'll increment that count increment that count and if the count is greater than our max and if the count is greater than our max we'll set the max equal to our account we'll set the max equal to our account okay so okay so before all this we'll first just do a before all this we'll first just do a base check so base check so it starts we don't have to assume we can it starts we don't have to assume we can assume that the length is at least one assume that the length is at least one so if so if the length of our the length of our array array is equal to one we're just going to is equal to one we're just going to return one return one and so and so we want to do that just because we're we want to do that just because we're using this previous value and how i'm using this previous value and how i'm implementing the for loop we might get a implementing the for loop we might get a index out of bounds error so this is index out of bounds error so this is just a quick check for that just a quick check for that and so afterwards we'll actually set our and so afterwards we'll actually set our previous previous equal to equal to nums at zero nums at zero so with the first iteration that means so with the first iteration that means we'll set i equal to one we'll set i equal to one and and so forth so well i is less than the so forth so well i is less than the length of our array length of our array and we're just going to iterate by one and we're just going to iterate by one of course of course and by the end of this as you might and by the end of this as you might assume we're going to return our max assume we're going to return our max as we want the max increasing as we want the max increasing subsequence or longest i guess subsequence or longest i guess and so and so yeah so let's go ahead and implement yeah so let's go ahead and implement this what do we need here we want to say okay first if our max is less than our account of course our new max will be equal to and at the end of each iteration we also and at the end of each iteration we also want to set our previous equal to our want to set our previous equal to our current current so nums at i we're iterating by one our account we're iterating by one our account we have we have our max which we're we have we have our max which we're setting here setting here the count so if the count so if our current nums at i our current nums at i is greater than our previous then we'll want to set our count otherwise otherwise if our if our oh i spilled that wrong oh i spilled that wrong otherwise if our current number isn't otherwise if our current number isn't greater than our previous greater than our previous therefore it's no longer so this would therefore it's no longer so this would mean that it's increasing mean that it's increasing or i'll say still increasing no longer increasing and so in that case we would just want to say our and then and then max is equal to count that our account is no longer increasing yeah let's go ahead and run that i think that's right all right so we want to set our count all right so we want to set our count equal to one in this case equal to one in this case and here and here because we want a minimum of at least because we want a minimum of at least one one just like how we're returning one here just like how we're returning one here let's go ahead and submit that and success so yeah so that error was just that because we want to return one no matter what we wanted to reset our account equal to one rather than zero so yeah i hope that helped i think it's very simple problem i think the the main issue with this is just making sure that you don't get that index out of bounds error when you're using that previous pointer so great good luck with the rest your | 2024-03-20 15:54:31 | 674 | 674. Longest Continuous Increasing Subsequence Java Solution |
|
ly72kgo3elg | hey everybody this is Larry I hit the like button hit the subscribe button let like button hit the subscribe button let me know how you're doing this farm I'm me know how you're doing this farm I'm gonna stop alive right about now 4:43 gonna stop alive right about now 4:43 strain compression given in a way of strain compression given in a way of strings compress it in place that's strings compress it in place that's always a little bit weird I always hate always a little bit weird I always hate in place things for reason that I could in place things for reason that I could get didn't do the length after get didn't do the length after compression must always be smaller than compression must always be smaller than or you go to the original way every or you go to the original way every element of their way should be a element of their way should be a character that end of length one character that end of length one after you're done modifying to input after you're done modifying to input away in place we turned a new length of away in place we turned a new length of their way could you solve it using only their way could you solve it using only one extra space I thought that's what one extra space I thought that's what the employs would do okay let's see you the employs would do okay let's see you give in some place and this is if you give in some place and this is if you see okay see okay does it have to be consecutive okay I does it have to be consecutive okay I guess it doesn't really actually say or guess it doesn't really actually say or the examples are not super clear on this the examples are not super clear on this one I mean I mean something of a one I mean I mean something of a cheating it on an interview you know the cheating it on an interview you know the thing to do it on an interview if you're thing to do it on an interview if you're having any questions just ask the having any questions just ask the interviewer right I can't do that interviewer right I can't do that incompatible whamming before it is incompatible whamming before it is because they will give you the answer I because they will give you the answer I just want to see unless that I miss just want to see unless that I miss something obvious that what I do answers something obvious that what I do answers to fine you know move to a to the back to fine you know move to a to the back for example like should do ace for example like should do ace compressed together like is it is it compressed together like is it is it next to each other that's what I want to next to each other that's what I want to know why is this returning in pins oh know why is this returning in pins oh it's the size of their new away okay it's the size of their new away okay not just Oh I guess I don't tweak it okay let's just look at the expected okay their input/output it's a little bit weird for this problem that's why I'm having a little bit slow reading it but okay so it seems like it is only next to each other so okay so this is essentially a one length encoding which is a way common thing and there are a couple of ways to think about it but the idea in general is just use a 2.2 algorithm sorry not a to point out one but just kind of keep track of consecutive elements and then the old one extra space is a little bit we and even the in-place stuff is kind of weird to be honest because I don't know why you need to because that's just because I would say that in a software engineering sense way often you do not need to do things in place that's at best or and yeah at best like an optimization but your API if you if you change it the input that feels a little weird especially nowadays because that's where these two bugs and stuff like that but yeah okay but that's it so the one coat one length encoding and was a little bit tricky because we might I guess the compression always makes it shorter so it would would necessarily be good okay I mean the way that I would check is just one character at a time so I I was thinking about how to implement this maybe I would have used a little bit to some pythonic coding stuff but I think I'm just gonna make the code a lot of readable we make the code readable so let's just do something like n is you go to length of chars and then floor index in range of n and I may be off by one here sir so that's just for now let's stop one so then we can compare choice of index with choice of index of my minus one so what happens if they're the same right if they're the same that means that we extend the last index by one right so so in that case we just have let's just have kept the increment by one and one is how do we start well they stopped of processing the first character because in that case the index minus one is well our bounds so let's just start f1 and then we put the last character use here's you go to choice of index oh sorry the first character so that and then yeah then else meaning if they're not equal that means that a string has ended with some choice of index as a new character so that means that okay now we have two so they're a couple of things I want to put two I don't want to skip ahead a little bit so I'm gonna put it not in place just to visualize it and then we'll do it in place and the reason why I do it this way is just for visualization because I think otherwise I'm doing like two things at the same time and it may be a little bit harder to follow but let's just have an answer away and then you know damn is that okay that choice of index is starting a new string or a new one length compression thing right so then let's put the answers so that you last count and then the count I'm just double checking whether we need to put the count as one okay so if there's only one character we do not need to put the cat okay yeah that's also coming with one length and coding so that's why I need to look for it but yeah if count is greater than 1 then we append the string version of the cow and now we just have to reset and start a new thing so we just said that and count as you go to 1 and now we're done except for at the very end right because the curse we don't because you could think about the last string as as yeah like an like an ang drink so actually why I could also hear well what I would maybe sometimes do is add a CP do these if statements again but another way of doing it is actually hand doing this chores done a pen just like some end of string type thing and then now let's print out answer because we have to do it in place but you know and then we return the length of the answer and I know that this is wrong per se because we have to do it in place so we didn't put it out but I just wanna get to a place where we double check whether our answers are correct just for testing purposes yeah and it seems like this matches to expect it and put an output wait we just have to put it back into the in place kind of thing okay so now we want to do it in place which is somewhere that I don't like but that's another rent for another time but but what are we doing with this answer away right and if this compression you know that the string that you're up you're creating will always be smaller than your original string and and index that you're processing so do you think that knowledge let's just say we have another thing called answer index maybe some instead of doing and to that a pen instead of doing and to that a pen that's character we just do choice of that's character we just do choice of answer index is the code to last answer index is the code to last character enter index + + and then here character enter index + + and then here again chose enter index is equal to again chose enter index is equal to string of care and then answer index 1 string of care and then answer index 1 and now at the way and it's just the and now at the way and it's just the answer index is the number of items answer index is the number of items right cool yeah let's now test some right cool yeah let's now test some cases with empty string someone say oh cases with empty string someone say oh is it all lowercase no ask you while you is it all lowercase no ask you while you do I think it is worth testing it is do I think it is worth testing it is worth testing mixing casing I think worth testing mixing casing I think that's like a something like that that's that's like a something like that that's one done yeah looks okay so that's one done yeah looks okay so that's submit oh no oh okay well that's crappy every element of each cow should be counted that end of length one okay I mean I guess I didn't read the problem precisely I wish that there's a test case for that wait David did I not copy the test oh that's okay I retract that statement for some reason I think I was used to order example cases being in there but a parent that is in one of the examples so I have no one to blame but myself I accept responsibility for this one but that is a because if I wear the code it would be you know I would have easily showed that that is well obvious so I just I just have a blind spot and then put in the test case this time but that's fine so in this case and this is still a compression but because for this to be double digits it will be ten anyway like ten or more so you're already compressing a lot of things so you don't have to worry about it over overflowing your current one time thingy for that reason so that's just say string version of the cow and count string is he going to care for each digit in counts string we took this okay so now we're good well better I okay so now we're good well better I don't know if it's good we're some it don't know if it's good we're some it again oh wow oh well that's unfortunate again oh wow oh well that's unfortunate so what so you may ask why I'm getting a so what so you may ask why I'm getting a wrong answer just because I asked you I wrong answer just because I asked you I think I'm just too used to characters think I'm just too used to characters being being alphanumeric that this time being being alphanumeric that this time so that's why I just put in like a so that's why I just put in like a random string at the end right random string at the end right but this random string is part of a but this random string is part of a possible output so it basically made my possible output so it basically made my output wall so so I think that's output wall so so I think that's actually a good that's a funny one that actually a good that's a funny one that uh you know make sure you really read uh you know make sure you really read the constraints and so forth right but the constraints and so forth right but yeah and we can hack this budget we yeah and we can hack this budget we noticed that every input is one noticed that every input is one character I think that's in constraints character I think that's in constraints as well in either case I think yeah so as well in either case I think yeah so we can't just make this like something we can't just make this like something like that and that should be okay I like that and that should be okay I think because then that would never think because then that would never match anything maybe you just want an match anything maybe you just want an imp why you that never matches anything imp why you that never matches anything right right oops right right oops that's a funny one and it happens at the that's a funny one and it happens at the very end so that was a very very very very end so that was a very very very unlucky but still incorrect are you unlucky but still incorrect are you deserving the unlucky but like what are deserving the unlucky but like what are the odds stand the test case isn't the odds stand the test case isn't literally because there's no only literally because there's no only trigger if in the test case there's trigger if in the test case there's literally a case where the dollar sign literally a case where the dollar sign is at the very end but uh which I don't is at the very end but uh which I don't know how what are the odds fit uh but know how what are the odds fit uh but apparently it is none soon okay so yeah apparently it is none soon okay so yeah so this is - that the - silliness seems so this is - that the - silliness seems relatively straightforward in the sense relatively straightforward in the sense that wanting one code and one length that wanting one code and one length encoding is pretty standard so the way encoding is pretty standard so the way that I did it is kind of a little bit that I did it is kind of a little bit static yeah let's let's figure out the static yeah let's let's figure out the complexity so for you to count do we complexity so for you to count do we only look at it once only look at it once so it's gonna be off n it how much space so it's gonna be off n it how much space are we using we only keep track of the are we using we only keep track of the last character and answer index and the last character and answer index and the current running count so this is all of current running count so this is all of one extra space there is stuff about in one extra space there is stuff about in place and space complexity that is worth place and space complexity that is worth its own video so I don't want to get its own video so I don't want to get into that I am NOT a fan of this way of into that I am NOT a fan of this way of counting space because conceptually you counting space because conceptually you will return a separate and so away or will return a separate and so away or something like then that's obviously off something like then that's obviously off event space because you can't do better event space because you can't do better than that than that whoa k space for some K which is output whoa k space for some K which is output sensitive but but yeah oh for what I was sensitive but but yeah oh for what I was just saying about I mean on interview I just saying about I mean on interview I could see maybe maybe without the in could see maybe maybe without the in place but but one thing for encoding is place but but one thing for encoding is something that comes up all the time so something that comes up all the time so I I would recommend just practicing a I I would recommend just practicing a little bit on competitive programming I little bit on competitive programming I think to be honest this is one of those think to be honest this is one of those things that well one is you should things that well one is you should practice it own because it's fun it is practice it own because it's fun it is very foundational for this problem and very foundational for this problem and just like keeping track and making sure just like keeping track and making sure the states are in a good place and maybe the states are in a good place and maybe even coming up with sento values but even coming up with sento values but imply doesn't come up that much in imply doesn't come up that much in competitive programming because this is competitive programming because this is quite too much on an easy side oh yeah quite too much on an easy side oh yeah but this is how I do it I think one but this is how I do it I think one thing that I just want to go over a thing that I just want to go over a little bit more is how how I did it was little bit more is how how I did it was a little bit hand wavy how we converted a little bit hand wavy how we converted it from in a way to do it in place there it from in a way to do it in place there are a couple of places where it was hand are a couple of places where it was hand wavy so the number one one is I hope wavy so the number one one is I hope that the conversion is straight for it that the conversion is straight for it basically we just start from the basically we just start from the beginning and we just literally put it beginning and we just literally put it in in place in the choice away one count in in place in the choice away one count at a time so I think if you had to code at a time so I think if you had to code that we had earlier then you should be that we had earlier then you should be able to see that this is way this should able to see that this is way this should be obvious in the conversion because we be obvious in the conversion because we just want one to one so the question just want one to one so the question that you might have is well that you might have is well what if you overwrite something that you what if you overwrite something that you had need to process later right I think had need to process later right I think that's the part that maybe it's a little that's the part that maybe it's a little bit tricky to prove and I think in my bit tricky to prove and I think in my head I knew that to be right but I head I knew that to be right but I didn't I didn't showed that correct but didn't I didn't showed that correct but you know I'm gonna do that now way like you know I'm gonna do that now way like so let's say you have some input so so let's say you have some input so there are only a couple of cases right there are only a couple of cases right what one is if you have to count it as what one is if you have to count it as only one of them like that's a dis then only one of them like that's a dis then this a is five itself so in this case this a is five itself so in this case and this is why we test one of the and this is why we test one of the example is that if there's only one example is that if there's only one character we don't have to write the character we don't have to write the number which is which makes sense number which is which makes sense depending on their type yeah oh that's depending on their type yeah oh that's just a constraint of the problem right just a constraint of the problem right so in that case well at most you will so in that case well at most you will have you know this match it if you want have you know this match it if you want to consider them two pointed one point to consider them two pointed one point of being the index here which is the of being the index here which is the index or a pointer that points to what index or a pointer that points to what you're processing and then another you're processing and then another pointer which is the answer index which pointer which is the answer index which points here well in this case do part points here well in this case do part after you process this so then you move after you process this so then you move the point for it then you overwrite this the point for it then you overwrite this here then you move the pointer for it so here then you move the pointer for it so because so in the case where so in the because so in the case where so in the case that all the numbers or all the case that all the numbers or all the inputs are unique and by itself you're inputs are unique and by itself you're gonna move them one at a time in a step gonna move them one at a time in a step lock kind of way so so that so you will lock kind of way so so that so you will never so the second point we're never never so the second point we're never over overtake the first point right now over overtake the first point right now in the second case well what are the in the second case well what are the possible cases where other than one well possible cases where other than one well the answer for someone like this is to the answer for someone like this is to go to over - what does 3 look like so from this you can also like dot dot dot this a little bit but from this you can see that you know if if they we have given two A's or two of the same letter or input this will also give it to size answer so it's the same logic as before of the ones you just move to and it's a little bit delayed due process the top one at a time and then and then after two characters you're like okay this is different orders enter the current one and then you push out the output of two characters or two output at the same time right so in that case the output will never pass the input and then now the other cases are more easier to see and that well you have three or more then the output is even slower than then their input right soon so then you can never overpass it and that's kind of a pseudo proof by exhaustion and and the only other thing was that we talked about and I had a little bit of a bug waa about is that we were doing like if if this is you go to 10 or more misspent white dot dot and this is to go to ten right well well well in this case by definition you have ten of these here and it converts no two spaces way so that's still slower than your your input it will always be faster than your output so that's that allows me to be very confident so I was thinking about this during solving was that this gives me a lot of confidence to be able to do this without worrying about like additional checks and stuff like this yeah and one thing to kind of go over is so another question is why drive this and know in the beginning right and the reason why I've descent know in the beginning is okay let's say we don't have this what happens what happens is that if the last character of their way let's say we're here so they say index let's say we're here so they say index is pointing here so index minus one is is pointing here so index minus one is pointing here at the one next to it and pointing here at the one next to it and then it just only does this increment then it just only does this increment count is to go to puzzle my she goes to count is to go to puzzle my she goes to one right but it doesn't output it to one right but it doesn't output it to their way so what normally I mean not their way so what normally I mean not normally but another way you can handle normally but another way you can handle it is okay now at the very end we check it is okay now at the very end we check to see if count is greater than zero to see if count is greater than zero that means if K is greater than 0 then that means if K is greater than 0 then that means we end it on a run and then that means we end it on a run and then we do some processing this way which is we do some processing this way which is basically copy and paste of disk look so basically copy and paste of disk look so you can do someone like that right but you can do someone like that right but if you look at the way that this code is if you look at the way that this code is is that well there is copy and pasting is that well there is copy and pasting right and copy and pasting is not great right and copy and pasting is not great it's not dry it's not you know pretty it's not dry it's not you know pretty and also you recall we did have a bug and also you recall we did have a bug where we had to change this at the very where we had to change this at the very end right so so like if you look at the end right so so like if you look at the first version of it I would have to first version of it I would have to change this T's code to this and then I change this T's code to this and then I have to go down here to change this code have to go down here to change this code to that as well to this as well like so to that as well to this as well like so it's bad way dry it's not very great it's bad way dry it's not very great it's kind of ugly right so what I did it's kind of ugly right so what I did instead was create a value where when I instead was create a value where when I append this end of end of string append this end of end of string character this basically it's a case character this basically it's a case where one is and will always process where one is and will always process this number at the very end or just this number at the very end or just input at the wei-yin and also that this input at the wei-yin and also that this would never be true so that by default would never be true so that by default is a sentinel value which is that this is a sentinel value which is that this will always execute at the very end and will always execute at the very end and that means that this code will get that means that this code will get executed at the very end no matter what executed at the very end no matter what it is to append the answer to the to the it is to append the answer to the to the empresa way and that's why I have this empresa way and that's why I have this at the beginning so that we can process at the beginning so that we can process it later you can also do it a little bit it later you can also do it a little bit differently but that's how I handle the differently but that's how I handle the standard values standard values but yeah that's what I have for this but yeah that's what I have for this problem let me know what your Frank hit problem let me know what your Frank hit the like phone hit the subscribe button the like phone hit the subscribe button and I will see you next time | 2024-03-22 12:33:51 | 443 | 443. String Compression (Leetcode Easy) |
|
pXG3uE_KqZM | hi guys welcome to algorithms made easy my name is khushpu my name is khushpu and in this video we'll see the question and in this video we'll see the question longest string chain longest string chain given a list of words each word consists given a list of words each word consists of english lowercase letter of english lowercase letter let's say word1 is a predecessor of word let's say word1 is a predecessor of word two two if and only if we can add exactly one if and only if we can add exactly one letter letter anywhere in word one to make it equal to anywhere in word one to make it equal to word two word two for example abc can be said to be a for example abc can be said to be a predecessor predecessor of abac because after adding of abac because after adding a in this abc we can get the word to a in this abc we can get the word to now a word chain is a sequence of words now a word chain is a sequence of words word one to word k word one to word k with k greater than equal to one where with k greater than equal to one where word one is a predecessor of word two word one is a predecessor of word two word two is a predecessor of word three word two is a predecessor of word three and so on and so on we need to return the longest possible we need to return the longest possible length of a word chain length of a word chain with words chosen from the given list of with words chosen from the given list of words words so here we are given an example wherein so here we are given an example wherein we are given these words we are given these words and we need to find the longest word and we need to find the longest word chain so the word chain can be either chain so the word chain can be either a b a b c a a b a b c a and b d c a or you can say a and b d c a or you can say a b a b d a and b d c b a b d a and b d c a or you can also say b b a or you can also say b b a b c a and b d c a and a b c a and b d c a and b b a b d a and bdca b b a b d a and bdca so you can get four combinations and the so you can get four combinations and the longest longest length of that is four so the output length of that is four so the output over here is four over here is four in the second example all of these in the second example all of these combined can form the longest chain combined can form the longest chain because if you because if you add a letter c to xb you will get xbc add a letter c to xb you will get xbc if you add a letter c to this one you if you add a letter c to this one you will get will get cxbc and then if you add p to it you cxbc and then if you add p to it you will get this will get this and when you add f to it you get the and when you add f to it you get the last word which is last word which is this one so the longest chain this one so the longest chain that could be formed is of length five that could be formed is of length five constraints given over here constraints given over here are related to the length of words and are related to the length of words and the length of the length of each string in this word array another each string in this word array another thing that is given to us thing that is given to us is that it will only contain english is that it will only contain english lowercase lowercase letters now let's see how we can solve letters now let's see how we can solve this question what are the intuitions this question what are the intuitions that we can get that we can get in order to proceed further taking the in order to proceed further taking the first first example that was given to us in the example that was given to us in the question we can say that question we can say that we have these two combinations that are we have these two combinations that are present and in these two combinations present and in these two combinations also we have also we have different paths that are possible in different paths that are possible in order to form order to form the word chain so if you look at this the word chain so if you look at this one you'll get one you'll get a you add a b in that you get a b a a you add a b in that you get a b a in this ba you either add a c or a d and in this ba you either add a c or a d and you get you get these words and in these words you can these words and in these words you can add one more letter add one more letter and you get this word and so the length and you get this word and so the length that that can be for this path is 4 similarly can be for this path is 4 similarly if you start with b you can get the word if you start with b you can get the word chain of length chain of length 4 and the maximum over here is 4 so 4 and the maximum over here is 4 so the answer would be 4. now what do you the answer would be 4. now what do you understand from this understand from this one of the things that we can get to one of the things that we can get to know about this is that know about this is that we can say we can start from the lowest we can say we can start from the lowest letter and from there the length of the letter and from there the length of the string string that is being formed goes on increasing that is being formed goes on increasing so so the length goes from low to high if we the length goes from low to high if we start from the lowest one start from the lowest one and so to get this in order and so to get this in order we can do a sort on our input on the we can do a sort on our input on the basis of basis of length that is first we take the length that is first we take the smallest one and then we go to the smallest one and then we go to the larger one larger one the second thing that we can see over the second thing that we can see over here is here is the branches that we are getting so the branches that we are getting so over here you can see that you have over here you can see that you have multiple branches that are coming out multiple branches that are coming out from from ba and so we can say that ba and so we can say that the result that we'll get at this the result that we'll get at this particular point particular point can be reused in all the branches that can be reused in all the branches that are going out of this are going out of this word string and so we can perform word string and so we can perform memoization memoization to reduce the time that we would need to to reduce the time that we would need to recalculate the answer for recalculate the answer for a particular word string that is given a particular word string that is given to us so now we know we can do two to us so now we know we can do two things one things one is sort and second is use memoization is sort and second is use memoization so let's start using this now i have so let's start using this now i have taken this particular path for my taken this particular path for my example so i have removed the b that was example so i have removed the b that was given to us in the question given to us in the question and just we are taking this path and we and just we are taking this path and we will apply will apply sort so sorting is done based on the sort so sorting is done based on the length and so this length and so this would be the result for the sort now for would be the result for the sort now for memoization we are going to use a map memoization we are going to use a map the map would store the string and the the map would store the string and the result for that particular string that result for that particular string that is is what is the maximum chain length that we what is the maximum chain length that we could have for this particular could have for this particular string starting with the first one we string starting with the first one we add add this string with the chain length of one this string with the chain length of one because because this is going to be a default that one this is going to be a default that one word can word can at least occur in the chain so one would at least occur in the chain so one would be our default be our default length of the chain and now we'll start length of the chain and now we'll start deleting the characters from this deleting the characters from this particular string to see particular string to see whether the smaller string exists in our whether the smaller string exists in our map or not if that exists we can use the map or not if that exists we can use the result for that particular string result for that particular string instead of recalculating it so let's see instead of recalculating it so let's see how we can reuse the result how we can reuse the result too over here we take a and we start too over here we take a and we start deleting a character so this arrow deleting a character so this arrow denotes the character that we are denotes the character that we are deleting from the string deleting from the string if we delete a we get a blank string and if we delete a we get a blank string and this string is not present this string is not present in my map so i do nothing but i need to in my map so i do nothing but i need to look for the other word in the array look for the other word in the array so in the array i go to the next so in the array i go to the next position position which is ba and over here i'll add this which is ba and over here i'll add this in the map with the default value of 1 in the map with the default value of 1 and now i'll and now i'll start deleting the characters if i start deleting the characters if i delete b from here the string that is delete b from here the string that is left with me is a left with me is a and i already have a calculated result and i already have a calculated result for this a which was for this a which was 1 and so i can use that result to find 1 and so i can use that result to find the one for the current string that is the one for the current string that is ba ba and the result would be either the and the result would be either the result result for ba that is there in the map or the for ba that is there in the map or the result for the smaller string result for the smaller string that is this a plus 1 for the string that is this a plus 1 for the string ba that is the current string so it ba that is the current string so it gives me gives me max of value for ba or value for a max of value for ba or value for a plus 1 and that would give me 2 as a plus 1 and that would give me 2 as a result for result for ba now again we will move forward to bca ba now again we will move forward to bca so we move over here and we add it in so we move over here and we add it in the map with a default value the map with a default value now we start deleting characters now we start deleting characters what happens when you delete b you get what happens when you delete b you get ca which is not there in the map ca which is not there in the map so you do nothing but you try to delete so you do nothing but you try to delete another character another character so here i have taken the example of so here i have taken the example of deleting deleting c from this string if we delete this we c from this string if we delete this we get get b a and b ba has already been calculated b a and b ba has already been calculated and its result is 2 and its result is 2 so we can reuse this result and the so we can reuse this result and the answer for bca would be answer for bca would be max of bca that is 1 or ba plus 1 that max of bca that is 1 or ba plus 1 that is is 2 plus 1 and that gives me maximum of 3 2 plus 1 and that gives me maximum of 3 and i store that in my map as a new and i store that in my map as a new result for bca result for bca next we go to bda and perform the next we go to bda and perform the similar checks similar checks again i have the smaller string ba in it again i have the smaller string ba in it and i do not have any other combination and i do not have any other combination that is i do not have that is i do not have ba or bd so i only have ba and i am ba or bd so i only have ba and i am showing it for ba showing it for ba but in reality you will have to iterate but in reality you will have to iterate and try to delete each and every and try to delete each and every character character from this string so for this one also my from this string so for this one also my answer would get updated to 3 answer would get updated to 3 going forward i take bdca going forward i take bdca now by deleting d from here now by deleting d from here i can get the string bca or by deleting i can get the string bca or by deleting c i can get the string bda so let's try c i can get the string bda so let's try to delete d to delete d we get bca and my result would become we get bca and my result would become either the result for bdca or either the result for bdca or bca plus 1 and that comes out to be bca plus 1 and that comes out to be 4 now let's try to delete c and we'll 4 now let's try to delete c and we'll get get bda and the result for that is also 3 bda and the result for that is also 3 so my maximum would not change in this so my maximum would not change in this particular particular scenario and would remain 4 itself now scenario and would remain 4 itself now we have come to the end we have come to the end and we have all the result in this map and we have all the result in this map and over here this result comes out to and over here this result comes out to be 4. so how do you store this result be 4. so how do you store this result you can have a variable and you can you can have a variable and you can update this variable whenever you are update this variable whenever you are trying to update the value in the map trying to update the value in the map and so at the end when you are done with and so at the end when you are done with the iteration you will also have your the iteration you will also have your answer in this result so that's it for answer in this result so that's it for the theory part the theory part now let's go ahead and code this now let's go ahead and code this particular approach out particular approach out and then we will see the time and space and then we will see the time and space complexity for this particular problem complexity for this particular problem as seen in our theory part we are going as seen in our theory part we are going to to sort on the length and so i'll do sort on the length and so i'll do arrays dot sort onwards and i'll take arrays dot sort onwards and i'll take length as a parameter so over here length as a parameter so over here let's write the comparator logic and let's write the comparator logic and that would take that would take length so this would do a sort on words length so this would do a sort on words and arrange my words in increasing and arrange my words in increasing length now i'll take a result variable length now i'll take a result variable that will initially be 0 and i'll take a that will initially be 0 and i'll take a map map and this map will contain string and and this map will contain string and integer integer i'm keeping its name as memoization memo i'm keeping its name as memoization memo because this is used for memoization now because this is used for memoization now we'll start iterating on the we'll start iterating on the words and these words are in the words and these words are in the increasing order of the increasing order of the length so i'll take for each loop length so i'll take for each loop and in here the first thing that i do is and in here the first thing that i do is put the current word in map so i'll do memoization dot put the word that i'm having with the default value of one once i have this i'll iterate for each and every character in the map and try to delete it so i'll take in i equal to 0 i less than word dot length and i plus plus over here i want to delete the character so i'll take this word in a string builder and then perform the delete so i'm taking the word as a current word so i'm taking the word as a current word and then i'll create the next word out and then i'll create the next word out of it so of it so this becomes the word after deleting the character at ith position now i need to check whether i have the answer for this word in my memoization map so i'll do if my map contains the key next i need to update the value in map with the maximum possible value and thus i'll once i am done with this particular loop once i am done with this particular loop i need to update i need to update my result variable also and that would my result variable also and that would become become maximum of either result maximum of either result or the answer that we have got for the or the answer that we have got for the current word finally current word finally return the result so that's it return the result so that's it let's try to run this code and we are let's try to run this code and we are getting a perfect result getting a perfect result let's try to submit this and it got let's try to submit this and it got submitted now let's see submitted now let's see how we can calculate the time and space how we can calculate the time and space complexity for this particular problem complexity for this particular problem considering n as the length of this considering n as the length of this words and words and l as the length over here that is l as the length over here that is the word dot length so for this sort the word dot length so for this sort we are going to require a time we are going to require a time of n log n and of n log n and this is going to be iterating this is going to be iterating for a time of n that is for a time of n that is for the length of array now in here we for the length of array now in here we are going to iterate are going to iterate in this loop for the length of board and one more thing that we have is this delete caret function and that uses the time complexity of length now we know the time complexity for all the pieces that we have so for this whole loop the time complexity would become length into length that is length for this multiplied by length for this secondly when we go over here this becomes multiplied by this whole so we write this and the total time complexity becomes n log n plus the time complexity for the loop that is n into length into length the space complexity is there for this map and so we can say that the space complexity is o of n and if you are trying to take the length into consideration 2 then you can multiply this with length that is the length of the word or else you can simply write o n if you want so that's it about this question guys i hope you like the video and i'll see you in another one so till then keep | 2024-03-25 16:14:07 | 1,048 | Longest String Chain | Live Coding with Explanation | Leetcode - 1048 |
|
lXY2oiDlc1E | in this video we're going to take a look at a legal problem called sliding window at a legal problem called sliding window median median so median is basically the middle value so median is basically the middle value in an in an order integer list so the size of the order integer list so the size of the list list is even then there's no uh middle value is even then there's no uh middle value so we gotta so we gotta have to find the average of the two have to find the average of the two middle value so middle value so here you can see we have an example of here you can see we have an example of two three four right so if we have two two three four right so if we have two three four the medium three four the medium is going to be three because the middle is going to be three because the middle value is three because the list is all value is three because the list is all right so the size of the list is odd right so the size of the list is odd it's an odd number and if we have a size it's an odd number and if we have a size of of this is even number like this 2 3 then this is even number like this 2 3 then the median is going to be 2 plus 3 the median is going to be 2 plus 3 divided by 2. okay so in this case we divided by 2. okay so in this case we have 2.5 have 2.5 so given array of nums there is a so given array of nums there is a sliding window of size k sliding window of size k which is moving from left to right to which is moving from left to right to left of the array to the right left of the array to the right so uh you can only see the k so uh you can only see the k numbers in the window so each time the numbers in the window so each time the slide in window slide in window moves right by one position your job is moves right by one position your job is to output the medium to output the medium of the window current the current window of the window current the current window right where i say each window in the right where i say each window in the original array original array so for example if we have an array like so for example if we have an array like this and k is this and k is three so in this case you can see the three so in this case you can see the the window are sliding the window are sliding now the median is one right because the now the median is one right because the middle value is one middle value is one and in this case there could also be a and in this case there could also be a situation where the median situation where the median is negative one right in this case is negative one right in this case the median is negative one and the the median is negative one and the median here median here is going to or i just say the middle is going to or i just say the middle value is going to be three right value is going to be three right and so we basically just store those and so we basically just store those median values into an median values into an array and then we are we're returning array and then we are we're returning this array at the end this array at the end so something that we have to watch out so something that we have to watch out for is for is that we want to make sure k is always that we want to make sure k is always valid so k is valid so k is always smaller than the input array size always smaller than the input array size and the answer and the answer is within this number so of the actual is within this number so of the actual value will be accepted as correct value will be accepted as correct so let's say we have an example of 1 so let's say we have an example of 1 3 negative 1 and negative 3 3 negative 1 and negative 3 5 3 6 7. so negative 3 5 3 6 7. so negative 3 5 3 and six seven right so in this case 5 3 and six seven right so in this case let's say k is equal to four let's say k is equal to four then the median in this case is going to then the median in this case is going to be uh be uh the average of the two middle values so the average of the two middle values so the two middle values gonna be negative the two middle values gonna be negative one and one one and one so the average between those two is so the average between those two is gonna be zero right and uh gonna be zero right and uh if we were to slide our window from here if we were to slide our window from here here right so here right so one to the right then we have a one to the right then we have a middle value so two middle values are middle value so two middle values are negative one negative one and three right uh in this case the and three right uh in this case the average between them average between them uh in this case is gonna be two divided uh in this case is gonna be two divided by two is one by two is one then we slide our window again right so then we slide our window again right so then we slide our window and now it's then we slide our window and now it's here here right including is three so the median right including is three so the median is gonna be is gonna be negative one plus three which is negative one plus three which is in this case it's going to be uh two and in this case it's going to be uh two and two divided by two is zero two divided by two is zero right so our medium or our uh median right so our medium or our uh median value is gonna be zero uh if we slide value is gonna be zero uh if we slide our window again our window again negative three plus five plus three plus negative three plus five plus three plus six so this one right here six so this one right here this window then we're going to have a this window then we're going to have a medium which is gonna be negative medium which is gonna be negative uh hold on yeah it's gonna be three plus uh hold on yeah it's gonna be three plus five five right because those are two middle right because those are two middle values so in this case we're getting values so in this case we're getting eight divided by two is which is four so eight divided by two is which is four so you get an idea right so if it's you get an idea right so if it's even if our window has the size of even even if our window has the size of even number then we're just going to take the number then we're just going to take the two two middle value and then take the average middle value and then take the average of those two so in this case what we can of those two so in this case what we can do is we can use the two heap technique do is we can use the two heap technique right that we just right that we just talked about on how we solve the find talked about on how we solve the find the median of the the median of the data stream problem which is very data stream problem which is very similar basically the idea similar basically the idea is this we're going to have a heap right is this we're going to have a heap right we're going to have our max keep we're going to have our max keep and we're also going to have our mint and we're also going to have our mint heat the idea is that we're going to use heat the idea is that we're going to use our min heap and the max heap to keep our min heap and the max heap to keep track of the middle track of the middle the two middle values or the middle the two middle values or the middle value of our current window value of our current window so usually what we're gonna do is we're so usually what we're gonna do is we're gonna have our input data right so we're gonna have our input data right so we're gonna have a max heat basically to keep gonna have a max heat basically to keep track of track of the first half of our data and the the first half of our data and the maximum value be at the top maximum value be at the top right and uh we're also going to have right and uh we're also going to have min heap min heap basically keep track of the second half basically keep track of the second half of our data of our data uh or our window and the middle value at uh or our window and the middle value at the middle the middle right where i just say the the smallest right where i just say the the smallest element will be at the top of our min element will be at the top of our min heap heap so the middle value is going to be those so the middle value is going to be those two the the top element two the the top element for our min and max heap so we can use for our min and max heap so we can use those two elements to get our those two elements to get our average value and uh or if we have a average value and uh or if we have a situation where situation where one heap has a size that's bigger than one heap has a size that's bigger than the other one then we're just gonna the other one then we're just gonna return the return the the top uh element of a heap the top uh element of a heap and then that will be our median for our and then that will be our median for our window right window right uh if our current size of our window is uh if our current size of our window is odd number odd number so basically the idea is this we're so basically the idea is this we're gonna add gonna add those elements that we have within our those elements that we have within our window onto window onto our heaps right so we have a min and max our heaps right so we have a min and max heap heap so in this case initially we have one so so in this case initially we have one so in this case the rule for min and max in this case the rule for min and max heap heap is that we want to make sure that every is that we want to make sure that every time when we're adding an element we time when we're adding an element we want to make sure we balance the heaps want to make sure we balance the heaps so the rule is this we want to make sure so the rule is this we want to make sure the max heap the max heap the size is the size is if it uh is actually equal to and keep if it uh is actually equal to and keep so men keep that size or so men keep that size or if we have situation where the min keep if we have situation where the min keep that size or that size or sorry the max keep the size is actually sorry the max keep the size is actually equal to equal to min heap the size plus once so we're allowed to have the max heap dot size to be bigger than men keep that size by one so in this case what we're going to do is we're going to first adding the first element onto our max heap so in this case because our max leave is empty so we have one here and then in this case we have a window size which is equal to k k is equal to four so in this case we're just going to keep adding those elements up to k when the size of our window is equal to reach to k right so in this case our max is one and our currently our heaps are balanced so we're just gonna continue to add those elements so in this case one three is bigger than one so we're gonna add it on to our min heap so we have three here and negative one in this case is less than one so we're just gonna add it on to our min uh max heap so far we have our heaps are balanced so now we have negative three negative three in this case is going to be less than one so we add it on to our max heap and in this case we have our heaps are unbalanced so in this case what we're going to do is we're going to remove the top element from our max heap and add it on to our min heap so in this case we're going to have negative one and basically what we're gonna do is and basically what we're gonna do is we're gonna have we're gonna have one here and three at the bottom right one here and three at the bottom right because we have a min heap because we have a min heap so in this case three at the bottom and so in this case three at the bottom and large element at the top large element at the top so then we once we reach the window so then we once we reach the window size which is equal to k then we're size which is equal to k then we're going to get the median so the median is going to get the median so the median is basically a top elements basically a top elements average so negative one plus one in this average so negative one plus one in this case is case is zero divided by two is zero so once we zero divided by two is zero so once we um done getting the median we're gonna um done getting the median we're gonna get our get our left pointer points one to the right so left pointer points one to the right so now we have three now we have three right so in this case to shift our left right so in this case to shift our left pointer or the pointer or the or shrink our window in this case what or shrink our window in this case what we need to do is we need to take the we need to do is we need to take the the top element in this case is negative the top element in this case is negative one one we see if the the element that we want we see if the the element that we want to remove which is in this case is one to remove which is in this case is one is actually inside this heap and to do is actually inside this heap and to do that we check to see if that we check to see if one uh negative one is actually one uh negative one is actually bigger than or equal to one in this case bigger than or equal to one in this case negative one is not bigger than or equal negative one is not bigger than or equal to one to one so therefore the the element that we so therefore the the element that we want to remove which is one in this case want to remove which is one in this case is not inside the max heap so we're just is not inside the max heap so we're just going to remove it going to remove it from the min heap so we know that min from the min heap so we know that min heap we have one here so we're just heap we have one here so we're just going to remove that going to remove that right so now we have three at the top right so now we have three at the top here here okay so then what we're going to do is okay so then what we're going to do is we're going to basically we're going to basically shift our window one to the right and uh shift our window one to the right and uh now we're going to expand our window now now we're going to expand our window now we we add five so five in this case is add five so five in this case is actually bigger than negative one actually bigger than negative one so in this case we're just going to add so in this case we're just going to add it on to our min key so it on to our min key so in this case we have three at the bottom in this case we have three at the bottom and five at the top or i should say and five at the top or i should say sorry three at the top sorry three at the top and five at the bottom because we have a and five at the bottom because we have a min heap so min heap so the median is going to be negative one the median is going to be negative one plus three plus three uh which is gonna be two and two divided uh which is gonna be two and two divided by two in this case it's gonna be zero by two in this case it's gonna be zero uh one sorry so the medium is going to uh one sorry so the medium is going to be one be one and then we're gonna slide our window and then we're gonna slide our window again so we remove the top again so we remove the top uh the left element in this case the uh the left element in this case the left element is three left element is three so we know that three is actually bigger so we know that three is actually bigger than the top element for our max heap so than the top element for our max heap so we're gonna delete it from we're gonna delete it from our min heap so our min heap has a three our min heap so our min heap has a three so we're going to delete it so we're going to delete it here so you can see we have our here so you can see we have our five right so five at the top and five right so five at the top and once we delete it we still know that once we delete it we still know that this current heaps are balanced this current heaps are balanced so we're gonna expand our window again so we're gonna expand our window again now we have now we have um add three right this three right here um add three right this three right here onto our onto our heaps because this three right here is heaps because this three right here is actually bigger than actually bigger than uh negative one so we're going to add it uh negative one so we're going to add it on to our min heap on to our min heap so we're gonna have five at the bottom so we're gonna have five at the bottom and three at the top and three at the top and we know the medium in this case the and we know the medium in this case the median median is going to be um yeah is going to be um yeah is basically going to be the top element is basically going to be the top element from both heap from both heap um the average of those two elements um the average of those two elements right so in this case we have right so in this case we have two divided by two which is one so you two divided by two which is one so you get an idea basically we're just going get an idea basically we're just going to slide our windows to slide our windows get our inserting elements get our get our inserting elements get our median deleting the element median deleting the element the the left element and then shifting the the left element and then shifting the window one to the right the window one to the right so to do this in code basically what so to do this in code basically what we're going to do is we're going to have we're going to do is we're going to have our constructor that defines our min and our constructor that defines our min and max heap max heap and the reason why we use a and the reason why we use a collection.reverse order here is because collection.reverse order here is because there could be a situation where there could be a situation where where we're adding a element that is where we're adding a element that is equal to integer.max equal to integer.max so if that's the case then we want to so if that's the case then we want to make sure we can just use make sure we can just use collection.reverse order so we can't collection.reverse order so we can't really use really use uh a b right so b minus a to get a descending order like that because we have can have a situation where integer is equal the element that we're adding is integer.max so that won't work so we need to use collection.reverse order and then we're going to have a method called add which this basically adds the element right it takes the element we check to see if the max heap is not empty sorry if the max heap is empty we're just gonna add it onto our max heap or if the max heap top element for our max ep is actually bigger than none then we also can be able to add it on to our max heap otherwise if we have a situation where the maxi does uh the top element for our max heap is actually less than or equal to or sorry yeah less than or equal to the number that we're adding then we're just going to add it on to our min heat and at the end we're going to balance our heat and then here you can see we have the removal method right right basically we take the element and check to see if it's actually within our max heap if it is then we're just going to delete it in our max heap otherwise we're gonna you know delete it in our min heap and then we're going to balance it and inside this balance method you can see we first check to see if the maxi dot size is actually bigger than keep that size plus one if it is then we're just going to we know that we're going to take the top element from our backseat and add it on to our min heap and if we have a situation where the mini heap does size is actually bigger than the max heap of the size then we're going to take the element from the min heap and add it on to our max heap in this case that's how we balance our heaps so to find median in this case is the same thing we're just going to see if we have uh whoever has a heap that is larger in size we're just going to return that top element and you notice that here we are basically dividing the top element for each heaps top element by 2.0 the reason why is because there could be a situation where the element that we're adding is actually equal to integer.max so in this case we're dividing that by itself and adding them uh once we get the the the element right in this case we want to make sure we're returning a double and that's why we have 2.0 and then in this case we have a function called meetings median sliding window which takes the array and k and basically we're we're going to have a double array which called result basically this is going to be the size or number of times that we're going to slide our window it's going to be n minus k plus 1 right or number of elements that we have minus k plus 1 which is basically how many times we had to slide our window each time we slide our window we expend uh we basically record or add the median number onto the array and then we're just going to um continue to do that right so in this case what we're going to do is we're just going to start from zero right we have our start which is kind of like our left corner and our n is going to be our right pointer we're going to slide our window until we get to a point where the size current size of our window is actually equal k then we're going to record our median add it onto our result ray and then remove the left element and then we move the left pointer one to the right so then we're just going to continue to repeat the process until we get the end is actually uh bigger than or equal to num delay so in this in this case at the end we're just returning the result array so in this case let's try to run our code and let's try to submit and here you see we have our success so the time complexity in this case for this algorithm right is going to be big o of n log k and the reason why we have a log k here is because log k for removing and deleting uh removing or adding element right removing and adding elements will be log k for time complexity and uh for each iteration in or for each element in the array we have to make sure we do the same process so in this case we have a log k for time complexity and the space complexity in this case is going to be uh big o of n and the reason why is big o of n not big o of k is because we have um this right here right we're basically adding pretty much the elements that we have in all the elements that we have in our window right or each time we slide our window we're basically adding the median number onto the result and if we have situation where k is equal to one right then we want to make sure we're basically adding let's say n minus k plus 1 which is basically n elements onto the the result so in this case we're getting um we're getting it right so the space | 2024-03-22 15:28:46 | 480 | [Java] Leetcode 480. Sliding Window Median [Two Heaps #2] |
|
V4fhgbLsE0k | [Music] hey guys hey guys welcome back to another video and today welcome back to another video and today we're going to be solving the lead code we're going to be solving the lead code question question detect capital uh so i just want to detect capital uh so i just want to mention two things before i get started mention two things before i get started so first i don't have a premium so first i don't have a premium membership so i won't be able to solve membership so i won't be able to solve these questions these questions and second uh if there are any specific and second uh if there are any specific lead code questions that you want me to lead code questions that you want me to answer answer just let me know down in the comments just let me know down in the comments and i'll try to get them answered for and i'll try to get them answered for you you okay so now let's just get started with okay so now let's just get started with the question so we're given a word the question so we're given a word and we need to judge whether the usage and we need to judge whether the usage of capitals of capitals is right or not and it is correct or not is right or not and it is correct or not based upon these three conditions based upon these three conditions so the first one is if we have all so the first one is if we have all capital letters then in that case capital letters then in that case we're going to return true if we have we're going to return true if we have all all lowercase letters that is also going to lowercase letters that is also going to be true be true and if we have only the first letter and if we have only the first letter being being uh upper case and everything else being uh upper case and everything else being a lower case a lower case then that that's also going to be true then that that's also going to be true so these three conditions are going to so these three conditions are going to be true be true and so i'm going to give you two and so i'm going to give you two solutions to solve this one's going to solutions to solve this one's going to be be a more intuitive approach and one's a more intuitive approach and one's gonna be a gonna be a very pythonic way to solve this question very pythonic way to solve this question okay okay so let's just get started with the first so let's just get started with the first one so i'm just gonna write the three one so i'm just gonna write the three cases that we have okay so these are kind of the three uh different conditions that we have and let's just make these into three different if statements and return true if any of these three are true so if all caps so what we're gonna do is we're gonna take our word and we're gonna uppercase everything so if word dot upper so what this does is it's going to make everything into uppercase and if that is equal to our original word then in that case we're going to return true okay so that's one of our conditions and now we have this if all our if all are lowercase so else if so we're so say similar to word.upper we have word.lower so if we lowercase everything and that's equal to our word and in that case we also return true all right so we took care of three of the conditions and now we have the third one so if first letter is a capital and everything else is lowercase okay so what we're going to do is we're going to take the first letter so where it is at the zeroth index and we're going to use the dot upper function on that and if that is equal to word at the zeroth index and if everything after the zeroth index so word from the first index to the ending uh dot lower because uh only the first letter is uppercase and everything else is lowercase so if every so the first letter over here is uppercase and now we're checking if everything else is lowercase and if that is equal to word starting from one all the way to zero then in that case we also return true so these are these are all the three conditions that we need to account for and else if none of these are true then we're just going to return false so let's accept i mean sorry let's submit our solution and okay as you can see our solution did get accepted so now we're going to look at the more pythonic solution to this uh do not use this in an interview by any means i'm just showing it to you because i think it's pretty cool um and python has a lot of inbuilt functions like this so it's just gonna be a one-liner so return so word dot is upper so if everything is uppercase it's going to return true or word dot is lower so if everything is lowercase it's going to return true so we got take so we took care of two of our conditions already and there's also one more which is called word dot is title um yeah is a word dot is title and a title is basically the first letter is capitalized and everything else is lowercase so it's just going to return that and let's and this solution was also accepted and and this solution was also accepted and finally do let me know if you have a finally do let me know if you have a better solution to this better solution to this or if you have any questions regarding or if you have any questions regarding this i'd love to help you this i'd love to help you and finally if there are any leak code and finally if there are any leak code questions that you want me to solve questions that you want me to solve specifically specifically just let me know down in the comments just let me know down in the comments i'll get them solved for you i'll get them solved for you alright thanks a lot for watching and do alright thanks a lot for watching and do let me know what you thought about this let me know what you thought about this video and don't forget to like and video and don't forget to like and subscribe subscribe thank you | 2024-03-22 16:37:50 | 520 | Detect Capital | Leet code 520 | Theory explained + Python code | August Leet code challenge |
|
4LoajzOxF4I | hello so today we are doing problems for this contest weekly contest 169 the this contest weekly contest 169 the first problem is find and unique first problem is find and unique integers that sum up to 0 and so the integers that sum up to 0 and so the problem says if we have an integer N and problem says if we have an integer N and we want to return any array containing we want to return any array containing and unique integers such that they are and unique integers such that they are such that these integers add up to 0 and such that these integers add up to 0 and so for example for n equal to 5 we can so for example for n equal to 5 we can return these 5 numbers so it means it a return these 5 numbers so it means it a number of number the number of integers number of number the number of integers that needs to be in the array but the that needs to be in the array but the additional constraint is that the sum of additional constraint is that the sum of the array has to be equal to 0 for n the array has to be equal to 0 for n equal to 3 you can just take - take equal to 3 you can just take - take minus 1 0 and + 1 right and so how can minus 1 0 and + 1 right and so how can we how can we approach this so the first we how can we approach this so the first there are actually three ways 3 there are actually three ways 3 different ways to look at this problem different ways to look at this problem so the first thing that I can start with so the first thing that I can start with as well what we can do is a simple thing as well what we can do is a simple thing which is just you notice that for even which is just you notice that for even numbers if if n is even what we can just numbers if if n is even what we can just do something very simple just take the do something very simple just take the negative numbers take half of the N negative numbers take half of the N divided by 2 from 1 to n divided by 2 as divided by 2 from 1 to n divided by 2 as positive number and the same numbers as positive number and the same numbers as negative and there some thicker will negative and there some thicker will cancel each other out and so for example cancel each other out and so for example if I have let's say and equal to 2 what if I have let's say and equal to 2 what I can do is just sort from 1 to N I can do is just sort from 1 to N divided by 2 which is 1 so just take divided by 2 which is 1 so just take minus 1 and take the same number but minus 1 and take the same number but positive 2 cancel it out for n equal to positive 2 cancel it out for n equal to 4 and divided by 2 is 2 so go from 1 to 4 and divided by 2 is 2 so go from 1 to 2 which means 1 to 2 positive and do the 2 which means 1 to 2 positive and do the same numbers negative now the only now same numbers negative now the only now when it's even then when it's odd then when it's even then when it's odd then we can do I do something slightly we can do I do something slightly different to just take the same number n different to just take the same number n minus 1 and then just add 0 so that minus 1 and then just add 0 so that because 0 wouldn't because 0 wouldn't anything so the Sun would still be zero anything so the Sun would still be zero in the number of integers will be five in the number of integers will be five right so the way to so the way to think right so the way to so the way to think about this basically as we just need to about this basically as we just need to generate the numbers from 1 to n divided generate the numbers from 1 to n divided by 2 positive and append them to the by 2 positive and append them to the negative values of the same range and negative values of the same range and just as 0 if n is odd and so pretty much just as 0 if n is odd and so pretty much what you can do here is just okay the what you can do here is just okay the clouds the final result here that we clouds the final result here that we will return and then go for the range will return and then go for the range from basically 1 to n divided by 2 which from basically 1 to n divided by 2 which is what we did here in the example so is what we did here in the example so from 1 to N divided by 2 and so in from 1 to N divided by 2 and so in Python that I need to be and divided by Python that I need to be and divided by 2 plus 1 and then we need to append both 2 plus 1 and then we need to append both minus I and the ice without it cancel minus I and the ice without it cancel each other out and if n is odd and so each other out and if n is odd and so that would mean this is different than 0 that would mean this is different than 0 we can just add 0 like this and that's we can just add 0 like this and that's pretty much it service on this okay goodbye segment okay so that works another way to check out using just binary operations is just doing which is a little bit faster but not that much so we can do it that way and this should okay so uh submit okay so that passes and another different method of so this is the first method another way we can do this is we can just generate the numbers from 1 to N minus 1 so basically all the numbers 1 2 & top n minus 1 and now we have n minus 1 numbers right and then we could just to cancel all these out can just take the Sun so call this a the array a and just take the sum of a and put minus 1 so that it can cancel all of them out and so it would be just pretty much just a plus an array containing this and that way this would cancel out a so that the sum of the entire array is 0 and we'd have n elements because a is n minus 1 element and then we are adding one element so we'd have n elements and so that's pretty much would be taking a to be the range from 1 to n minus 1 and to reach n minus 1 we need to put M as the end and to get a list we need to do it like this and then we can just return that plus minus sum of a so that can cancel out and become 0 and the length can become n now we don't need to distinguish odd or even here because this number would be from 1 to n it would be an even number of elements if n was odd and then we'll add 1 and it will be odd and the similar thing 1 n is even right so that's pretty much it it's all and submit it okay so that passes so and submit it okay so that passes so another way to solve this problem is to another way to solve this problem is to think about AB just to generate all the think about AB just to generate all the different cases and see if we can find a different cases and see if we can find a pattern so for n equal to one we can pattern so for n equal to one we can just give 0 right the sum is 0 and the just give 0 right the sum is 0 and the number of element is just 1 right for n number of element is just 1 right for n equal to 0 we can just give the mpls equal to 0 we can just give the mpls right the length is 0 for n equal to 2 right the length is 0 for n equal to 2 we can just have minus 1 and 1 we can just have minus 1 and 1 right they cancel out to 0 and that right they cancel out to 0 and that length is 2 for n equal to 3 we can have length is 2 for n equal to 3 we can have minus 2 2 and we can have 0 and so the minus 2 2 and we can have 0 and so the length is 0 or the length is 3 and the length is 0 or the length is 3 and the sum is 0 for n equal to 4 what we can do sum is 0 for n equal to 4 what we can do is take basically minus 3 take minus 1 0 is take basically minus 3 take minus 1 0 1 & 3 and that's sorry without 0 so 1 & 3 and that's sorry without 0 so that's four elements and the sum is 0 that's four elements and the sum is 0 right for n equal to 5 we can do - 4 - 2 right for n equal to 5 we can do - 4 - 2 0 2 & 4 and you can see this is 5 0 2 & 4 and you can see this is 5 elements and can they cancel out to be elements and can they cancel out to be some 0 so you can notice the pattern some 0 so you can notice the pattern here is basically doing the range from here is basically doing the range from minus n minus 1 right that's what we did minus n minus 1 right that's what we did for 5 we take which we took n minus 1 for 5 we take which we took n minus 1 which is 4 and we did minus 4 same thing which is 4 and we did minus 4 same thing for 3 minus 3 here we did n minus 1 for 3 minus 3 here we did n minus 1 which is 3 and we did minus 3 and then which is 3 and we did minus 3 and then we we go all the way to n minus 1 but we we go all the way to n minus 1 but every time we increase by every time we increase by by 2 because here if you look - - we start from n minus 1 minus n minus 1 which is minus 2 and to increase by 2 to get 0 then we increase by 2 to guess - he o start from n minus 1 which is 3 so minus 3 we are - who give we get minus 1 we had 2 we get one where 2 we get 3 here we start from n minus 1 which is 4 so minus 4 we add 2 we get minus 2 we had to get 0 we had another to get to add another - Lea 4 so you could see this is the idea of the of the solution right and so let's just implement that so in Python we have a function fringe that does exactly this for us so range we give it the start right and then we give it the end and we'll give it this step right and so the start here for us is just minus n minus 1 right and the end is well we want to stop at n minus 1 but we're gonna include it n minus 1 and so to include n minus 1 we need to stop at and here because it will start at just the previous value which is n minus 1 and then the step is - and that's pretty much it now just to make this a little bit easier to read we can enter the - and so we have plus 1 here and we can just put 1 here instead and we have from 1 minus n 2 N and increase every time by I guess I'll submit okay so that's it pretty much so we saw there are three ways to solve this problem and all of them are over an essentially and yeah that's pretty much | 2024-03-20 11:51:12 | 1,304 | Leetcode 1304: Find N Unique Integers Sum up to Zero |
|
SxX8AhuDWic | yes it is or how to be going this video I'm going to take a look at six seven I'm going to take a look at six seven for an easy one longest continuous for an easy one longest continuous increasing subsequent given an unsorted increasing subsequent given an unsorted array I also did array array of integers array I also did array array of integers find the length of longest continuous find the length of longest continuous increasing subsequence sub array so 1 3 increasing subsequence sub array so 1 3 5 4 7 the longest would be 1 3 4 or 1 3 5 4 7 the longest would be 1 3 4 or 1 3 5 so get 3 well yeah I think this could 5 so get 3 well yeah I think this could be done just to just loop through the be done just to just loop through the array and the fine if the number is array and the fine if the number is bigger than the previous one if it is we bigger than the previous one if it is we passed one if not we reset it right yeah passed one if not we reset it right yeah so that's the maximum would be 0 long so that's the maximum would be 0 long case Oh maximum the minimum should be 1 case Oh maximum the minimum should be 1 right right okay so we look through all the numbers okay so we look through all the numbers the previous week we need to get the the previous week we need to get the previous one so we use index okay we previous one so we use index okay we should start with the 1 actually if it should start with the 1 actually if it is bigger than it then we plus 1 so is bigger than it then we plus 1 so let's current max equals parent in N let's current max equals parent in N equals 1 if it's bigger than it then we equals 1 if it's bigger than it then we plus 1 if numbs eye is bigger than arms plus 1 if numbs eye is bigger than arms I'm a swan we current named aslan and I'm a swan we current named aslan and max it was math max max it was math max [Music] okay we don't need to hear actually we could just own it a point to meet some descending once right oh no I just do it here that's cool and then if you make something equal or smaller than it then this should be the map the Karina's should be set to 1 right it means like the fact we met we need 4 then 4 is the law and the current continuous increasing supply finally coming back sure we're right almost empty phenom cement equals zero we return for sure yeah cool so this set isn't it easy one I hope it helps | 2024-03-20 15:55:16 | 674 | LeetCode 674. Longest Continuous Increasing Subsequence | JSer - JavaScript & Algorithm |
|
mWdV3-SxOK0 | hello hello hello hi guys welcome back I hope that you guys are doing good and hope that you guys are doing good and problem night dialers and again in this problem night dialers and again in this video we're going to see all three video we're going to see all three approaches to solve this problem and approaches to solve this problem and we'll code also simultaneously we'll we'll code also simultaneously we'll modify the existing codes itself please modify the existing codes itself please make sure that you look onto all the make sure that you look onto all the approaches and how we progressively go approaches and how we progressively go on it and also for the folks who are on it and also for the folks who are very confused in recursion please make very confused in recursion please make sure in the beginning you just follow me sure in the beginning you just follow me on how actually I get the hint of what on how actually I get the hint of what and how the recursion can be built so I and how the recursion can be built so I have seen many of our followers and have seen many of our followers and folks and many students are actually folks and many students are actually confused on how to actually build the confused on how to actually build the recursion the question itself tells you recursion the question itself tells you that so let's see that how we can that so let's see that how we can actually build the recursion itself we actually build the recursion itself we will not we'll do nothing it's just that will not we'll do nothing it's just that we will read the problem and we'll we will read the problem and we'll follow what he is saying which the follow what he is saying which the problem is saying firstly let's have a problem is saying firstly let's have a quick look that it has been asked by quick look that it has been asked by Amazon in the last 6 months last 6 to Amazon in the last 6 months last 6 to one year and a lot of times asked by one year and a lot of times asked by Bloomberg Facebook Google and Bloomberg Facebook Google and tweo TW okay cool let's see uh the tweo TW okay cool let's see uh the problem says that there's a chess Knight problem says that there's a chess Knight has a unique movement as you know uh in has a unique movement as you know uh in a chest a knight has a unique movement a chest a knight has a unique movement it may move two squares vertically and it may move two squares vertically and one square horizontally and two squares one square horizontally and two squares horizontally or one square vertically if horizontally or one square vertically if you don't know a knight moves like this you don't know a knight moves like this two and then one two and then one two two and then one two and then one two and then one two and then one two and and then one two and then one two and then one two and then one two and then then one two and then one two and then one two and then one this is how a KN one two and then one this is how a KN moves and this is how our movement needs moves and this is how our movement needs to be there cool uh just it says the to be there cool uh just it says the possible movement of the of a knight are possible movement of the of a knight are shown in the diagram below so it is a shown in the diagram below so it is a POS movement so for you to just verify POS movement so for you to just verify that how the Knight will actually move that how the Knight will actually move if you don't know that we have already if you don't know that we have already seen some Knight problems where we know seen some Knight problems where we know that if it is a IJ then what all that if it is a IJ then what all coordinates needs to be these cool a coordinates needs to be these cool a chest Knight can move as indicated in chest Knight can move as indicated in the chess diagram below that is great the chess diagram below that is great now we have a knight okay that that's now we have a knight okay that that's just saying that we have a chess Knight just saying that we have a chess Knight and a phone PAD as shown below the and a phone PAD as shown below the Knight can only stand on the numeric Knight can only stand on the numeric cell that is a blue cell a knight will cell that is a blue cell a knight will not stand here this is no more a place not stand here this is no more a place for the Knight Knight can only stand on for the Knight Knight can only stand on these cells now when I say a knight these cells now when I say a knight stand on these cells if let's say a stand on these cells if let's say a knight is standing on this cell then he knight is standing on this cell then he can move to and then this location so can move to and then this location so from a Knight can move to three which from a Knight can move to three which means if I say that I have my knight on means if I say that I have my knight on a pad eight or a digit 8 it can move to a pad eight or a digit 8 it can move to a next digit as three that is very a next digit as three that is very obvious that it he's saying that obvious that it he's saying that basically we are replicating that chest basically we are replicating that chest scenario on a phone pad on our simple scenario on a phone pad on our simple Nokia phone pad and the same way it can Nokia phone pad and the same way it can go to this location from eight if I just go to this location from eight if I just move via the night ways it can go to a move via the night ways it can go to a location of one that's great and there's location of one that's great and there's no more location it can go because no more location it can go because because it has no more places to go to because it has no more places to go to so what we actually can do is we can so what we actually can do is we can just make a map kind of stuff or vctor just make a map kind of stuff or vctor kind of stuff no worries that if it is kind of stuff no worries that if it is actually required or not still I'm just actually required or not still I'm just showing you that we just want to showing you that we just want to replicate the movements so you can say replicate the movements so you can say okay from zero it can move 2 4 6 from 1 okay from zero it can move 2 4 6 from 1 can move to 68 2 to 79 3 to 4 6 4 to 3 9 can move to 68 2 to 79 3 to 4 6 4 to 3 9 0 uh 5 to nothing uh 6 2 170 7 to 28 8 0 uh 5 to nothing uh 6 2 170 7 to 28 8 to 13 as we saw on above and 9 to 24 to 13 as we saw on above and 9 to 24 this is we can just manually write it this is we can just manually write it down because it's very hectic to down because it's very hectic to actually go and find I plus a so like we actually go and find I plus a so like we can just hardcode this stuff and no like can just hardcode this stuff and no like no like not sure if it is used or not no like not sure if it is used or not but yeah still we have just write it but yeah still we have just write it down because we know that we have to down because we know that we have to replicate this whole scenario on a phone replicate this whole scenario on a phone part now comes the interesting part we part now comes the interesting part we have a chess Knight and a phone pad okay have a chess Knight and a phone pad okay that is done and we have to just move on that is done and we have to just move on the cells now given an integer n return the cells now given an integer n return how many distinct phone numbers of how many distinct phone numbers of length n can be dial again we are given length n can be dial again we are given an integer n so it is for sure for us an integer n so it is for sure for us that if I given integer N I have to find that if I given integer N I have to find let's say the N is of four digits so I let's say the N is of four digits so I have to find how many such four n have to find how many such four n digits phone numbers I can dial again I digits phone numbers I can dial again I have not done anything extra I'm just have not done anything extra I'm just writing what the question is saying writing what the question is saying please make sure that you follow up and please make sure that you follow up and that will be the part how you get to that will be the part how you get to know that what and how the recursions know that what and how the recursions are done or how the states are being are done or how the states are being applied and all that stuff now you are applied and all that stuff now you are allowed to place the Knight on any allowed to place the Knight on any numeric cell initially okay so he was numeric cell initially okay so he was saying that I have to build a digit of n saying that I have to build a digit of n digits and initially initially I can digits and initially initially I can place my night on any of the digits what place my night on any of the digits what digits I have I have 0 1 2 3 4 5 6 7 8 9 digits I have I have 0 1 2 3 4 5 6 7 8 9 10 like nine only so I on the first 10 like nine only so I on the first place I can place 0 1 2 2 3 4 5 6 7 8 place I can place 0 1 2 2 3 4 5 6 7 8 and 9 so on the first place I can place and 9 so on the first place I can place these digits oh that's great I can place these digits oh that's great I can place these digits and I did nothing again uh these digits and I did nothing again uh and then you should perform n minus one and then you should perform n minus one jumps to the dial a number of length n jumps to the dial a number of length n okay because as you know that the length okay because as you know that the length was n so I know that I have placed one was n so I know that I have placed one digit any of these digits from 0 to 9 I digit any of these digits from 0 to 9 I have placed so now I I will have to have placed so now I I will have to perform perform n-1 n-1 jumps because for sure I want the jumps because for sure I want the remaining n minus one digits and this is remaining n minus one digits and this is what the question was saying all jumps what the question was saying all jumps should be have valid night jumps okay should be have valid night jumps okay which means all jumps should be a valid which means all jumps should be a valid night jumps which means let's say if in night jumps which means let's say if in the beginning because you know that okay the beginning because you know that okay we had four digits because my n was four we had four digits because my n was four in this example like I was taking okay n in this example like I was taking okay n digits and let's say we have placed a digits and let's say we have placed a small number ns4 now if I have placed a small number ns4 now if I have placed a digit zero here and he's saying that all digit zero here and he's saying that all the jump jump should be a valid night the jump jump should be a valid night jumps so I know that I I will ultimately jumps so I know that I I will ultimately have to make n minus one jumps as the have to make n minus one jumps as the question was saying but the next jump question was saying but the next jump should be a valid night jump so from should be a valid night jump so from zero I can only jump to four and six so zero I can only jump to four and six so I will use this jumps array to help me I will use this jumps array to help me if existing I have a digit I have a if existing I have a digit I have a digit as zero so next jump can only be a digit as zero so next jump can only be a four or a six and I should do a next four or a six and I should do a next jump of a four or a six and that is how jump of a four or a six and that is how greatly I can just figure out bro I know greatly I can just figure out bro I know that myit is this my remaining I have to that myit is this my remaining I have to fill as n minus one digits and I know fill as n minus one digits and I know for sure the next digit I can place at a for sure the next digit I can place at a four or six and then I can simply going four or six and then I can simply going keep on going forward until so far I keep on going forward until so far I have did I have done nothing now as the have did I have done nothing now as the answer can be pretty large return the answer can be pretty large return the answer with the module 9+ 7 because we answer with the module 9+ 7 because we have to find the number of ways so the have to find the number of ways so the answer he's saying can be prettyy large answer he's saying can be prettyy large so just return it 9+ 7 that we make sure so just return it 9+ 7 that we make sure that we will do in the for sure like in that we will do in the for sure like in the while solving the problem itself now the while solving the problem itself now now now coming on back we have solved now now coming on back we have solved majorly the part of the intuition itself majorly the part of the intuition itself that it is for sure in the beginning I that it is for sure in the beginning I will place I will have nine options to will place I will have nine options to place and I will and I I cannot say that place and I will and I I cannot say that I will blindly place these nine I one I will blindly place these nine I one way of doing these problems is you like way of doing these problems is you like you just say that to place on the first you just say that to place on the first location you have nine options and you location you have nine options and you just place that nine number here that just place that nine number here that okay for the first location I have nine okay for the first location I have nine options then what's the options for next options then what's the options for next location but here I cannot do that I location but here I cannot do that I have to actually Place one digit I have have to actually Place one digit I have to place a zero because that zero will to place a zero because that zero will make sure that what should be my next make sure that what should be my next jump so every digit will matter here so jump so every digit will matter here so I will do one thing okay I know that my I will do one thing okay I know that my current digit is this and I also know current digit is this and I also know that I have to figure out if I have that I have to figure out if I have placed I have to figure out for the next placed I have to figure out for the next n minus one places Ms have to figure out n minus one places Ms have to figure out and and that's that's what the question and that's that's what the question and that's the question was saying so again that's the question was saying so again I can just place a one as the first I can just place a one as the first digit and I can again go and ask for the digit and I can again go and ask for the N minus one digit again I can place a N minus one digit again I can place a two here as a first digit and I can two here as a first digit and I can again go and ask for the next n minus again go and ask for the next n minus one digit now now when you place a zero one digit now now when you place a zero let's let's imagine you place a zero you let's let's imagine you place a zero you place a zero right so the next digit so place a zero right so the next digit so the next digit it can be it can be a the next digit it can be it can be a four or a six as we plotted as we saw four or a six as we plotted as we saw right it should be valid night jump it right it should be valid night jump it can be a four or six so I can place a can be a four or six so I can place a four or a six let's imagine we place a four or a six let's imagine we place a four or let's imagine we place a six so four or let's imagine we place a six so we can place both of them so for sure we we can place both of them so for sure we will have two options again if we just will have two options again if we just copy this up so that with this we will copy this up so that with this we will see that we will have these two see that we will have these two options and with these two options I can options and with these two options I can easily say that okay I can place either easily say that okay I can place either a four here or a six here oh if I place a four here or a six here oh if I place a four or a six okay then I have to go a four or a six okay then I have to go and find for next nus 2 locations again and find for next nus 2 locations again next nus 2 locations right again if for next nus 2 locations right again if for one again we'll go and check okay I can one again we'll go and check okay I can place a six or eight let's right now place a six or eight let's right now only place one thing one thing six only place one thing one thing six although we although we will place both although we although we will place both of them but for Simplicity I'm just for of them but for Simplicity I'm just for explanation so showing if I place a six explanation so showing if I place a six then again I'll go and find for n minus then again I'll go and find for n minus 2 locations oh bro bro bro that is same 2 locations oh bro bro bro that is same that you placed a digit now bro how is that you placed a digit now bro how is this same one was no no bro I just want this same one was no no bro I just want to do previous digit because this six to do previous digit because this six will make sure what should be the next will make sure what should be the next location this six will make sure what location this six will make sure what should the next location because I want should the next location because I want the valid night jump from six so it is a the valid night jump from six so it is a same configuration saying from six I same configuration saying from six I want a length of nus 2 What is the want a length of nus 2 What is the number what is the number of possible number what is the number of possible phone pad combinations from six if I do phone pad combinations from six if I do off length n minus 2 what is the number off length n minus 2 what is the number of valid phone pad combinations so ultim of valid phone pad combinations so ultim you figure out this needs to be your DP you figure out this needs to be your DP state that you like you can just write state that you like you can just write any any which ways down that this is the any any which ways down that this is the remaining number of location and this is remaining number of location and this is the current digit this current digit the current digit this current digit will help me make sure I need to find my will help me make sure I need to find my next digit I need to find my next digit next digit I need to find my next digit I can find my next digit next digit by I can find my next digit next digit by just iterating on this jumps array of just iterating on this jumps array of the current the current digit that I can know what is the digit that I can know what is the possible next digit location and that's possible next digit location and that's how you got to know that it is a how you got to know that it is a question of recursion because you know question of recursion because you know that for sure for sure just will simply that for sure for sure just will simply keep on replicating you know that it is keep on replicating you know that it is having a repeating sub problem so for having a repeating sub problem so for sure we will apply a memor or a DP so sure we will apply a memor or a DP so that is a second point you got to know that is a second point you got to know what needs to be the state of your what needs to be the state of your recursion or the DP so as to solve this recursion or the DP so as to solve this question so ultimately we have reached question so ultimately we have reached to a conclusion that uh we just need one to a conclusion that uh we just need one thing we need remaining and we need thing we need remaining and we need current digit so in the beginning in the current digit so in the beginning in the beginning I have the options to place beginning I have the options to place all the nine digits so in the beginning all the nine digits so in the beginning I will place I'll just say in the I will place I'll just say in the beginning I'll place all the nine digits beginning I'll place all the nine digits 0 1 2 3 4 5 6 7 8 and 9 and as I place 0 1 2 3 4 5 6 7 8 and 9 and as I place on all the nine digits I know the on all the nine digits I know the remaining for all of them the remaining remaining for all of them the remaining for all of them is nus one nus one nus for all of them is nus one nus one nus one why nus one because the pro saying one why nus one because the pro saying now nus one jumps for the remaining one now nus one jumps for the remaining one so I know I have placed one I have to so I know I have placed one I have to place in total n so the remaining is nus place in total n so the remaining is nus one for sure n minus1 nus1 n -1 nus1 and one for sure n minus1 nus1 n -1 nus1 and so on so forth and with this you will so on so forth and with this you will just pass this in your recursion you just pass this in your recursion you will know okay this is the remaining will know okay this is the remaining this is the this is the remaining this this is the this is the remaining this is the digit you know for sure that from is the digit you know for sure that from this digit you need to do some number of this digit you need to do some number of jumps so you will know that if I want to jumps so you will know that if I want to go to my next location I will just say go to my next location I will just say bro jumps of this digit will give me the bro jumps of this digit will give me the next digits will give me the next digits next digits will give me the next digits next next digits that will be a simple these all digits that will be a simple these all next digits for me to jump to so that I next digits for me to jump to so that I will know that from this location I can will know that from this location I can jump to nus 2 because now the remaining jump to nus 2 because now the remaining digits will be nus 2 and now the current digits will be nus 2 and now the current digit will be a zero for Zer it is a digit will be a zero for Zer it is a four or six so it will be a I will just four or six so it will be a I will just call recursion for four and for the same call recursion for four and for the same thing I call recursion for for six this thing I call recursion for for six this will be our next recursive State and for will be our next recursive State and for sure I want the number of ways sure I want the number of ways ultimately if it means okay from this ultimately if it means okay from this you will see that if I place if if if you will see that if I place if if if let's say I had just two numbers so I let's say I had just two numbers so I place a zero here next I can place a place a zero here next I can place a four right next it will just say bro four right next it will just say bro remaining now remaining let's say my remaining now remaining let's say my total n was to itself so now the total n was to itself so now the remaining is zero now the remaining is remaining is zero now the remaining is zero which means I have I have formed zero which means I have I have formed one valid combination when the remaining one valid combination when the remaining goes zero which means I don't need to goes zero which means I don't need to place any any digit now so my I have place any any digit now so my I have found a Val combination of Digit so just found a Val combination of Digit so just says that when you're remaining says that when you're remaining remaining is just this number right remaining is just this number right remaining number of places to have to remaining number of places to have to place the digit if the remaining is zero place the digit if the remaining is zero bro you have all you have formed the bro you have all you have formed the valid combination please return a one so valid combination please return a one so this will return me a one because I have this will return me a one because I have formed a valid combination ultimately formed a valid combination ultimately and for sure you are having multiple and for sure you are having multiple options so please either because from options so please either because from zero you can either go zero you can either go on four or you can go on six so keep on on four or you can go on six so keep on adding the possible ways for every of adding the possible ways for every of those Childs which means four or six and those Childs which means four or six and that's how you can simply get this that's how you can simply get this solved in the cursion and again the time solved in the cursion and again the time complexity will actually be you will see complexity will actually be you will see that you are actually going on to just n that you are actually going on to just n and these digits n is nothing but the and these digits n is nothing but the question itself which is given n and the question itself which is given n and the digits can be zero to 9 which is 10 digits can be zero to 9 which is 10 itself so the time will actually be o of itself so the time will actually be o of n into 10 or you can also say that o of n into 10 or you can also say that o of n itself and the space also you will n itself and the space also you will keep track and do a memorization for keep track and do a memorization for that you will again need a space of O of that you will again need a space of O of n into 10 or you again say that o of n n into 10 or you again say that o of n itself let's quickly see that how we can itself let's quickly see that how we can pute this up again I hope that you guys pute this up again I hope that you guys have got it uh for Simplicity I have have got it uh for Simplicity I have just pasted the jumps array because we just pasted the jumps array because we have to manually make it up uh now we have to manually make it up uh now we know that we need to have a 2d Vector uh know that we need to have a 2d Vector uh for this now I will as you know that we for this now I will as you know that we are doing modulo so uh let's take are doing modulo so uh let's take everything in long long because it is everything in long long because it is much more easier for us to do a modulo much more easier for us to do a modulo and for sure uh we have to take a mod 1 and for sure uh we have to take a mod 1 2 3 4 5 6 7 8 9 + 7 now uh I'll just do 2 3 4 5 6 7 8 9 + 7 now uh I'll just do uh my DP now I'll just resize my DP uh uh my DP now I'll just resize my DP uh because it just feels like now we need because it just feels like now we need the first is the remaining remaining can the first is the remaining remaining can be from 0 to n so I just take a size of be from 0 to n so I just take a size of n+ one now and the next part was a digit n+ one now and the next part was a digit for us again um you can just swap both for us again um you can just swap both of them which means you can have the of them which means you can have the digit and your remaining or any which digit and your remaining or any which way you can have the remaining and the way you can have the remaining and the digits so here the digits will only be digits so here the digits will only be 10 from 0 to 9 so that's the reason we 10 from 0 to 9 so that's the reason we have just only done this now our main have just only done this now our main part comes when we actually have to call part comes when we actually have to call a solve function now the solve function a solve function now the solve function if you had known that is just uh a if you had known that is just uh a simple function saying that just solve simple function saying that just solve it it's a DB function now I have the it it's a DB function now I have the remaining I have the digit current digit remaining I have the digit current digit which I am on why current digit I on which I am on why current digit I on because you know that for my final because you know that for my final answer I have to initially start on and answer I have to initially start on and place every digit so I'll just try and place every digit so I'll just try and place I'll I try and place every digit place I'll I try and place every digit from 0 to 9 and then because you saw now from 0 to 9 and then because you saw now in the first location I can place any in the first location I can place any digits so I'll just say I'll place every digits so I'll just say I'll place every digits which means I'll place every digits which means I'll place every digit so the remaining number will be n digit so the remaining number will be n minus one and I have placed this digit minus one and I have placed this digit as a first digit for me and ultimately I as a first digit for me and ultimately I can just say return the um answer mod can just say return the um answer mod with this value so yeah also do a mod at with this value so yeah also do a mod at every step because mod can be pretty every step because mod can be pretty dangerous now I can just simply go and dangerous now I can just simply go and have a solve function uh in the have a solve function uh in the beginning I just showed you that if your beginning I just showed you that if your remaining reaches zero uh which means remaining reaches zero uh which means bro you have found a valid combination bro you have found a valid combination so simply return a minus one now here so simply return a minus one now here I'll just ask him bro um for that if you I'll just ask him bro um for that if you have already found the value simple have already found the value simple memor check then simply return DP of memor check then simply return DP of remaining and that digit it's a simple remaining and that digit it's a simple memor check which you already always do memor check which you already always do now as you saw that for the current now as you saw that for the current digit I can go on next next digits so I digit I can go on next next digits so I will have my answer now I for this will have my answer now I for this current digit I'll go on to next digits current digit I'll go on to next digits so I'll go on to next digit for this so I'll go on to next digit for this current digit and what how I can go by current digit and what how I can go by the jumps array which I have made the jumps array which I have made earlier so I'll go on to for this digit earlier so I'll go on to for this digit and I will just ask him bro um just add and I will just ask him bro um just add the answer whatsoever you have uh just the answer whatsoever you have uh just go and solve it I know the remaining go and solve it I know the remaining will actually decrease and become a will actually decrease and become a remaining minus one because one digit remaining minus one because one digit I'm taking right now which is a digit I'm taking right now which is a digit and I'll go on to this next digit next and I'll go on to this next digit next digit is my digit next digit is my next digit is my digit next digit is my next digit and for sure please keep on doing digit and for sure please keep on doing the modulo and ultimately return the the modulo and ultimately return the answer but before returning please make answer but before returning please make sure that you memoize it and place that sure that you memoize it and place that in your digit so that you can just use in your digit so that you can just use it later on also and simply answer and it later on also and simply answer and with this mod value now let's quick with this mod value now let's quick check it up if we have not done any check it up if we have not done any errors uh Vector okay let's correct this errors uh Vector okay let's correct this and yeah uh if yeah and with this the and yeah uh if yeah and with this the time will actually be o of n into o of time will actually be o of n into o of like space and time both are actually o like space and time both are actually o of N and that's the code which you also of N and that's the code which you also saw now uh now comes that shall we saw now uh now comes that shall we optimize it but in memor you cannot optimize it but in memor you cannot think of any optimizations so for sure think of any optimizations so for sure you have to convert the same thing into you have to convert the same thing into a convert the same thing into a bottom a convert the same thing into a bottom up so what I will do is the same code up so what I will do is the same code which we have written previously I'll which we have written previously I'll just do one thing and try to see that just do one thing and try to see that how I can convert this code to a bottom how I can convert this code to a bottom of code same stuff uh we will use the of code same stuff uh we will use the same remaining end digits we will just same remaining end digits we will just do one thing okay uh you know that what do one thing okay uh you know that what was the base case base case was when the was the base case base case was when the remaining is zero now our DP looks like remaining is zero now our DP looks like remaining and then digit now my base remaining and then digit now my base case was that my remaining is zero so case was that my remaining is zero so what I will do is I simply have a base what I will do is I simply have a base case that okay my uh DP of DP of0 and case that okay my uh DP of DP of0 and for all the digits which is your 0 to 9 for all the digits which is your 0 to 9 all the digits the value you should all the digits the value you should place as one itself for the base case place as one itself for the base case because I trying to replicate the top because I trying to replicate the top down to a bottom up so I'm just manually down to a bottom up so I'm just manually seeing okay what how my bottom of code seeing okay what how my bottom of code looks how my top down code looks like looks how my top down code looks like and with that I'm converting my and with that I'm converting my converting my code to a bottom up code I converting my code to a bottom up code I saw my base case remaining was Zero for saw my base case remaining was Zero for every digit I'm returning a one so that every digit I'm returning a one so that is my base case for my bottom of DP then is my base case for my bottom of DP then I will just start off with my actual DP I will just start off with my actual DP itself and we go on to all the remaining itself and we go on to all the remaining from one up till the remaining is less from one up till the remaining is less than equal to n minus one because you than equal to n minus one because you saw now remaining will go to n minus one saw now remaining will go to n minus one itself and then remaining Plus+ for that itself and then remaining Plus+ for that remaining I'll go on to all the digits remaining I'll go on to all the digits of that remaining that is what you of that remaining that is what you usually do you go on to all the digits usually do you go on to all the digits from zero to actually less than 10 which from zero to actually less than 10 which means less than equal to 9 digit plus means less than equal to 9 digit plus plus now again for every digit you will plus now again for every digit you will actually say now that okay uh for this actually say now that okay uh for this current digit okay the remaining is one current digit okay the remaining is one the I have the current digit what could the I have the current digit what could be the my last jump or like what what be the my last jump or like what what should be my next jump to be so I'll should be my next jump to be so I'll just say okay uh what is the next jump just say okay uh what is the next jump which I need to have and I'll just which I need to have and I'll just iterate on the jumps of this particular iterate on the jumps of this particular digit array and with this I can just say digit array and with this I can just say that I'm iterating on my remaining that I'm iterating on my remaining digits and the next jump and I'll just digits and the next jump and I'll just say that my DP or or I can just say my say that my DP or or I can just say my DP of remaining and digit will be a DP of remaining and digit will be a summation of my DP of remaining minus summation of my DP of remaining minus one and next jumps next jumps and that's one and next jumps next jumps and that's what we had been doing remaining minus what we had been doing remaining minus one we would have already calculated one we would have already calculated because we are going in the disorder and because we are going in the disorder and remaining minus one will actually be a remaining minus one will actually be a zero in the beginning so we are going in zero in the beginning so we are going in the order so for sure we would have the order so for sure we would have already calculated the previous state already calculated the previous state which is remaining minus one and for which is remaining minus one and for sure the next jum will be the digits sure the next jum will be the digits itself from 0 to 9 so we can we would itself from 0 to 9 so we can we would have already computed that also so have already computed that also so ultimately we will just do a summation ultimately we will just do a summation and while doing summation please and while doing summation please remember of the mod and stuff and that remember of the mod and stuff and that will be a simple bottom up DP how this will be a simple bottom up DP how this bottom of DP will look will look like so bottom of DP will look will look like so we have to just simply modify this we have to just simply modify this particular code and remove the above particular code and remove the above code let's quickly do the same thing code let's quickly do the same thing again the time again if we just go back again the time again if we just go back the time and the space are again same the time and the space are again same time is again o of N and space is again time is again o of N and space is again o of n then Arian why did you do that by o of n then Arian why did you do that by why did you why did you do that we will why did you why did you do that we will see because if you want to think of if see because if you want to think of if let's say the interview ask you can you let's say the interview ask you can you optimize this so firstly you will have optimize this so firstly you will have to convert that code to a bottomup code to convert that code to a bottomup code again there are chances that there might again there are chances that there might not be any optimizations at all but not be any optimizations at all but still if there are then you will have to still if there are then you will have to have to convert your code to a bottom up have to convert your code to a bottom up code you cannot optimize the code using code you cannot optimize the code using a top down approach now uh we are back a top down approach now uh we are back and we just don't need to solve function and we just don't need to solve function because we will act do a bottom up because we will act do a bottom up approach for us now uh for the bottom up approach for us now uh for the bottom up we just initialize with the zero itself we just initialize with the zero itself and as we saw also previously that for and as we saw also previously that for the first remaining as zero so I'll just the first remaining as zero so I'll just go on to all of my digits uh starting go on to all of my digits uh starting from 0 less than 10 and digits uh digit from 0 less than 10 and digits uh digit ++ I just do one thing and just say that ++ I just do one thing and just say that DP of zero when the remaining is zero as DP of zero when the remaining is zero as I should you it was a base case for our I should you it was a base case for our um top down approach uh for this um top down approach uh for this corresponding digit the answer is one corresponding digit the answer is one now uh comes the interesting part that I now uh comes the interesting part that I will actually go on and say okay will actually go on and say okay remaining uh remaining is one remaining remaining uh remaining is one remaining is less than equals to n minus1 and then is less than equals to n minus1 and then remaining remaining Plus+ now uh what I will do is I'll just Plus+ now uh what I will do is I'll just go and say okay uh the digit is again go and say okay uh the digit is again equal to zero digit is less than 10 and equal to zero digit is less than 10 and digit digit Plus+ I just go and go for digit digit Plus+ I just go and go for all of my all of my next digits for the corresponding digit next digits for the corresponding digit uh I just say bro what can be the next uh I just say bro what can be the next digit it can be the next digit it can be the next digit uh in like again the jumps are digit uh in like again the jumps are will be useful for us for the will be useful for us for the corresponding digit I'm going on and I corresponding digit I'm going on and I just say okay our brackets are yeah now just say okay our brackets are yeah now I'll just say that I'll just update that I'll just say that I'll just update that in my answer now answer plus okay I not in my answer now answer plus okay I not initialized the answer we'll initialize initialized the answer we'll initialize the answer itself now for every digit the answer itself now for every digit shall I initialize it yeah let's shall I initialize it yeah let's initialize it now the answer is zero I initialize it now the answer is zero I just say that answer will be for this just say that answer will be for this corresponding digit which is the corresponding digit which is the remaining minus one and for this next remaining minus one and for this next digit what what was what had been the digit what what was what had been the value for me and for sure do the mod at value for me and for sure do the mod at every step when this is done for all the every step when this is done for all the next digits I would have known that for next digits I would have known that for this remaining for the corresponding this remaining for the corresponding digit this would have been my answer and digit this would have been my answer and simply assign that to my answer and that simply assign that to my answer and that I can do it for every of my remaining I can do it for every of my remaining digit combination now when this part is digit combination now when this part is done again I'll go on to my answer and done again I'll go on to my answer and we say and go on to all the digits and we say and go on to all the digits and I'll just say that instead of this my I'll just say that instead of this my final uh my final DP of n minus one final uh my final DP of n minus one would have me showing that for this would have me showing that for this corresponding corresponding digit next M1 what should have been digit next M1 what should have been there so simply do this and if the there so simply do this and if the brackets are correct I don't think they brackets are correct I don't think they are correct let's remove this bracket are correct let's remove this bracket and yeah it should work now so it's just and yeah it should work now so it's just that we can converted digit at line 24 that we can converted digit at line 24 we just want one I and this is how we we just want one I and this is how we can actually do it so uh in this we just can actually do it so uh in this we just actually converted our code to just the actually converted our code to just the uh bottom up code now comes the uh bottom up code now comes the interesting part uh now we have interesting part uh now we have converted this code to a bottom up code converted this code to a bottom up code can we see something in this code what can we see something in this code what whatsoever code we have written can we whatsoever code we have written can we see something here yeah we can see see something here yeah we can see something uh what you'll see that for something uh what you'll see that for every DP for every for every DP of every DP for every for every DP of remaining you are only using DP of remaining you are only using DP of remaining minus one so it is just that remaining minus one so it is just that you're only using a previous state which you're only using a previous state which means you only need a DP array of this means you only need a DP array of this next side which is actually the number next side which is actually the number of digits actually 10 so you just need a of digits actually 10 so you just need a DP AR of size 10 and say okay I will DP AR of size 10 and say okay I will have a previous digits of size 10 and have a previous digits of size 10 and the next and the current DP let's say the next and the current DP let's say the previous DP of size 10 and the DP of the previous DP of size 10 and the DP of size 10 this DP will be storing this DP size 10 this DP will be storing this DP of remaining end digits this previous DP of remaining end digits this previous DP will be storing the DP of remaining will be storing the DP of remaining minus one end digits now with this I can minus one end digits now with this I can simply keep on assigning my DP previous simply keep on assigning my DP previous DP DP previous DP DP like previous DP so DP DP previous DP DP like previous DP so I would need only two lines only only I would need only two lines only only two rows so I won't be needing those n two rows so I won't be needing those n of my previous rows so because in this of my previous rows so because in this let's say for DP of 15 and let's say a let's say for DP of 15 and let's say a digit of two a DP of I would need a DP digit of two a DP of I would need a DP of 14 right and a digit of two like of 14 right and a digit of two like whatsoever is the next digit but DP of whatsoever is the next digit but DP of 13 and DP of 12 and all that stuff would 13 and DP of 12 and all that stuff would not be needed so I only need the not be needed so I only need the previous DP state so that's the reason I previous DP state so that's the reason I can just reduce my o of n space entirely can just reduce my o of n space entirely and I would only use 2 into 10 space and I would only use 2 into 10 space which is actually o of 20 space which which is actually o of 20 space which actually o of constant space so my time actually o of constant space so my time is still o of n o of n although it was O is still o of n o of n although it was O of n into 10 but yeah 10 is constant so of n into 10 but yeah 10 is constant so it is O of n but my space can be reduced it is O of n but my space can be reduced to O of one my space can be reduced to O to O of one my space can be reduced to O of one because I will use only current of one because I will use only current DP and the previous DP let's quickly DP and the previous DP let's quickly modify it that's not a big change for us modify it that's not a big change for us so if we go now we would not need a 2d so if we go now we would not need a 2d DP uh we would just need a simple DP DP uh we would just need a simple DP which is I we will just say that a DP which is I we will just say that a DP and for sure the size is 10 now this DP and for sure the size is 10 now this DP and for sure we also need a previous DP and for sure we also need a previous DP now previous DP uh what shall we now previous DP uh what shall we initialize with we'll initialize with initialize with we'll initialize with one why one because we know that in the one why one because we know that in the beginning the previous DP has a value of beginning the previous DP has a value of one itself okay cool now I just simply one itself okay cool now I just simply go on to my remaining I'll go on to my go on to my remaining I'll go on to my digits my answer as this my next digits digits my answer as this my next digits are this my DP of remaining minus one is are this my DP of remaining minus one is actually my previous DP okay that is actually my previous DP okay that is done and for the next dig I will go uh done and for the next dig I will go uh DP of remaining minus one is actually DP of remaining minus one is actually the current DP okay that is done when the current DP okay that is done when this part of entirely of for every every this part of entirely of for every every digit is done please simply make sure digit is done please simply make sure that you assign the previous DP value to that you assign the previous DP value to the DP because we want to go on and keep the DP because we want to go on and keep forward right and ultimately in the end forward right and ultimately in the end I will go into all the digits uh for DP I will go into all the digits uh for DP I'll just have the current state uh my I'll just have the current state uh my previous DP will always contain the previous DP will always contain the answer so I'll just have the previous DP answer so I'll just have the previous DP why not DP itself because let's say I I why not DP itself because let's say I I just have my remaining like let's say my just have my remaining like let's say my n is one itself so it will never come in n is one itself so it will never come in inside but previous DP will still have inside but previous DP will still have the answer because one is for sure the answer because one is for sure possible right so it will still get the possible right so it will still get the value so previous DP will always contain value so previous DP will always contain the value DP may or may not contain the value DP may or may not contain depending upon if I have just ran the depending upon if I have just ran the loop once or like I have not ran the loop once or like I have not ran the loop at all so DP might not contain the loop at all so DP might not contain the value itself so that's the reason value itself so that's the reason previous DP will always contain the previous DP will always contain the answer that's the reason we always use answer that's the reason we always use the previous DP itself let's quickly run the previous DP itself let's quickly run this code uh it should work yeah and you this code uh it should work yeah and you will see now the space uses o n rather will see now the space uses o n rather than o of sorry the space user o of one than o of sorry the space user o of one rather than space user O N I hope that rather than space user O N I hope that you guys got it uh if yes can we please you guys got it uh if yes can we please smash that like button this is It's So smash that like button this is It's So Mo motivation for me uh it takes time Mo motivation for me uh it takes time and thanks watching goodbye take care and thanks watching goodbye take care bye-bye | 2024-03-25 11:43:09 | 935 | 935. Knight Dialer | 3 Ways | O(1) space | Facebook | Bloomberg | Google |
|
MqFDlAqlffU | hello everyone so today's question is from july lead coding challenge day 7 from july lead coding challenge day 7 and it's called island perimeter we have and it's called island perimeter we have a 2d matrix a 2d matrix or a grid of zeros and ones zero or a grid of zeros and ones zero represents water represents water and one represents land grid cells are and one represents land grid cells are connected horizontally and vertically connected horizontally and vertically not diagonally so from any given cell not diagonally so from any given cell you can you can only go up down right or left only go up down right or left grid is surrounded by water so we can grid is surrounded by water so we can imagine that imagine that our grid is part of a very large grade our grid is part of a very large grade of zeros of zeros there is exactly one island it means there is exactly one island it means that all ones that all ones in the grid are connected to each other in the grid are connected to each other either directly or indirectly either directly or indirectly so we can never see any grid like these so we can never see any grid like these each cell of this grid is a square of each cell of this grid is a square of side length one side length one and the grid is rectangular where both and the grid is rectangular where both width width and height are not more than hundred we and height are not more than hundred we have to find the perimeter of this have to find the perimeter of this island island for example we have a grid of all zeros for example we have a grid of all zeros and ones and ones there is exactly one island which has there is exactly one island which has been highlighted been highlighted and we have to find the parameter of and we have to find the parameter of this island this island so it would be 1 2 3 4 5 6 so it would be 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 and 16. 7 8 9 10 11 12 13 14 15 and 16. now the question is how do we solve it now the question is how do we solve it let's say let's say we have a grid which contains a single we have a grid which contains a single one one and all other elements are zero so and all other elements are zero so the total parameter of this square the total parameter of this square island would be four island would be four now what if there are more number of now what if there are more number of ones because the problem statement says ones because the problem statement says there is exactly one island which means there is exactly one island which means all ones are connected we could have a all ones are connected we could have a new one new one adjacent to the old one let us say the adjacent to the old one let us say the new one is on the right side of the old new one is on the right side of the old one one so now the contribution of old one in so now the contribution of old one in the total parameter would decrease by the total parameter would decrease by one one similarly if there are two more ones similarly if there are two more ones other than the old one other than the old one the contribution of old one in the total the contribution of old one in the total parameter would decrease by two parameter would decrease by two so can we say that for any one the so can we say that for any one the contribution in the total parameter contribution in the total parameter would be would be four minus number of ones directly four minus number of ones directly adjacent to it adjacent to it sounds good let's verify this on an sounds good let's verify this on an example example so we have a grid of zeros and ones and so we have a grid of zeros and ones and we need to sum up the contribution of we need to sum up the contribution of all the ones in the total parameter so all the ones in the total parameter so for this one for this one we need to check the number of ones in we need to check the number of ones in the cells which are directly adjacent to the cells which are directly adjacent to it it so you see the number of ones which are so you see the number of ones which are directly adjacent to directly adjacent to this cell is one so its contribution this cell is one so its contribution in total perimeter would be four minus in total perimeter would be four minus one one that is three now for that is three now for this cell for this one the number of this cell for this one the number of ones which are directly adjacent to it ones which are directly adjacent to it is is two so its contribution would be four two so its contribution would be four minus two minus two that is two similarly for that is two similarly for this one the contribution would be 4 this one the contribution would be 4 minus minus 2 that is 2. now for this last one 2 that is 2. now for this last one contribution would be 4 minus 1 contribution would be 4 minus 1 that is 3. so the total parameter of that is 3. so the total parameter of this island would be 10 this island would be 10 let us now frame these steps into an let us now frame these steps into an algorithm the main idea is algorithm the main idea is we sum up the total contribution to the we sum up the total contribution to the total parameter by each fund total parameter by each fund so we initialize total parameter to be 0 so we initialize total parameter to be 0 initially initially then we traverse the grid and whenever then we traverse the grid and whenever we see a one we see a one we increase the total parameter by four we increase the total parameter by four then we count the number of adjacent then we count the number of adjacent cells cells having one then we need to decrease the having one then we need to decrease the total parameter like this total parameter like this and at the end we just return the total and at the end we just return the total parameter that is p parameter that is p that's it let us quickly write a code that's it let us quickly write a code initially total parameter would be zero initially total parameter would be zero then we traverse the grid and whenever then we traverse the grid and whenever we see a one we see a one we first update our total parameter like we first update our total parameter like this this then we are going to visit each one of then we are going to visit each one of the four the four adjacent cell to update the value of adjacent cell to update the value of total parameter again total parameter again at the end we are just going to return at the end we are just going to return the total parameter so far the total parameter so far so that's it for today's video if you so that's it for today's video if you like this video please hit the like like this video please hit the like button and subscribe to my channel | 2024-03-22 15:09:38 | 463 | Island Perimeter Leetcode 463 | Python Solution Explained | O(n.m) | Google Coding Interview |
|
XmQ8T3MiW-c | hello everyone welcome back to my channel today i will introduce the channel today i will introduce the analytical question minimal high trees analytical question minimal high trees and i will use typological to solve this and i will use typological to solve this problem problem from the description we can say we have from the description we can say we have a tree a tree and it is a direct graph and it is a direct graph and each two node connected in one path and each two node connected in one path so that means this graph without any so that means this graph without any circle connect and then from the tree we circle connect and then from the tree we can say there are can say there are a node as an input a node as an input it just shows the connection of each it just shows the connection of each node node and in this question we need to find and in this question we need to find which node could be the root and then which node could be the root and then this string has the minimal height and this string has the minimal height and let's take a look on the example one let's take a look on the example one so we have four nodes the node zero and so we have four nodes the node zero and one connector one connector one two connector and one three one two connector and one three connector connector and and there are four possible there are four possible there are four possible tree there are four possible tree and and the second one the second one we can say this is the minimum height we can say this is the minimum height because they're only how because they're only how the one the hit one the one the hit one and the others with the h2 and the others with the h2 so so how could we solve it by topological so how could we solve it by topological so first they we save first they we save all the paths into a graph all the paths into a graph and save each and save each each node we count the indegree of each each node we count the indegree of each node node the the way save the integrate way save the integrate save the node with integrate equal to 1 save the node with integrate equal to 1 into the into the into the queue and into the queue and we use the queue to iterate we use the queue to iterate the graph the graph in the end address of node would be the in the end address of node would be the result result so let's take a look on the code so let's take a look on the code so first of all we need to create a so first of all we need to create a graph and we also need graph and we also need we also need array to we also need array to save each node's in degree save each node's in degree so let's build the graph from the input so let's build the graph from the input of h of h we need to save we need to save both nodes into the graph because this both nodes into the graph because this is our direct is our direct graph graph and then we create a queue we iterated the integrand and then we try to find the node based in degree one so let's do the topological for each loop basis to check how many nodes with how many nodes in the same level so we need to create a variable to save how many nodes in the and before the queue we create a list to and before the queue we create a list to save the node we added the current one into the into into the list iterate the connections of the node and if we found it in the degree and away minus 8 from the in degree if we found the integrate is equal to 1 we save the cooler queue before each loop away create a new and we and we and instead of save it to the result we and instead of save it to the result we save it to this list save it to this list and and [Music] [Music] after this loop we after this loop we save the result save the result to the list and to the list and so at the end of the so at the end of the topological the result is which is a topological the result is which is a node we found and the nodes can build the tree with this is hashmap the time complexity and the space complexity is o o n and n is the number of the notes if you like this video please subscribe me and give me a dance app and thank you | 2024-03-24 10:12:46 | 310 | Leetcode 310. Minimum Height Trees |
|
s9bGU-3x_po | and then you have to check if a person can attend a meeting so which means I uh can attend a meeting so which means I uh in this case in this case from 0 to 30 right so this is zero this from 0 to 30 right so this is zero this is 30 and this is five this is 10 this is 30 and this is five this is 10 this is 15 this is 20. so you want to know if is 15 this is 20. so you want to know if there is an interval that can I mean there is an interval that can I mean there's a person who can intercept with there's a person who can intercept with all of the interval right so basically all of the interval right so basically we need to reward uh we need to just we need to reward uh we need to just sort the array so we have to sort based sort the array so we have to sort based on the first index so so again this one on the first index so so again this one two four right and then Seven Ten right two four right and then Seven Ten right 7 10. and then this person can attend all of the medium and this is because you can attend this one and then there's a break and then you can turn this one right and then for this one the zero and thirty right so it takes over 11 I mean I mean there are two interval overlap with this one right so uh basically like this question is supposed to be like super simple so after you sort right so I just have to check so you just have to check the starting time and ending time right so I'm gonna take two interval all of the computer so I'm going to take this one and this one so I'm going to say okay is my ending is my first ending ending right which is what which is greater than the second starting right so which means everything about intercept right all right so let's start holding so I'm going to say for in I put one I listen to rows a length and then I plus plus one so just want to make sure I soaked index and then index and then I'm gonna come here so it's my I'm gonna come here so it's my interval so 5 minus 1 is the first one interval so 5 minus 1 is the first one right first ending is my first ending right first ending is my first ending greater than the current one greater than the current one starting I will return post starting I will return post and then in this case I'm going to and then in this case I'm going to return this group return this group so so and run it uh so let's talk about the time in space uh so let's talk about the time in space so this is going to be a time and this so this is going to be a time and this is also the time so this is all the fun is also the time so this is all the fun right and this is a noggin so the time right and this is a noggin so the time is a login and this is is a login and this is uh I mean they're the space complexity uh I mean they're the space complexity is constant within allocate any is constant within allocate any variables so all of one for the space variables so all of one for the space I'm not going for the time so this is a I'm not going for the time so this is a solution and talk to you later bye | 2024-03-22 12:06:47 | 252 | LeetCode 252 | Meeting Rooms | Sort | Java |
|
7SHV_QfVROE | Hello Hi Science Students Questions, Monthly pension is available by liking Adityanath, If the Monthly pension is available by liking Adityanath, If the details of this pack abs were white part complete, then the details of this pack abs were white part complete, then the pattern has been made for graphic's reference, pattern has been made for graphic's reference, thank you, special program, Tarak Hain Mountain, thank you, special program, Tarak Hain Mountain, National football team's National football team's practice session in its struggle character, practice session in its struggle character, from Zauq electronic media friend. zanot10 only and only anti sequence subscribe 559 then click on subscribe to subscribe I am on 10 friends NRHM Payal rogue not warred because it is not warred over cost question subscribe subscribe definitely subscribe subscribe subscribe subscribe and subscribe Mark Pimple Mark Pimple Mark Pimple last checked for the last fiscal deficit only last checked for the last fiscal deficit only take essentials and if you were not a subscriber of this suite take essentials and if you were not a subscriber of this suite question mark question mark question question mark question mark question mark video channel of many countries mark video channel of many countries then on this occasion 30 to 8 minutes if then on this occasion 30 to 8 minutes if you subscribe subscribe you subscribe subscribe that you are what warriors money name that you are what warriors money name They Give Controllers Question Patton There Are They Give Controllers Question Patton There Are Five Questions Mental And The Horse On Back Five Questions Mental And The Horse On Back Subscribe Button Show Steady Stream Of The Subscribe Button Show Steady Stream Of The Country Husband Is Wondering The Observer That's Country Husband Is Wondering The Observer That's Why This Turtle Problem Subscribe Subscribe Subscribe A Flying Officer Shopping Dynamic A Flying Officer Shopping Dynamic Programming It's Very Hard To Programming It's Very Hard To Understand Why The Understand Why The Understand Why The Svabhava or else and then you use my questions in the examples and Vikram se contact example wash this mask only religious program this article only here to earn valor etc economic ruturi matrix regret field at this time when school subscribe subscribe Subscribe to ki by Subscribe to ki by Subscribe to ki by hawaii na mix kar meaning of the hawaii na mix kar meaning of the english translation for in the australian english translation for in the australian shepherd ne my it is completely way less shepherd ne my it is completely way less time a to values into flowers from som vs time a to values into flowers from som vs pair is destroy reference pair is destroy reference anti-stress patan distic president anti-stress patan distic president please subscribe please subscribe please subscribe Mere Sath Office Amazon Ke Pathak Subscribe And Financial Condition 100 And Witch Proven 210 And Spinal Column Specific 210 And Spinal Column Specific Ki Kausar Partner Jyoti Patel Point Par Ki Kausar Partner Jyoti Patel Point Par Hatim Subscribe August Month Kicks Off Hatim Subscribe August Month Kicks Off Subscribe Love U G I More Than 250 Subscribe Love U G I More Than 250 Followers The Followers The Hem Of i20 Phal Hem Of i20 Phal Hem Of i20 Phal water column on this forest profile pic playlist to right side doing this pattern all subscribe still 2014 yes yes - 134 222 aaj tak aapke print unauthorized turnoff - page not difficult viral extra ko subscribe subscribe to Flash Lights Notes Platform So Helpless Between for watching this Video that I will keep it partner question mother while doing that I will keep it partner question mother while doing soldiers force partner question soldiers force partner question wangdi se 600 candy crush subscribe wangdi se 600 candy crush subscribe subscribe a that subscribe a that pragya hai ma'am size andra se investor pragya hai ma'am size andra se investor edison important tips all difficulties for edison important tips all difficulties for students in all students in all students in all Channel [Music] Subscribe Must Subscribe To Tomorrow Morning Notifications Tractors Tasty And Of I - Kar That Fixed At The Starting Of - Man Why Not Bhi Can Gate And Matrix Liye Is Chief Combine the deal of so that fixed floating touch tractor subscribe - - that their fans after and in the morning were so improved this will remain straight return gift subscribe - panchayat next subscribe don't forget to subscribe and subscribe don't forget to subscribe and only - subscribed this video only - subscribed this video Recent Yes Parshad Stress subscribe Recent Yes Parshad Stress subscribe and subscribe the Channel subscribe subscribe subscribe to main sirf patan half rate minus one this main sirf patan half rate minus one this fact fact is the name of IPL is the name of IPL that can be given by name off side - but subscribe this Video plz subscribe Channel Please subscribe and subscribe Arrest Subscribe To Hello Hi Arrest Subscribe To Hello Hi Arrest Subscribe To Hello Hi - Mangne - Mangne 16 To Make Maut Hai Subscribe Must Subscribe My Channel A Rich Kusum And Example Sanchay Ko 10 Saal A Rich Kusum And Example Sanchay Ko 10 Saal Dharma Hotspot Phir Haar Channel Must Subscribe Swift Dharma Hotspot Phir Haar Channel Must Subscribe Swift Spots And Did Not Match Subscribe Atif Aslam subscribe and subscribe Now Question A I only and there functions based power for my channel subscribe subscribe subscribe ki aset to aaj sandwich cfab unfair loop fast subscribe and subscirbe subscribe Channel Please Channel Please Channel Please subscribe and subscribe and subscirbe Subscribe Subscribe How to work on water Sara Script Author How to work on water Sara Script Author Aegis of strength of this question on Aegis of strength of this question on Class 10th Class 10th Main 10 Director Subscribe BJP Ko Subscribe Subscribe Main 10 Director Subscribe BJP Ko Subscribe Subscribe Must subscribe Must subscribe and subscribe subscribe and subscribe subscribe that this PM oil that this PM oil that you have only that you have only that you have only for Temples Page for All Elements [Music] Subscribe Ki Yas Side Sari Ho Gayi Hai Restroom Gloves Vikram Sathi Name List A Gay Hai Question Maa Ki Dastan Quid Subscribe To Ki Tiger Is From Aap Without Introduce Embed This Value Only Most subscribe and subscribe the two subscribe and subscribe the two subscribe and subscribe the two and subscribe to that and subscribe to that I have done that Manav Bittu Rajput System I have done that Manav Bittu Rajput System Dushwaris Shekhar Labs Ki Omaze Dushwaris Shekhar Labs Ki Omaze Subscribe Eggs List Subscribe Eggs List Subscribe Eggs Paytm Ne Question Mark subscribe and And subscribe The And subscribe The And subscribe The Which Story Full Vidyalaya From Your Tests A Specific Of The Finance Form Second Final Them Is Quite Eccentric A Person Should Not Be Used To Appoint You Operation Adham 8 - Friends Triangle Participate In 8 - Friends Triangle Participate In Order That In The Question Order That In The Question Order That In The Question specific artist sperm in all cases pair getting volume diner ten subscribe and the water for patan exist subscribe se fold art festival with banner2 subscribe subscribe and share subscribe subscribe to subscribe and share subscribe subscribe to Tables Cancer Represented Tables Cancer Represented Tables Cancer Represented By 30 Months Stress Can All Subscribe Subscribe Please Like Share And | 2024-03-20 09:28:04 | 44 | Coding Interview Question | Wildcard Matching | Dynamic Programming with Optimization |
|
Ok0VVwnm0FA | hi my name is david today we're going to do number 1748 do number 1748 sum of unique elements this is an easy sum of unique elements this is an easy level problem level problem only code and we're going to solve it in only code and we're going to solve it in javascript so you're given an integer javascript so you're given an integer array nums array nums the unique elements of an array are the the unique elements of an array are the elements that appear exactly once in the elements that appear exactly once in the red red return the sum of all the unique return the sum of all the unique elements of nums so for example we get a elements of nums so for example we get a numbers array numbers array with one two three two the output is with one two three two the output is four because there's four because there's the unique elements of one and three the unique elements of one and three that only appear once we can't use two that only appear once we can't use two because we repeat it because we repeat it and we add the values of one and three and we add the values of one and three and we get four and we get four so that is what we need to do so how so that is what we need to do so how we're going to solve this we're going to solve this is that first we need to create a is that first we need to create a variable to hold this output value so create some variable to hold output and next we need uh we need to keep track of all the unique uh elements in this array so creating a hash table is a great way to organize this so we create map variable and then with this we're going to keep track of how many times it's repeated so we can say tell if it's unique or not so after that we're going to loop through nums array and inside of this loop we're going to to see the the current index value of the current index value of that value is the current index value of that value is the current index value of the the array is inside of the map array is inside of the map if it's not in it object object if it's not if it's not in it we add it in it we add it and set it to one and set it to one that's the key that's the value so that that's the key that's the value so that is going to see is going to see if it's not in it we're going to add it if it's not in it we're going to add it to it so to it so the first time we see that number we're the first time we see that number we're going to add it that value going to add it that value and set it the key value equal to 1. and and set it the key value equal to 1. and otherwise else we increment otherwise else we increment the value of that key the value of that key so we see this number against twice so so we see this number against twice so when we do this one when we do this one 2 is there twice the value is going to 2 is there twice the value is going to be 2. so be 2. so what we need to know what we need to what we need to know what we need to focus on is that focus on is that the key values that have a value of one the key values that have a value of one so after that we're gonna loop so after that we're gonna loop through the map object through the map object and inside of this we have to create a and inside of this we have to create a condition condition to see if the to see if the key value has key key value has key has a value of 1. we're gonna add the we're gonna add the sum by the integer of the key since the key will be a string and lastly you will return sum so to put it in code we first create the variable that sum and it starts off as zero and next we create the map as an empty object we loop through the nums array so for of nums and inside of it we will have to create a condition so if map the num is not in it if we're seeing this value for the first time we add it and set it equal to one we increment this value so this will get create us the map of all the unique all the unique values all the elements and how many times we've repeated so next we have to loop through the object map object for let key in map okay so when we do this we only have to take the value if the map num the the map has a key value of 1. so if map.key is equal to 1 which is what we need we by the integer of key great so great so our time complexity is that we're going to oven because we'll create we'll looping and the space complexity will also be of and since we're creating this map that's proportional to how long this gnomes array is | 2024-03-22 11:44:00 | 1,748 | How to Solve "1748 Sum of Unique Elements" on LeetCode? - Javascript |
|
xKnKFV1HbdI | hello hello hello hi guys good morning welcome back to the new video this video welcome back to the new video this video we're see the problem minimum time we're see the problem minimum time visiting All Points although it's a easy visiting All Points although it's a easy problem and it is very intuitive also problem and it is very intuitive also but it can be a way that you might get but it can be a way that you might get confused on how to approach these kind confused on how to approach these kind of problems which are kind of ad hoc and of problems which are kind of ad hoc and no algo or something is being used so it no algo or something is being used so it has been asked by Apple and that's a has been asked by Apple and that's a good thing and that is a bit frequent good thing and that is a bit frequent also so yeah it's worth to look at now also so yeah it's worth to look at now what the problem says is that in on a 2d what the problem says is that in on a 2d plane of just points now what we are plane of just points now what we are given is we have n points for sure and given is we have n points for sure and it's in the coordinate basis which is X it's in the coordinate basis which is X XI comma Yi we have to return the XI comma Yi we have to return the minimum time in seconds again we have to minimum time in seconds again we have to return minimum time in seconds to visit return minimum time in seconds to visit all the points in order given by the all the points in order given by the points again we have to visit in the points again we have to visit in the order itself and also minimum time in order itself and also minimum time in seconds which is required now how the seconds which is required now how the move movement is from one point to other move movement is from one point to other point it is that we can move point it is that we can move vertically uh one unit move horizontally vertically uh one unit move horizontally one unit and move diagonally also one one unit and move diagonally also one unit now we have to visit the points in unit now we have to visit the points in the same order as they appear as it was the same order as they appear as it was stated earlier also in the same order as stated earlier also in the same order as they appear and again uh you are allowed they appear and again uh you are allowed to pass through the points that appear to pass through the points that appear in the later in the order but these do in the later in the order but these do not count as visited again it is saying not count as visited again it is saying that you are allowed to pass a point that you are allowed to pass a point that later in the order but these does that later in the order but these does not do not count as visits which means not do not count as visits which means that if you encounter some point which that if you encounter some point which means pass through the point that appear means pass through the point that appear later in the order which means right now later in the order which means right now I'm passing through a point which might I'm passing through a point which might appear later in the order but still when appear later in the order but still when that point chance will come as in let's that point chance will come as in let's say P1 P2 P3 while traveling from P1 to say P1 P2 P3 while traveling from P1 to P2 if I'm traveling via P3 it doesn't P2 if I'm traveling via P3 it doesn't count that okay I have traveled P3 I count that okay I have traveled P3 I will have to travel from P2 to P3 for will have to travel from P2 to P3 for sure when I will be traveling so it is sure when I will be traveling so it is as that uh let's say in P3 might come in as that uh let's say in P3 might come in between but still it is not counted its between but still it is not counted its chance will come when it is about to get chance will come when it is about to get counted cool so for for example it's the counted cool so for for example it's the best example they have given we travel best example they have given we travel from 1 1 which is 1A 1 to actually 3A 4 from 1 1 which is 1A 1 to actually 3A 4 again we want to travel in minimum again we want to travel in minimum possible time again I would have said possible time again I would have said okay 1 1 2 sorry 1 2 3 4 5 from okay 1 1 2 sorry 1 2 3 4 5 from traveling from 1A 1 to 3A 4 I would have traveling from 1A 1 to 3A 4 I would have used 5 Seconds of five as a time but used 5 Seconds of five as a time but still I can travel this in 3 seconds 1 2 still I can travel this in 3 seconds 1 2 and 3 you saw that is nothing but you and 3 you saw that is nothing but you tried your best to travel diagonally for tried your best to travel diagonally for sure some whenever you want to travel sure some whenever you want to travel anywhere you travel that diagonally anywhere you travel that diagonally first so as to travel the minimum first so as to travel the minimum distance and you know one thing even if distance and you know one thing even if I travel as horizontal it's a 1 second I travel as horizontal it's a 1 second even if I travel vertical it's a 1 even if I travel vertical it's a 1 second even if I travel diagonal it's a second even if I travel diagonal it's a 1 second so for this portion it is 1 second so for this portion it is taking 3 seconds again from 3A 4 next is taking 3 seconds again from 3A 4 next is - 1A 0 again I'm traveling in order of - 1A 0 again I'm traveling in order of points itself and you can see it's a points itself and you can see it's a straight line you can just travel straight line you can just travel diagonally down and thus it is giving us diagonally down and thus it is giving us a 1 2 3 and 4 4 seconds for here 3 a 1 2 3 and 4 4 seconds for here 3 seconds for here ultimately it's a 7 seconds for here ultimately it's a 7 Seconds that's an answer now one thing Seconds that's an answer now one thing for sure for sure you might have seen by for sure for sure you might have seen by this example itself is when you ever in this example itself is when you ever in general in real life also whenever you general in real life also whenever you want to travel to a point you try to want to travel to a point you try to travel that diagonally as much as travel that diagonally as much as possible the same will happen and the possible the same will happen and the cost is also same even if you travel cost is also same even if you travel horizontally or vertically or diagonally horizontally or vertically or diagonally the cost is always one so one thing is the cost is always one so one thing is for sure my first preference is to for sure my first preference is to travel dally and then and then travel dally and then and then whatsoever and then whatsoever it is whatsoever and then whatsoever it is either it can be a vertical or it can be either it can be a vertical or it can be a horizontal I can just try travel in a horizontal I can just try travel in that way now comes the interesting part that way now comes the interesting part that one thing I have to only make sure that one thing I have to only make sure is that how much time it will require is that how much time it will require how much minimum time it will require to how much minimum time it will require to travel from a point P1 to a point P2 travel from a point P1 to a point P2 because the same I have to repeat for because the same I have to repeat for every Point as my only task is to figure every Point as my only task is to figure out the time needed for my traveling out the time needed for my traveling from my01 to point 2 now the best from my01 to point 2 now the best example for us is this point1 and this example for us is this point1 and this point 2 because for sure for this point point 2 because for sure for this point 2 to point3 you can see it is diagonal 2 to point3 you can see it is diagonal so we can just easily say that so we can just easily say that whatsoever is a diagonal time here you whatsoever is a diagonal time here you will see 3 - 1 4 - 0 so 3 - of -1 4 will see 3 - 1 4 - 0 so 3 - of -1 4 minus of 0 both are giving me as four minus of 0 both are giving me as four and you will see that X I have to travel and you will see that X I have to travel four as you can see X I have to travel four as you can see X I have to travel four y I have to travel four ultimately four y I have to travel four ultimately I'll take the minimum of both of them or I'll take the minimum of both of them or basically you can also say maximum basically you can also say maximum because both are for sure equal so because both are for sure equal so anything I can take when I am directly anything I can take when I am directly and only traveling diagonally so that I and only traveling diagonally so that I can take anything I can take because it can take anything I can take because it is only traveling only traveling is only traveling only traveling diagonally now comes the interesting diagonally now comes the interesting part is how will you do for the part is how will you do for the situation situation as I told that first is to travel always as I told that first is to travel always diagonally now whenever I have a point diagonally now whenever I have a point 1A 1 can I just say that okay 3 comma 4 1A 1 can I just say that okay 3 comma 4 is other point so for sure if it had to is other point so for sure if it had to travel diagonally only then it would travel diagonally only then it would have traveled this up till 3A 3 it would have traveled this up till 3A 3 it would have traveled diagonally 3 comma 3 it have traveled diagonally 3 comma 3 it would travel only diagonally or I can would travel only diagonally or I can easily say if I have this coordinate as easily say if I have this coordinate as 3 3 - 1 is 2 so it is saying I traveled 3 3 - 1 is 2 so it is saying I traveled horizontally 2 4 - 1 is 3 it is saying I horizontally 2 4 - 1 is 3 it is saying I traveled vertically 3 what you can see traveled vertically 3 what you can see is this three I can break it down to two is this three I can break it down to two and one right two and one two and one and one right two and one two and one now when this is broken as two and one now when this is broken as two and one you can easily see that two it is you can easily see that two it is traveling diagonally and remaining one traveling diagonally and remaining one it is traveling horizont yeah vertically it is traveling horizont yeah vertically here in this case it is traveling here in this case it is traveling vertically but it is very easy to infer vertically but it is very easy to infer that whatsoever maximum value is now in that whatsoever maximum value is now in this case maximum value difference this case maximum value difference maximum value is 40 y it is actually maximum value is 40 y it is actually three it can also be that X is maximum three it can also be that X is maximum like X is more but it is inferring that like X is more but it is inferring that the common part which means this common the common part which means this common part is used to travel diagonally and part is used to travel diagonally and the remaining part is used to travel the remaining part is used to travel vertically so I can say 2 + 1 is vertically so I can say 2 + 1 is actually the answer or I can also say actually the answer or I can also say that ultimately 4 - 1 which is 3 is also that ultimately 4 - 1 which is 3 is also the answer because it is a summation of the answer because it is a summation of diagonal plus vertical so I can just say diagonal plus vertical so I can just say that in this I'll do a 3 minus of Min -1 that in this I'll do a 3 minus of Min -1 4 minus it's a minus one sorry 3 - of 1 4 minus it's a minus one sorry 3 - of 1 or 4 minus of one whatsoever is the or 4 minus of one whatsoever is the maximum value just give me that maximum maximum value just give me that maximum value but Arian that can be negative value but Arian that can be negative also right if you are just moving to also right if you are just moving to some other coordinates so yeah that can some other coordinates so yeah that can be true to so simply take a absolute of be true to so simply take a absolute of this and take the maximum and that will this and take the maximum and that will give you the minimum time travel from give you the minimum time travel from point 1 to point 2 because you are point 1 to point 2 because you are choosing to travel first diagonally and choosing to travel first diagonally and then remaining points is either then remaining points is either horizontally or vertically and that will horizontally or vertically and that will be for sure included in the difference be for sure included in the difference itself cool let's quickly see that how itself cool let's quickly see that how we'll code it we'll simply go on to all we'll code it we'll simply go on to all the points and simply have a maximum of the points and simply have a maximum of absolute difference between their absolute difference between their corresponding x coordinates and y corresponding x coordinates and y coordinate and whatever is maximum we'll coordinate and whatever is maximum we'll just take that particular value let's just take that particular value let's quickly see that uh firstly uh we know quickly see that uh firstly uh we know that we want to have an answer uh we that we want to have an answer uh we will also have points size because it's will also have points size because it's easy for us to travel now I I want to easy for us to travel now I I want to have a difference between two have a difference between two consecutive points so um I can just consecutive points so um I can just iterate starting from the point one now iterate starting from the point one now for sure that I want to increase for sure that I want to increase something in my answer so I'll just say something in my answer so I'll just say take the maximum of uh now maximum I take the maximum of uh now maximum I have two options uh first is the x have two options uh first is the x coordinate difference uh which is coordinate difference uh which is nothing but points of I of0 and points nothing but points of I of0 and points of IUS one of 0 and second is the of IUS one of 0 and second is the y-coordinate difference which is y-coordinate difference which is absolute of points of I and 1 minus uh absolute of points of I and 1 minus uh points of i- one and one now when this points of i- one and one now when this portion is done simply return the answer portion is done simply return the answer because I am by this I'm trying to because I am by this I'm trying to choose either vertically or horizontally choose either vertically or horizontally as maximum difference value and that as maximum difference value and that will make sure that I either traveling will make sure that I either traveling diagonally and then either hor or diagonally and then either hor or vertically cool vertically cool thank and yeah the time is actually o of thank and yeah the time is actually o of N and space is O of one time o of n N and space is O of one time o of n because you are traveling on all the end because you are traveling on all the end points and space is O of one because you points and space is O of one because you not using any extra space at all cool not using any extra space at all cool see you guys see you guys bye-bye | 2024-03-19 17:48:24 | 1,266 | 1266. Minimum Time Visiting All Points | Apple | Media.net | Space - O(1) |
|
svOIvIozkcs | welcome to SF job slab we bring you our possible solution of interview portion possible solution of interview portion including the most efficient one and including the most efficient one and today we will see how to find a median today we will see how to find a median of two sorted arrays of size M and M so of two sorted arrays of size M and M so let us understand this portion with an let us understand this portion with an example so let's assume if we have these example so let's assume if we have these areas where we have element values 6 9 areas where we have element values 6 9 15 and 39 in array a and we have two 10 15 and 39 in array a and we have two 10 31 65-69 in Arabi and this arrays are 31 65-69 in Arabi and this arrays are already sorted so in this case our already sorted so in this case our median would be 15 median would be 15 and if we have these arrays as an input and if we have these arrays as an input then in this case our median would be then in this case our median would be six point five so I guess question is six point five so I guess question is pretty much straight over so if you have pretty much straight over so if you have understood this very well so you can understood this very well so you can pause this video for a while and you can pause this video for a while and you can solve the problem with yourself first or solve the problem with yourself first or else less continue for the solution else less continue for the solution before you go to the solution I want to before you go to the solution I want to tell you that we are going to cover this tell you that we are going to cover this problem in two different part in this problem in two different part in this part or we are going to see all possible part or we are going to see all possible solution so it is my request you to all solution so it is my request you to all if you want to see the most efficient if you want to see the most efficient solution of this problem then please do solution of this problem then please do watch this video till the end and in the watch this video till the end and in the second part we will see how to code in second part we will see how to code in the interview for this problem as we the interview for this problem as we have to find a median then it is very have to find a median then it is very important for us to understand what is a important for us to understand what is a median first and what are the key median first and what are the key properties we have to keep in mind while properties we have to keep in mind while looking for the median so let's see that looking for the median so let's see that first so let us assume if you have some first so let us assume if you have some sequence number like this and we have to sequence number like this and we have to find out what is the median of find out what is the median of disciplines the first thing first we disciplines the first thing first we have to do is we need to sort this have to do is we need to sort this sequence first and then after sorting if sequence first and then after sorting if our sequence size is odd then our median our sequence size is odd then our median will be in the element which is placed will be in the element which is placed at n plus 1 by 2 'the element so in our at n plus 1 by 2 'the element so in our example you can see that the size of the example you can see that the size of the sequence is 9 so basically the 5th sequence is 9 so basically the 5th element will be our median so 5th element will be our median so 5th element is element is this 10 but if the sequence size is even this 10 but if the sequence size is even then in that case medium will be the then in that case medium will be the every job and by 2 and n by 2 plus one every job and by 2 and n by 2 plus one element okay so for even case let's element okay so for even case let's assume if you have a one more element assume if you have a one more element here 11 then after sorting our shipments here 11 then after sorting our shipments will arrange in this increasing order will arrange in this increasing order where the fifth and sixth element we where the fifth and sixth element we have to take the average of the fifth have to take the average of the fifth and sixth element which is 10 and 11 and sixth element which is 10 and 11 which will come as a 10.5 so in this which will come as a 10.5 so in this case our median will be 10.5 and if you case our median will be 10.5 and if you observe very closely then what this observe very closely then what this median does is the median will divide median does is the median will divide the sequence in two equal halves so if the sequence in two equal halves so if you see in this case you will have a you see in this case you will have a left sub sequence where the size is four left sub sequence where the size is four and you will have a right sub sequence and you will have a right sub sequence in this also you will have four element in this also you will have four element right the same case when we have the right the same case when we have the even size sequence so in this case also even size sequence so in this case also if you see that the median has divided if you see that the median has divided our sequencing two equal halves where our sequencing two equal halves where the left side you will have five the left side you will have five elements and in the right side also you elements and in the right side also you have five elements one small correction have five elements one small correction here this is 56 anyways and just people here this is 56 anyways and just people so this sequence is in increasing order so this sequence is in increasing order so this is pretty much obvious that the so this is pretty much obvious that the element value which is there in the element value which is there in the right sub sequence those values will be right sub sequence those values will be always greater than the element value always greater than the element value which is there in the left sub sequence which is there in the left sub sequence right so finally we can summarize our right so finally we can summarize our discussion into these three points so if discussion into these three points so if we have to find a median then the first we have to find a median then the first point is we need to sort the sequence point is we need to sort the sequence first and then based on the sequence first and then based on the sequence size we have to get the middle element size we have to get the middle element of the sequence and the median will of the sequence and the median will divide our sequence into two equal divide our sequence into two equal halves so remember these three points halves so remember these three points now let's get back to the question now now let's get back to the question now we will take this inputs in our further we will take this inputs in our further discussion and let's start with a basic discussion and let's start with a basic approach first approach first then we will see how we can get the then we will see how we can get the median value as in 15 here okay so in median value as in 15 here okay so in basic approach what we can think of that basic approach what we can think of that we can create new AIRAID let's name it we can create new AIRAID let's name it see in which we'll add all the element see in which we'll add all the element of a and B one by one so let's start of a and B one by one so let's start adding the element value of a and once adding the element value of a and once we'll get over with array a then we'll we'll get over with array a then we'll start adding all the elements value of B start adding all the elements value of B then as we know that through finding out then as we know that through finding out median we have to sort the entire median we have to sort the entire sequence first and then as we have size sequence first and then as we have size here is nine and then we will use our here is nine and then we will use our formula so here and is hard that means formula so here and is hard that means our median will be there at this place our median will be there at this place right means our median is stripped right means our median is stripped element which is nothing but Krypton element which is nothing but Krypton here this is a good start but the here this is a good start but the problem here is we are creating a one problem here is we are creating a one new array while C which is consuming new array while C which is consuming extra space and the second problem is extra space and the second problem is time complicity here we are doing a sort time complicity here we are doing a sort operation so any good sorting algorithm operation so any good sorting algorithm will take n log n time complicity so for will take n log n time complicity so for this approach and complicity will be this approach and complicity will be order out n plus M log n plus M right order out n plus M log n plus M right just because in question it is given the just because in question it is given the size of a and B is eminent so total size of a and B is eminent so total element we have M plus n in the same way element we have M plus n in the same way space complicity space complicity have order of and plus M so to optimize have order of and plus M so to optimize our solution from here definitely we our solution from here definitely we have to think better than n log n time have to think better than n log n time complexity right that means we have to complexity right that means we have to think of this stage whether we have to think of this stage whether we have to do a sorting or not I mean we would have do a sorting or not I mean we would have done sorting if we would have had both done sorting if we would have had both array a and B in unsorted order but here array a and B in unsorted order but here we have both array a and B in sorted we have both array a and B in sorted order that means we have to simply merge order that means we have to simply merge them in such a way that the final them in such a way that the final segment should be in sorted order segment should be in sorted order and if you remember that this kind of and if you remember that this kind of logic we already have used it you know logic we already have used it you know in Malad right so now we will optimize in Malad right so now we will optimize the same logic over here so let's merge the same logic over here so let's merge this is same as what we do in Mashhad this is same as what we do in Mashhad we'll pick one element from a and one we'll pick one element from a and one element from B so here we will be element from B so here we will be picking six and two and we will take picking six and two and we will take minimum of this two and we'll place that minimum of this two and we'll place that into our Odyssey so two will come here into our Odyssey so two will come here and then we will pick minimum of this and then we will pick minimum of this two element six and ten so six will be two element six and ten so six will be placed in second position after which placed in second position after which we'll pick minimum of nine and ten so we'll pick minimum of nine and ten so nine will come here like this we'll keep nine will come here like this we'll keep on repeating our process and at this point of time as we have reached a last element of a then whatever the element we are left with in array B we will put all the elements one by one at the hand of the C and now if you see a we have a sorted array C and after which as we know that the size is and if you think about the time and if you think about the time complicity so if you have so that we complicity so if you have so that we have is can only once bow that is a and have is can only once bow that is a and B so that means the time converse field B so that means the time converse field would be order of n plus M right and would be order of n plus M right and just because we are creating a new array just because we are creating a new array because of that we are still consuming because of that we are still consuming space and plus M so this solution is far space and plus M so this solution is far better than the previous one and because better than the previous one and because we have optimized the time complicity we have optimized the time complicity over here and now to optimize further over here and now to optimize further this time people think about space this time people think about space complexity do we actually need this complexity do we actually need this obsolete space so let's see one obsolete space so let's see one situation here where is 1 2 3 4 and B is situation here where is 1 2 3 4 and B is having element 5 6 7 8 and let's assume having element 5 6 7 8 and let's assume if this is a our left subsequence and if this is a our left subsequence and this is our right subsequence and if you this is our right subsequence and if you calculate the last element of left calculate the last element of left subsequence which is 4 is actually subsequence which is 4 is actually lesser than the first element of the lesser than the first element of the right subsequence right so once you get right subsequence right so once you get to know about this condition we will to know about this condition we will immediately get to know that the immediately get to know that the elements of right subsequence is greater elements of right subsequence is greater than all the elements of the left sub than all the elements of the left sub sequence now think that do we actually sequence now think that do we actually need extra space to figure out median need extra space to figure out median here no right just because in this case here no right just because in this case our median would be 4 plus 5 by 2 which our median would be 4 plus 5 by 2 which is 4 point 5 so from this observation we is 4 point 5 so from this observation we can clearly see that we have to always can clearly see that we have to always look in to the last element of the left look in to the last element of the left sub array and the first element of the sub array and the first element of the rights of area right so this was all rights of area right so this was all corner case now let's see standard case corner case now let's see standard case so let's suppose if we have our sub so let's suppose if we have our sub arrays like this where a 1 to a 8 is a arrays like this where a 1 to a 8 is a part of array E and B 1 to B 10 is a part of array E and B 1 to B 10 is a part of our led and remember this this part of our led and remember this this array is already sorted here total array is already sorted here total numbers of element we have 18 that means numbers of element we have 18 that means each sub array will have 9 elements and each sub array will have 9 elements and as you can see that we already have as you can see that we already have our left and right sub area the red our left and right sub area the red element is a part of the left sub area element is a part of the left sub area and the green element is a part of the and the green element is a part of the right sub array so in step 1 the first right sub array so in step 1 the first thing first we have to do is we have to thing first we have to do is we have to calculate the last element of the left calculate the last element of the left sub array right so in the left sub array sub array right so in the left sub array if you see then then the last element if you see then then the last element will be the maximum of a for na be will be the maximum of a for na be Phibes Phibes because again this starting from E to a because again this starting from E to a fourth is the sorted and B 1 to B files fourth is the sorted and B 1 to B files all also sorted so if you'll merge that all also sorted so if you'll merge that using a merge technique right so in that using a merge technique right so in that case the last element of this will be case the last element of this will be the maximum of a 4 or B 5 okay that is the maximum of a 4 or B 5 okay that is pretty much fear and now in the second pretty much fear and now in the second step we have to figure out first element step we have to figure out first element of the right sub array which will be the of the right sub array which will be the minimum of a 5 and B seats again with minimum of a 5 and B seats again with the same much logic and now in third the same much logic and now in third step we need to check this condition if step we need to check this condition if this condition is true and now we can this condition is true and now we can find a median bit using the standard find a median bit using the standard formula you total size is even then we formula you total size is even then we have to use the max of F would be PI have to use the max of F would be PI plus me know if I be 6 divided by 2 if plus me know if I be 6 divided by 2 if the size is odd then we have to return the size is odd then we have to return match of a 4 B 5 why we are returning match of a 4 B 5 why we are returning here max of a 4 B 5 because in that case here max of a 4 B 5 because in that case the size of the left sub array will be 1 the size of the left sub array will be 1 mol then the size of the rights of in it mol then the size of the rights of in it ok so if the total size is 9 then we ok so if the total size is 9 then we will have 5 elements in the left sub will have 5 elements in the left sub array and will have a 4 elements in the array and will have a 4 elements in the rights of it okay so that is pretty much rights of it okay so that is pretty much obvious that the last element of the obvious that the last element of the left sub array will be the middle left sub array will be the middle element of the entire area right and if element of the entire area right and if the condition is not satisfied then in the condition is not satisfied then in that case we have to move our max of a 4 that case we have to move our max of a 4 B 5 towards right side so let's assume B 5 towards right side so let's assume if a 4 is a maximum in this a 4 end d5 if a 4 is a maximum in this a 4 end d5 so you can see that now a 4 will be the so you can see that now a 4 will be the part of the right sub array and just part of the right sub array and just because we have to maintain the equal because we have to maintain the equal size so because of that the B 6 which size so because of that the B 6 which was the part of the right sub array now was the part of the right sub array now that will be the part of the left sub that will be the part of the left sub array okay then again we'll repeat our array okay then again we'll repeat our step one process means the last element step one process means the last element of the left sub array will be maximum of of the left sub array will be maximum of III and b6 III and b6 similarly the first element of the right similarly the first element of the right sub array will be the minimum of F or n sub array will be the minimum of F or n b7 and now let's see some other scenario b7 and now let's see some other scenario as well so if our array and B will have as well so if our array and B will have these elements so in this case you can these elements so in this case you can see that we have a lots of array see that we have a lots of array containing elements from both a and B containing elements from both a and B but in the right sub array we have only but in the right sub array we have only elements from array B so in this case so elements from array B so in this case so everything look the same the only everything look the same the only difference is no while calculating the difference is no while calculating the first element of the right subtree then first element of the right subtree then we have to return B body in the same way we have to return B body in the same way we can encounter such kind of scenario we can encounter such kind of scenario as well where the lots of array will as well where the lots of array will have all the elements from array a and have all the elements from array a and the right sub array will have a elements the right sub array will have a elements from both array a and B so in this case from both array a and B so in this case in step one we have to return a seven in step one we have to return a seven enough for better understanding let's enough for better understanding let's understand this process with an example understand this process with an example let us assume if our input array a is let us assume if our input array a is this and array B is having this elements so as you can see that the length of array is 10 and length of array B is 6 which means our left sub array and right sub array size will be 8 so at the beginning I am dividing our survey race like this so what are the elements is towards left side of this boundary is a part of blood sovereign and the elements which is right side of this boundary line is a part of rights over it and now let's start our process here so in step 1 we'll be calculating max of 79 and 9 which will return 79 and second step we will be calculating Minos 51 and 15 which will return 15 now we will check it is lesser than so it is not 79 is greater than 15 that means this 79 should be part of the right sub array so let's do that so we have reduced one element from a and we have added one element from B right and now again we will calculate a step one we have to calculate max of 72 15 this will return 72 and from the right side we have to type in me knob 79 and 39 which will return 39 so again 72 is greater than 39 so we cannot find our median at this point of time that means we have to sift 22 towards right side and again we'll calculate max of 69 and 39 which will return 69 and from right side will calculate min of 72 and 42 which will return 42 so here also the condition is not ready satisfied that means again we have to accept our boundary towards left side and now let's calculate again max off and 42 this will return 42 and from right side again me know 69 and 49 so this will return 49 so here the condition is getting satisfied here 42 is lesser than 49 that means at this point of time we have divided our errors in two groups every group will have the same size and the element value of the right sub array will be greater than the element of element value of the left sub array that means now we can find a median over here so we'll apply the formula here and the total size is even that means our median will be average of 42 plus 49 by two and now if you think about the space complicity over here so as you can see that we have not used any extra memory so it's paste complicity here is constant and now let's analyze our time complicity here so what we have been doing here starting from the beginning is that we are looking for a number which can satisfy our condition right so that's why you know we started from here 79 but this pair was not getting satisfied so we jumped to 72 and then we jumped to 69 and here also the condition was not satisfied so we jump to 10 so here you can clearly see that we are moving towards left linearly right and this moves we can do for many times we can do this many times let's say if size of B is M then we can move like this one by one in M times that means time complexity of this is order of min of M comma M and now the question is can we optimize our performance better than this so the answer is yes we can do that by just because here we have to notice one thing that we are searching element on sorted array and as we know that most efficient way to search any element on sorted array is through binary search so instead of doing a linear search over here now we will be finding our element through binary search so let's do that so this was our initial situation where our condition was not satisfied so now instead of moving linearly towards left side now what we will do we will be a jumping middle element of dis away okay so middle of this happily is ten so let's move our boundary from seventy nine to ten and then we need to calculate max of 10 and 42 which we'll return 42 and if we need to calculate min of 69 and 49 so this will return 49 and now you can see that our condition is getting satisfied over here then we need to stop our operation at this point of time and if you think of time complicity over here so it will be order of o log of min of M comma hat and this is our optimal performance of this problem I hope that you liked this video and if you do so so please share this with your friends who is especially preparing for the interview and through comments please let us know which kind of questions you want us to cover in our next video thanks again for watching | 2024-03-18 10:49:17 | 4 | Find Median of Two Sorted Arrays of Different Sizes | Data Structure Interview Questions |
|
OqcUWxkd5Rs | hey what's up guys this is chung here again again so this time i'll lead code number 1938 maximum genetic difference query uh so this one is a pretty difficult one like to be it has some many a few it has some many a few small sub problems we need to solve small sub problems we need to solve first first okay so we you're given like a rooted okay so we you're given like a rooted tree right consisting of unknowns number tree right consisting of unknowns number from 0 to n minus 1 from 0 to n minus 1 and each node's number right denotes to and each node's number right denotes to its unique genetic value basically the its unique genetic value basically the root the root the the node number is its value the node number is its value and the genetic difference between two and the genetic difference between two genetic value genetic value values is defined as a bitwise or right values is defined as a bitwise or right so this is a pretty so this is a pretty common problem type of problem bitwise common problem type of problem bitwise or or okay and okay and and then you're given like integer array and then you're given like integer array parent parent because we're gonna need we can use this because we're gonna need we can use this one to this one to build like a one to this one to build like a tree right and then you're also given like a red queries right where the queries has two values the first one is the node right and the second one is a value so for each queries we need to find the maximum genetic difference between the value of and all all its parents of the current node including the this right and then we want right and then we want we want to return this answer right we want to return this answer right after each query after each query so basically what does it mean it means so basically what does it mean it means that you know uh first you're given like that you know uh first you're given like a tree a tree right and then in the form of a parent right and then in the form of a parent and then you're given like a queries so and then you're given like a queries so for each query what we need to get is for each query what we need to get is that you know the first one is a node that you know the first one is a node right right so this one means that you know from the so this one means that you know from the current node all the way back to its current node all the way back to its parent parent right then we have like different values right then we have like different values along the way right along the way right and the and we won't get the maximum and the and we won't get the maximum bitwise or bitwise or right between this value in the queries right between this value in the queries and all the values uh and all the values uh on this path right to the to the to the on this path right to the to the to the root root that's why you know so this is the tree that's why you know so this is the tree we have here right and then the queries we have here right and then the queries we have is 0 2 we have is 0 2 3 2 and 2 5. so the answer is 2 3 5 3 2 and 2 5. so the answer is 2 3 5 because because for root 0 right i mean there's nothing for root 0 right i mean there's nothing right for root 0 right for root 0 it's uh there's there's only one node it's uh there's there's only one node right we can right we can we can use which is two basically zero we can use which is two basically zero x uh b twice x or x uh b twice x or right to two equals to two all right right to two equals to two all right that's why we have two but for three that's why we have two but for three right as you right as you first three uh we have we have three first three uh we have we have three nodes that we can use which which nodes that we can use which which is three one and zero right among those is three one and zero right among those three nodes three nodes i uh the biggest value we can get it is i uh the biggest value we can get it is is this one is because the it's one with a difference of that's going to be the 2x or one basically the value is two here right and then the best we can use is this node which is one equals to one which is three sorry equals to three and the third one is two and five right so for two and five we have two one and zero we have three notes to use right and an amount of three ones i think i believe we pick two because 5x or 2 equals 7 which will give us the the biggest one right so that's basically the the description of this problem right and then we have some common common like uh constraints right i think those are pretty common ones and the value is also this one right okay so for this one you know and every time you know every time when you guys see a b to wise x or plus a bunch of queries we need to solve you know i think the first thing we should always uh think about consider the the beat uh try or the beat prefix tree because you know the beat prefix 3 can give us like a very uh i think all of constant time to query to get to query the uh the values the the biggest value among all the available numbers in this case is uh in this case it's all the the parent nodes including the node itself right and for those who don't who doesn't know what the bit prefix tree is that you know maybe i can give you a brief introduction here you know for example we have you know like i said we have a bunch of numbers uh along the way we want to compare right among those numbers we want to efficiently quickly find which one number can give us the best or the the biggest uh xor value with the current value right um so how can i where should i start you know so first we need to convert each of the numbers to its bit value so let's say we have these two values here one zero a few numbers here okay and then we have 0 1 1 1 0 and then we have another one 1 0 0 1 0 right there could be more right so those are the available numbers okay and our current number is what our current number is this one let's say the current number is 0 zero one zero one so this is the current number we're trying we're trying to use and we want among we want to find the biggest number right that can can get which can give us the maximum value here right and how should we do it i mean obviously we want to check the values bit by bit assuming we only have like five bits five five bits in in our case right so the ideal case is what ideal case is like this ideal case if we have a number if we have a number is this one one zero one zero right this is the this is the ideal case because this will give us what this will give us uh one one one one one right which is the maximum possible number we can get right but obviously this one as you guys can see this one does not exist in this in this set right but you but you guys see the pattern here so basically you want to make we want to get and okay so which means that you know and okay so which means that you know we won't get as many ones as possible we won't get as many ones as possible and we want to get at and we want to get at the the ones can give us the biggest the the ones can give us the biggest value value first because right so which one uh first because right so which one uh which bit can give us the which bit can give us the the biggest value we obviously is the the biggest value we obviously is the one from one from from the left left side this is the the from the left left side this is the the first one we want to get first one we want to get right that's why you know uh right that's why you know uh what we want to check that we want to what we want to check that we want to see okay if if there's any number see okay if if there's any number that has this this bit equals to one that has this this bit equals to one right if it is and then we know okay at right if it is and then we know okay at least we can get least we can get what we can get 2 to the power of what we can get 2 to the power of of 4 right which is 16 of 4 right which is 16 right so basically if if this one if we right so basically if if this one if we have a number have a number who has the value bit y bit value equals who has the value bit y bit value equals to one to one for this one no i know we at least i can for this one no i know we at least i can get 16 get 16 right and the reason we want to use this right and the reason we want to use this one first is because you know one first is because you know if there's a one if there's one has a if there's a one if there's one has a bit value bit value equals to to one here we will definitely equals to to one here we will definitely use that number because you know use that number because you know otherwise if this one is zero otherwise if this one is zero even though everything else is equal to even though everything else is equal to one right one right so what's this value this is 15 right 15 so what's this value this is 15 right 15 still smaller than 16. still smaller than 16. that's why i want to gradually pick the that's why i want to gradually pick the ones from the ones from the from the left from the left from the left from the left right so so now we see okay so right so so now we see okay so we have one right so there's a there's we have one right so there's a there's one here one here there's one there's actually there are there's one there's actually there are two numbers two numbers two numbers two numbers that have one for this bit okay how that have one for this bit okay how about the second one about the second one second we're also trying to see if second we're also trying to see if there's a one here but you know there's a one here but you know since we we already picked since we since we we already picked since we already picked already picked this one here you know after the one uh this one here you know after the one uh both of them have value zero both of them have value zero right so which means what so which means right so which means what so which means this this the second one is not possible this this the second one is not possible because even though we have a we have because even though we have a we have one here but this one one here but this one coming from the zero right which we coming from the zero right which we didn't use didn't use because we picked the ones we this which because we picked the ones we this which is the one is the one we picked those two numbers with the we picked those two numbers with the ones here that's why we ones here that's why we we have to use zero here right so which we have to use zero here right so which means zero is not possible how about the means zero is not possible how about the third one third one the third one uh what we're looking for the third one uh what we're looking for is a zero is a zero do we have zero yes we have zero here do we have zero yes we have zero here right right that's why you know we have what then that's why you know we have what then since we have this one we can have like since we have this one we can have like uh two to the power of two right if we keep going right so this the next one is what the next one we're looking for is one right do we have one here right we have one here which is this one because you know since we have we have already followed this path now this one is not available anymore we have to go with this one right that's why we have another of one how about zero yes we have zero that's so that's basically the uh the values we so that's basically the uh the values we can get right can get right and this is how we use the uh the binary and this is how we use the uh the binary fixed tree you know because fixed tree you know because the way binary binary the way binary binary uh sorry not not binary or bit be the uh sorry not not binary or bit be the prefix trace like this prefix trace like this we have a root here so for roots right we have a root here so for roots right so each root can only have possible so each root can only have possible either either zero or one node either basically either zero or one node either basically either either one node or either has no node either one node or either has no node zero zero or node has one so for this one you know or node has one so for this one you know we have one here right so that's why you we have one here right so that's why you know we have know we have we have one here okay and then we have we have one here okay and then we have zero so let's define the left one is zero so let's define the left one is always zero the right one is always one always zero the right one is always one then we have zero here okay and then then we have zero here okay and then next one is one next one is one right so we have one here and then next right so we have one here and then next one is also one one is also one okay and then the last one is zero okay and then the last one is zero okay so that's how we insert the first okay so that's how we insert the first number into this number into this uh bit uh try right uh bit uh try right and then the second one is 0 1 1 so we and then the second one is 0 1 1 so we have 0 and then we have 1 have 0 and then we have 1 right and the next one is also 1 also 1 last one is 0. right the last one is this one 1 0 0 zero one so we have one we have zero and then we have we have we have zero in this case right and then we have one and then we have zero all right so that's how we build this uh bit bit uh prefix tree and when it comes down comes down to uh how do we how can we use it right like i said we start from we start from this root right and we traverse we check we're looking for one right for the first one okay so that's why you know we'll go here right because we have one and then from from the one here right we're also look so the next one we're also looking for for one right but we don't have a one after this one we only have zero right that's why you know we'll we'll move to zero and notice that we only increase uh accumulate the answers when when we can find a match right because otherwise you know this bit will be zero zero means there's no value right to be to be added so that's why we have zero right because we don't have anything right so we have zero and the next one is is what next one is also we're looking for zero in this case right that's why we'll go go here right so that's why we're coming here and then the last one is the next one is one right and then the next one is one and then the last one is zero that's how we traverse this one down down down the row right to get the uh the maximum possible okay so that's the uh the basic okay so that's the uh the basic idea of the prefix tree you know i uh i hope you guys uh understand how it works okay so given this one right the next problem is that how can we find this kind of uh basically candidates right we can do the x word um so let's go back to the uh to the problem right as you guys can see right the uh the queries is for the current for the node right and so the brutal force way is that for the current node we want to find all the other parents nodes and then we add all the parents nodes into the uh into know just a bit try right and then we just do a query on on that but if we do that if we do that do it that way uh for each of them to create here right to find all the parents notes worst case scenarios we need an untime right and then for the queries here you know it's going to be n times n right going to be n square time complexity for that that's why you know we cannot use that because the with this constraints here i think it will most likely tle right that's why we have to find like a more efficient way to to do the query right so what we can do is that you know since we have a tree structure here right i mean we can create we can do the query along the way while we're tr while we're doing the dfx reverse of of the tree here so what does it mean it means that let's see we have everyone knows dfs right so we have dfs here so dfs we have a u here right every time when we when we visit a u here right we insert we're going to into the pre into the bit of try the into the pre into the bit of try the prefix tree prefix tree and after df has finished we're going to and after df has finished we're going to remove it we're going to remove the u from the prefix tree because you know for example for this one right so when we have 0 1 and 2 right so once two is once two is it's finished processing and then the next one from one is is going to be three right but at this moment let's say two has already been added right to the prefix tree now when we're processing three here we don't want the two to be we we need to remove two from the previous three because obviously for three we have we only have three one and zero we don't have two that's why we have to find the efficient way to remove the to remove the two from the prefix tree right so how can we remove it uh a trick is that we can keep a count we can keep a count for each of the node in the in the prefix tree and every time when we insert when we insert we increase that the count by one and when we remove we simply just uh do a decrease that okay and then later on when we try to query the prefix tree we also need to check if the count is greater than zero right if it's zero then we know it there there's a value there this this bit has a value right from some okay and that's that right nice as you okay and that's that right nice as you guys can see so for this one guys can see so for this one we can simply just uh piggyback on this we can simply just uh piggyback on this dfs dfs traverse right and then to calculate the traverse right and then to calculate the the queries right basically you know the queries right basically you know what what i mean what what what i mean what what i mean is that you know every time what i mean is that you know every time we have like a u here you know we have like a u here you know after inserting here we can do something after inserting here we can do something here so what we can do here so what we can do because at this moment right everything because at this moment right everything everything for this u for this number u everything for this u for this number u here for this node u here has already here for this node u here has already been been inserted all the patterns have been inserted all the patterns have been inserted into the prefix tree inserted into the prefix tree that's why you know from here we can we that's why you know from here we can we can do the query and query for for this u right and we can query for this u for all the queries that has this number has the node equals to this u right so let's say for example we have we have three here let's say we have three two i know there's another query three five there's another one of three six right so at this moment right we can i can answer the query for all three queries because of this three here let's say u is equal to three at this moment right because at this moment like i said everything all the parents of three have had already been added to the prefix tree okay and right and after that we also need to remove it for the u because here you know after answer the queries we're going to also do a dfs right okay i think that's the basic idea here okay i think that's the basic idea here right so right so and yeah i guess then we can start and yeah i guess then we can start coding coding uh i think the implementation is a bit uh i think the implementation is a bit long here so but i will try to make it long here so but i will try to make it short uh so first you know from not for me i always prefer to create a note self okay self okay self dot children okay have children self dot children okay have children equals to this equals to this and i have self dot count right like i and i have self dot count right like i said we need we need a count oh and i think another thing i i forgot oh and i think another thing i i forgot to mention is that you know for the to mention is that you know for the prefix prefix for the bit prefix tree uh how many for the bit prefix tree uh how many digits we want to digits we want to uh we want to check right that's that's uh we want to check right that's that's the number of digits we want to check the number of digits we want to check depending on the biggest number depending on the biggest number in for this problem right because you in for this problem right because you know for example you know know for example you know previously we only have like five five previously we only have like five five digits digits right because you know i'm just using right because you know i'm just using this one as an example but for this one this one as an example but for this one as you as you as you as you as you guys can see we have as you guys can see we have uh 10 to the power of 5 right so which 10 to the power of 5 right so which means that you know means that you know we need prop probably we need 10 to the we need prop probably we need 10 to the power of 18 power of 18 to cover everything right because this to cover everything right because this one one so what's i think this one is three some so what's i think this one is three some something i don't i don't remember something i don't i don't remember the the exact numbers but i think 2 to the the exact numbers but i think 2 to the power the power of 18 can cover uh this big range here of 18 can cover uh this big range here right because obviously we won't have right because obviously we won't have like enough base value to cover like enough base value to cover all the values here right all the values here right and so uh so where shall we start um okay so first one is the root right uh let's try to implement the the prefix tree here uh so for this one we have since we need to do both the insert and the remove so i'm going to use this one as a update so we're going to have number and we have a value here right so basically this number will when when it comes to when it's insert this value will be one right when it's removed this value will be a negative one okay current equals to root right so for i in range of 17 uh because you know like i said since uh because you know like i said since we're we're trying to when we're trying to create trying to when we're trying to create the prefix three we're trying to create the prefix three we're trying to create from the leftmost bits from the leftmost bits bit value right which is this one right bit value right which is this one right that's why when we do the insert that's why when we do the insert we want to do it in the in the reverse we want to do it in the in the reverse way right we want to insert this one way right we want to insert this one into the prefix three first into the prefix three first that's one because only that only then that's one because only that only then we can just uh we can just uh after the root the first the next child after the root the first the next child will be the will be the the left most digits right that's why we the left most digits right that's why we have we do it in a reverse way have we do it in a reverse way okay and like i said since the uh since okay and like i said since the uh since 2 to the power of 18 is enough that's 2 to the power of 18 is enough that's why we why we we use 17 because 17 to 0 we use 17 because 17 to 0 is 18 right so is 18 right so the b divided it's like this so this is the b divided it's like this so this is gonna a little bit manipulation here gonna a little bit manipulation here right we uh do this one this one do here right we uh do this one this one do here n of one that's how we get the the left n of one that's how we get the the left most most not the leftmost the this number of not the leftmost the this number of this bit value of the at this index has this bit value of the at this index has this position this position right and then it's like the standard right and then it's like the standard uh prefix three implementation right uh prefix three implementation right template if this one not in the current template if this one not in the current dot children right we uh dot children right we uh we create this this child node we create this this child node right because the node of itself right right because the node of itself right and then we uh currently goes to and then we uh currently goes to current.children dot bit current.children dot bit right and then in the end don't forget right and then in the end don't forget to increase the count to increase the count by this value right because by this value right because um yeah and then the next one is a query um yeah and then the next one is a query right right grave number so this one similarly as grave number so this one similarly as this one this one oops i i can uh this one i can copy and paste this the structure is the same but this one is different so now okay so we also need the answer here right the answer is going to be 0 here and so this time we need a target right remember the target will be the the reverse value of the original value right which is uh which that's why i do a x or in the end that's that's how we get the target and for this one we do what so if the target is in now this time target is in this and this one and remember since we have a count here and dot target dot count is greater than zero right that's when we will by this by this value okay and then by this by this value okay and then answer equals answer.children.target answer equals answer.children.target right else right else if it it's not right else right else if it it's not there there right uh we can we will not do the right uh we can we will not do the answer answer we'll not increase the answer but here we'll not increase the answer but here we'll basically do the we'll basically do the x square this one right because at this moment if this one does not exist obviously the other side must have must exist right because we have already populated because you know if since there there's because you know if since there there's always like a path to the end right so always like a path to the end right so if this one if this one does not exist then the other side has does not exist then the other side has has to exist has to exist right because there has to be a path right because there has to be a path follow to the end follow to the end to the to the leaf right if this one's to the to the leaf right if this one's not there the other side must not there the other side must exist that's why we can safely uh exist that's why we can safely uh assign the current with the is the assign the current with the is the target actual one okay and again target actual one okay and again so this part you know you know if so this part you know you know if there's no count here there's no count here right so this one is enough but since we right so this one is enough but since we have this have this uh counter here so which means that you uh counter here so which means that you know even though know even though the this path exists but if this node the this path exists but if this node even though this even though this this node might be it might exist but this node might be it might exist but the count could be zero because it could the count could be zero because it could be uh be uh we we we add it but now then later on we we we we add it but now then later on we remove it remove it that's why we have to check both of the that's why we have to check both of the two things here two things here okay and yeah so that's it right and i okay and yeah so that's it right and i mean mean simply we in the end we return the simply we in the end we return the answer answer oh sorry uh this one uh yeah oh sorry uh this one uh yeah so this part is not needed right so this part is not needed right so that's how we query the bit prefix so that's how we query the bit prefix tree okay cool so and so that's the the the prefix tree and the rest is what so let's so let's try to view the graph okay um well actually it's true it's not a graph trace like this so we're going to have trace like this so we're going to have default of the list default of the list right and then we also need to find the root value okay so that's why i need to define the root value it's going to be a minus one okay and then for i dot parent right in enumerate of parents okay uh if the parent is equal to minus one then we know okay so the current this index is the root gonna be what they're gonna be i because later i'm going to do the dfs we need to start from the root that's why i use this one right and since we already have a root here i i need to use a different variable name and then dot parent all right dot append dot parent all right dot append i right so that's how we build it build i right so that's how we build it build a tree a tree and then the next one is what the dfs and then the next one is what the dfs right so let's do dfs here right so let's do dfs here because later on we're going to do a dfs because later on we're going to do a dfs uh going to be dfs uh going to be dfs of the root value right and then we of the root value right and then we return the answer oh we haven't defined return the answer oh we haven't defined the answer yet the answer yet uh the answer is okay it's here uh the answer is okay it's here so we have the answer it's going to be so we have the answer it's going to be the of length of course okay of length of course okay so that's the answer right and then so that's the answer right and then return the answer later on right return the answer later on right okay now the dfs so we have a u here okay now the dfs so we have a u here right right u and v here so first uh every time we u and v here so first uh every time we uh enter the note here we're gonna uh enter the note here we're gonna update right we're gonna insert update right we're gonna insert basically gonna update basically gonna update the u with one right and later on we're the u with one right and later on we're gonna remove it gonna remove it right u minus one right u minus one right that's how we and then let let's right that's how we and then let let's finish the dfs first so we have d finish the dfs first so we have d and then for v in uh and then for v in uh tree of u right we do dfs of v right so that this is the dfs template right pretty straightforward and like i said on top of this one right before doing this now we can answer queries for you right and for you right and okay yeah in order to do that i think we okay yeah in order to do that i think we also need to create like also need to create like a dictionary uh between the note to the a dictionary uh between the note to the queries queries right because if this this this uh this right because if this this this uh this node here could have multiple queries node here could have multiple queries that we can answer right that's why that we can answer right that's why uh let's see um okay let me create uh let's see um okay let me create another dictionary i'll just call it a another dictionary i'll just call it a node node to query it's going to be another dictionary right so for this one index and we have u and value right in enumerate of course q e r i s e r i s so the key for this one obviously obviously is the is a the value itself right and then we need to append two things the first one is the index second one is the value right because we need the original index to update the answer right okay and so let's go back here now we can answer the queries so for index of u right so the answer of this index of u right so the answer of this index equals to the query of the value right and yeah i think that's it right uh okay let's try to run code finger cross okay accept it nice okay cool so this one passed but as you okay cool so this one passed but as you guys can see this one is guys can see this one is it's almost tle you know it's almost tle you know um i don't know um i don't know i think that's how this problem the test i think that's how this problem the test case was was given case was was given and this maybe it's because it's going and this maybe it's because it's going to be harder for python to be harder for python you know i believe if you use c plus you know i believe if you use c plus plus or java you may get a plus or java you may get a faster runtime but for python this is faster runtime but for python this is as i mean the best i can i can do i as i mean the best i can i can do i guess guess almost tle um almost tle um so let's take a look at the time so let's take a look at the time complexity right complexity right so here right so the update and queries so here right so the update and queries so this one is like so this one is like what 18 right as you as you guys can see what 18 right as you as you guys can see right so this one you can think of as an right so this one you can think of as an off one but off one but it's anyway it's an o of 18. and so for the dfs right so for the dfs and for this kind of queries here so how many queries we have we have this so how many queries we have we have this queries here queries here the queries is this one and the uh so the node is let's say n right and this one is m okay so because we have this many queries we when you down answer that's why we have this photo here but anyway but all in all in total so what we have we have m plus n right we have m plus anything we we need to answer and on top of this one we have 18 right because in total the dfs right the dfs because in total the dfs right the dfs in total in total will will traverse endnotes right and will will traverse endnotes right and among among all those kind of introverts traversing all those kind of introverts traversing will answer will answer m queries for those for this for this m queries for those for this for this many nodes that's why in the total we many nodes that's why in the total we have m times have m times n and for each of them we're going to do n and for each of them we're going to do either query or update either query or update and either query query i'll update the and either query query i'll update the time complexes time complexes of 18 that's why this is the total time of 18 that's why this is the total time complexity complexity right uh right uh yeah i think that's it right i i know yeah i think that's it right i i know this one is a long one this one is a long one um i don't know just to recap right so um i don't know just to recap right so first thing first thing is that you know every time we see this is that you know every time we see this bitwise or and a bunch of queries bitwise or and a bunch of queries always try to use the prefix three right always try to use the prefix three right at the beat prefix three at the beat prefix three and then we try to build a bit freak and then we try to build a bit freak street bit street bit uh prefix three uh with the count uh prefix three uh with the count right so because we because we right so because we because we for each queries we want to only we for each queries we want to only we we need to make sure the bit the prefix we need to make sure the bit the prefix tree only can only include tree only can only include the parents node for the current node the parents node for the current node that's why that's why uh we also need a count to also help us uh we also need a count to also help us to identify right if this if this node to identify right if this if this node has a value has a number associated with has a value has a number associated with it or not it or not okay that's why we we have two we have okay that's why we we have two we have update right we either increase or update right we either increase or decrease decrease okay and once we figure out the prefix okay and once we figure out the prefix tree tree the next thing is that you know we need the next thing is that you know we need to use to use the dfs right to to efficiently the dfs right to to efficiently traverse all the nodes while also traverse all the nodes while also a lot while traversing the tree we also a lot while traversing the tree we also want to answer the want to answer the questions the queries for the for the questions the queries for the for the current node current node that's why we have this structure right that's why we have this structure right so first we have dfs so first we have dfs and i for every time we enter a node and i for every time we enter a node so we update we insert into the prefix so we update we insert into the prefix three and then later on we remove it three and then later on we remove it and then in between right we can answer and then in between right we can answer the questions for all the queries for the questions for all the queries for this node this node okay and the rest is just a bunch of oh okay and the rest is just a bunch of oh oh i'll have to answer here return here oh i'll have to answer here return here the right is just a bunch of like uh the right is just a bunch of like uh miscellaneous miscellaneous stuff right to help us do it to finish stuff right to help us do it to finish to accomplish our goal to accomplish our goal right um right um yeah i think that's it for this one and yeah i think that's it for this one and thank you for watching this video guys thank you for watching this video guys and stay tuned and stay tuned see you guys soon bye | 2024-03-25 13:32:13 | 1,938 | LeetCode 1938. Maximum Genetic Difference Query |
|
RnxuoWbs_v8 | you guys it's just everything go in this video I'm going to take a look at 1 6 to video I'm going to take a look at 1 6 to find peak animun a peak annamund is a find peak animun a peak annamund is a name and that is greater than its name and that is greater than its neighbors we're given an input array neighbors we're given an input array noms we're no adjacent numbers are equal noms we're no adjacent numbers are equal so there must be a peak because we are so there must be a peak because we are asked that the minus 1 and the next asked that the minus 1 and the next number will be minus negative infinity so they will be they were only these only case that they were the no peak in iment is that all the numbers are same but we that's not possible so there must be a big array may contain multiple Peaks we can return any of them mm-hmm so one two three one well we could just loop through the elements and the found and check if it is greater than neighbors but we are asked to the solution must be a lot logarithmic logarithmic logarithmic logarithmic complexity well log then it should be something like binary search let's analyze these so the condition of this actually is the key point right suppose if we're doing something like suppose if we're doing something like binary search we choose the middle one binary search we choose the middle one and what week you found well we if we compare the number between its Labour's let's suppose there are two numbers okay the the one one there will be no peak numbers this is minus infinity left one is infinity right so once the number like go up go bigger like to then there must be a pig in a minute right because once you go up you must go down to infinity so once there is an upward slope let go up then there must be a picking them to the right if downward then again yuning's there will be picking them into left right so yeah that's it we can use binary search let's start equals zero okay let's say if start equals to in if okay let's say if start equals to in if noms middle if if equal then we compare noms middle if if equal then we compare the previous one if it is equal then we the previous one if it is equal then we don't know if it's not equal okay and that's that's good now just me plus one can be the next one suppose something like one two three now we pick two in the middle now we have found our slope go bigger so a peak point Kahneman must be to the right one there must be one to the right okay so we start set to an even plus one the other case up to the end so now we go to three and three the others say finally we get to the same element then it must be the P Kinnaman right why because like any fear if these last elements yeah it's big if not that look like there is a four back to okay so go up okay now - three two right now we choose the number is three go down so end will go to 2 right so it will end at what end the star begin it and we start on okay okay start beginning means start is the possibility of the picking image and is the possibility okay if we go up then means the not possible not it's not pick an huh wait a minute doh - so we check huh wait a minute doh - so we check three two against two and three this is three two against two and three this is downward so and okay and they said to - downward so and okay and they said to - so now we got two three okay start is it so now we got two three okay start is it is got four we got it's a three four and is got four we got it's a three four and then three four then three four so start for yeah start tasty adamant so so start for yeah start tasty adamant so we return start yeah we're accepted and we return start yeah we're accepted and the time as we are asked to its long and the time as we are asked to its long and please find a research space constant please find a research space constant okay that's all for this problem hope okay that's all for this problem hope help see you next time bye bye | 2024-03-21 13:47:15 | 162 | LeetCode 162. Find Peak Element | JSer - JavaScript & Algorithm |
|
t1GLDWqWVQk | hey yo what's up my little coders let me show you in this tutorial how to solve show you in this tutorial how to solve the leadpro question number the leadpro question number 1752 check if array is sorted 1752 check if array is sorted and rotated let me just explain an and rotated let me just explain an example example what we need to do basically imagine what we need to do basically imagine that this is our input array that this is our input array if we sort this input array this is what if we sort this input array this is what we will get we will get so one two three four five check offer so one two three four five check offer is sorted but also check if it's rotated is sorted but also check if it's rotated so with the sorted array we also need to so with the sorted array we also need to check check if it has been rotated and when you if it has been rotated and when you rotate you just basically select like rotate you just basically select like a random value x we don't know what it a random value x we don't know what it will be equal but in this will be equal but in this case they explain that x is equal to case they explain that x is equal to three which will mean that you three which will mean that you that you rotate the array by three that you rotate the array by three positions positions so from the sorted array the first value so from the sorted array the first value will be moved to the right by three will be moved to the right by three positions positions so from here we will go one two three so from here we will go one two three after after we rotate the array one should be here we rotate the array one should be here which is correct which is correct then the second value elsa moves by then the second value elsa moves by three positions three positions so one two three then two will be so one two three then two will be somewhere in the end somewhere in the end and yeah two is somewhere in the end and yeah two is somewhere in the end with the middle element with the middle element if you go by three positions we do one if you go by three positions we do one two two okay there's then that's the end of the okay there's then that's the end of the array so we will do like three array so we will do like three and they'll appear here in the beginning and they'll appear here in the beginning of the array and four will go away so of the array and four will go away so this value which is correct this value which is correct five will go to this value which is also five will go to this value which is also correct so this array correct so this array has been sorted and rotated by three has been sorted and rotated by three positions positions and if the array has been sorted and and if the array has been sorted and rotated we just return true rotated we just return true if it hasn't been sorted and rotated in if it hasn't been sorted and rotated in this case we need to return false this case we need to return false this is basically what we need to do this is basically what we need to do guys how can we solve this problem guys how can we solve this problem efficiently without actually efficiently without actually sorting the array and trying to rotate sorting the array and trying to rotate by by the possible amount of uh positions the possible amount of uh positions let's think about some patterns okay let's think about some patterns okay imagine if x is equal to zero imagine if x is equal to zero it's like the base case let's say in it's like the base case let's say in this case if x is equal to zero it means this case if x is equal to zero it means that we that we basically don't rotate the array because basically don't rotate the array because we rotated by zero positions we rotated by zero positions which like will mean that we need to which like will mean that we need to check if this array check if this array if the original array is just sorted if if the original array is just sorted if it doesn't rotate it we just check only it doesn't rotate it we just check only if it's sorted or not if it's sorted or not but if x is not equal to zero but it's but if x is not equal to zero but it's equal to equal to like a positive number which is greater like a positive number which is greater than zero than zero what it would mean for us then it will what it would mean for us then it will mean that like if the array mean that like if the array is indeed has been sorted and rotated it is indeed has been sorted and rotated it will mean that like somewhere will mean that like somewhere you have like two small arrays you have like two small arrays which are both sorted and elsa which are both sorted and elsa the last value from the second array the last value from the second array is not greater than the first value is not greater than the first value in the array this is basically the in the array this is basically the pattern pattern and this is the conditions for which we and this is the conditions for which we need to check need to check in order to identify if the array has in order to identify if the array has been sorted and rotated been sorted and rotated in case if x is not equal to zero in case if x is not equal to zero okay let's just code it guys okay guys so we create the integer to basically increment our counter and keep track of in how many places the values are not sorted if the counter will be greater than one at any point we just returned false straight away because it will mean that this array is not sorted and rotated at the same time but if you just find one place where the current element is basically greater than the next element in this case we'll increment the counter but if you will not if you will not find any other places where this condition applies in this case you incremented only one and only once and will not return false here in this case we'll iterate through the four array and we just will return true in the end but there is one very hacky thing here so we just we don't just check for the next element but we also do like i plus one and then mod the the by the length of the array and what does this mod actually do okay let me explain you guys so if you start with the first value at index zero we do i zero plus plus one which is equal to one so we do one mod five because numbers of lengths is equal to five because there are five elements and if you do uh one mode five you basically get one then if you will go to the next element so i will be equal to one i plus one plus i is equal to two if you do two mode five you also will get uh two if you if you do like three mod five we get three if you do four mode five we get four but guys if you do five mode five if you get zero and what does it mean it means that like when it will iterate and will be at the last element and in this case i will be equal to four and if you do four plus one it will be five and we do five mod mod five you will get zero which will mean that like we will check the element at index zero so we compare this element with this element and in this case basically we will iterate through the four array and we'll check if there are two sorted sub arrays and the last value in the sorted sub array is not greater than the first value in the array and yeah it's basically equivalent of checking if the array has been sorted and rotated at the same time and if at any moment this condition will apply twice we just will return false otherwise return true this is basically all what we need to do so if i run the code now if i submit i get hundred percent simply if i submit i get hundred percent simply as that guys as that guys i hope it was it was clear and you i hope it was it was clear and you understood everything please guys make understood everything please guys make sure you subscribe to my channel sure you subscribe to my channel to not miss a lot of videos which are to not miss a lot of videos which are going to come soon going to come soon and guys challenge your friends to see and guys challenge your friends to see if they can solve this question or not if they can solve this question or not then leave in the comments section the then leave in the comments section the comment like saying which little comment like saying which little question you want me to solve next question you want me to solve next and i will see you next video guys good and i will see you next video guys good luck | 2024-03-22 11:57:08 | 1,752 | Leetcode 1752. Check if Array Is Sorted and Rotated [Java] |
|
lTPqWStKEyI | [Music] [Applause] [Applause] hello and welcome today we're doing a hello and welcome today we're doing a question from week code called angle question from week code called angle between hands of a clock it's a medium between hands of a clock it's a medium let's get started let's get started given two numbers our minutes returned given two numbers our minutes returned the smaller angle in degrees formed the smaller angle in degrees formed between the hour and the minute hand between the hour and the minute hand example given our 12 minutes 30 we example given our 12 minutes 30 we output 165 and here there could be two output 165 and here there could be two possible angles one between the minute possible angles one between the minute hand and the hour hand or since we know hand and the hour hand or since we know that there are 360 degrees in a circle that there are 360 degrees in a circle 360 degrees minus that so if this is X 360 degrees minus that so if this is X this angle between these two hands we this angle between these two hands we could also output 360 minus X whichever could also output 360 minus X whichever one is the smaller of those two example one is the smaller of those two example 2 given 330 we output 75 degrees example 2 given 330 we output 75 degrees example 3 315 we output 7.5 degrees so we can 3 315 we output 7.5 degrees so we can also output decimals given 451 55 also output decimals given 451 55 degrees and given 12 o'clock we output 0 degrees and given 12 o'clock we output 0 because both the hour hand and the because both the hour hand and the minute hand are at position 12 and minute hand are at position 12 and constraints I'm kind of blocking this constraints I'm kind of blocking this but our minutes are always between 0 and but our minutes are always between 0 and 59 and hours are between 0 and 12 so 59 and hours are between 0 and 12 so this is essentially just a this is essentially just a straightforward math problem we want to straightforward math problem we want to return the smaller angle in degrees return the smaller angle in degrees between the hour and the minute hand all between the hour and the minute hand all we have to do is change the hour and we have to do is change the hour and minute hand into degrees to subtract and minute hand into degrees to subtract and return the smaller angle and that would return the smaller angle and that would be our output so for minutes we have be our output so for minutes we have minute degrees equaling well how many minute degrees equaling well how many minutes are in a full circle there are minutes are in a full circle there are 60 so minutes divided by 60 and 60 so minutes divided by 60 and multiplying that by 360 to get degrees multiplying that by 360 to get degrees for the minute hand and we're dividing for the minute hand and we're dividing by 60 only to multiply again by 360 we by 60 only to multiply again by 360 we can easily just do times 6.0 and I'm can easily just do times 6.0 and I'm doing point o because we saw that we doing point o because we saw that we could output a decimal so keeping could output a decimal so keeping everything everything to float for a quick sanity check if to float for a quick sanity check if there are zero minutes 0 times 6 is zero there are zero minutes 0 times 6 is zero degrees if there are 30 minutes 30 times degrees if there are 30 minutes 30 times 6 is 180 we have our 180 degrees so 6 is 180 we have our 180 degrees so we're going over here and same thing for we're going over here and same thing for our our degree how many hours are in a our our degree how many hours are in a full circle that is 12 so power divided full circle that is 12 so power divided by 12 and multiplying that by 360 to get by 12 and multiplying that by 360 to get our degrees but there is something we our degrees but there is something we need to also keep track of the hour need to also keep track of the hour isn't sufficient because if the hour is isn't sufficient because if the hour is 12 it's pointing right here we want zero 12 it's pointing right here we want zero degrees right but if it is 12:30 our our degrees right but if it is 12:30 our our hand is actually moved and according to hand is actually moved and according to how many minutes there are so we need to how many minutes there are so we need to somehow combine the minutes and the somehow combine the minutes and the hours and then convert that into degrees hours and then convert that into degrees so what I'm going to do is first convert so what I'm going to do is first convert few minutes into hours and all the hours few minutes into hours and all the hours into degrees how many minutes are an into degrees how many minutes are an hour 60 so minutes divided by 60 this hour 60 so minutes divided by 60 this entire thing is then going to be divided entire thing is then going to be divided by 12 and then multiplied by 360 to get by 12 and then multiplied by 360 to get our degrees but there is still one more our degrees but there is still one more thing that we want to keep track of we thing that we want to keep track of we reset every time we hit this zero mark reset every time we hit this zero mark if we get 360 we want to reset to zero if we get 360 we want to reset to zero degrees again so with the hours we also degrees again so with the hours we also want to do mod 360 because as you can want to do mod 360 because as you can see here if we are at 12 o'clock we want see here if we are at 12 o'clock we want to be zero degrees not 360 right so even to be zero degrees not 360 right so even at 12:30 we have our 12 minutes 30 so at 12:30 we have our 12 minutes 30 so this is 12.5 divided by 12 a little bit this is 12.5 divided by 12 a little bit over 1 times 360 we are over 360 but we over 1 times 360 we are over 360 but we want to reset each time we hit 360 which want to reset each time we hit 360 which is why we do mod 360 and now all we have is why we do mod 360 and now all we have to do is return the minimum between our to do is return the minimum between our angles so return the absolute value of angles so return the absolute value of mini degree minus our degree and mini degree minus our degree and absolute value because the our degree absolute value because the our degree could be ahead of the men we could be ahead of the men we really No so this value or 360 minus really No so this value or 360 minus that value right here so you can also that value right here so you can also wrap these into another parentheses run wrap these into another parentheses run code accepted let's submit and it is code accepted let's submit and it is accepted as well and time complexity accepted as well and time complexity this is just a constant operation math this is just a constant operation math this is of one constant time same with this is of one constant time same with space we just have constant variables so space we just have constant variables so this is a one time and of one constant this is a one time and of one constant space if you have any questions let me space if you have any questions let me know it down below know it down below otherwise I'll see you next time otherwise I'll see you next time [Music] | 2024-03-21 00:17:02 | 1,344 | Angle Between Hands of a Clock - LeetCode 1344 Python |
|
lq45d7jexs8 | friends welcome to code Sutra in this video we'll be discussing about lead video we'll be discussing about lead code problem number 1675 minimize the code problem number 1675 minimize the deviation in an array in this problem we deviation in an array in this problem we are given an array for example this are given an array for example this particular array and what is deviation particular array and what is deviation it is the difference between the maximum it is the difference between the maximum element and the minimum element what is element and the minimum element what is the deviation now the deviation is 19 the deviation now the deviation is 19 but we have to reduce this deviation how but we have to reduce this deviation how can we reduce this deviation we can can we reduce this deviation we can perform two operations one is you can perform two operations one is you can pick up any odd element and you can pick up any odd element and you can increase the odd element that is increase the odd element that is multiplying it by two for example this multiplying it by two for example this one can be multiplied by 2 and this can one can be multiplied by 2 and this can be converted to 2. again you can pick up be converted to 2. again you can pick up this 3 and you can multiply it by two this 3 and you can multiply it by two that is one approach the second one is that is one approach the second one is you can pick up any you can pick up any even element and divide it by two for even element and divide it by two for example 20 becomes 10 and again since it example 20 becomes 10 and again since it is an even again you can perform the is an even again you can perform the operation so let us dive into the operation so let us dive into the intuition of the problem and the intuition of the problem and the approach approach what's the intuition the intuition is what's the intuition the intuition is say here it was one right now we say here it was one right now we increase the two so can this 2 be increase the two so can this 2 be increased further no right why it can't increased further no right why it can't be increased because any odd number once be increased because any odd number once it is multiplied by an even number it is multiplied by an even number it will become an even number and you no it will become an even number and you no longer can increase for example if this longer can increase for example if this is the given array can you increase this is the given array can you increase this any element of this given array no right any element of this given array no right why because all the elements in this why because all the elements in this array are even for example if we array are even for example if we multiply the odd elements of this array multiply the odd elements of this array by 2 by 2 . now can you increase any element in . now can you increase any element in the array no right so this will be our the array no right so this will be our maximum possible value of any element in maximum possible value of any element in the array so now none of the elements in the array so now none of the elements in this particular array can have a value this particular array can have a value greater than this so we have solved off greater than this so we have solved off of the problem that is any value we now of the problem that is any value we now know the maximum value of that what is know the maximum value of that what is the second step we have to do the second the second step we have to do the second step we have to do is to reduce the step we have to do is to reduce the maximum value right so the idea is to maximum value right so the idea is to minimize the gap between the maximum and minimize the gap between the maximum and the minimum value now we have increased the minimum value now we have increased the minimum values now the other option the minimum values now the other option is we have to reduce the maximum value is we have to reduce the maximum value so how do we do that we pick up the so how do we do that we pick up the maximum element in an array maximum element in an array and we divide it by 2. again what is the and we divide it by 2. again what is the maximum element of this array again it maximum element of this array again it is 10 and we will divide it by 2. now is 10 and we will divide it by 2. now can we go can we go any further no right because this is an any further no right because this is an odd number and we cannot divide it odd number and we cannot divide it further by 2. see here we do have an further by 2. see here we do have an even number we don't want to care about even number we don't want to care about that why because our maximum element that why because our maximum element cannot be divided by two so what is the cannot be divided by two so what is the answer in this case the answer is 2. so answer in this case the answer is 2. so can we just follow this procedure and can we just follow this procedure and return the answer that is we will do all return the answer that is we will do all the steps then finally we will return the steps then finally we will return the difference between the maximum the difference between the maximum element and the minimum element can we element and the minimum element can we do that no right why we can't do that I do that no right why we can't do that I will show you with an example for will show you with an example for example this is 3 and this is 5 we have example this is 3 and this is 5 we have multiplied both of them by 2 that is we multiplied both of them by 2 that is we got 6 and we got 10. now let's go on to got 6 and we got 10. now let's go on to do it what is 10 by 2 10 by 2 will be 5 do it what is 10 by 2 10 by 2 will be 5 again what is 6 by 2 6 by 2 is 3. again what is 6 by 2 6 by 2 is 3. finally what is the answer the answer is finally what is the answer the answer is 2 but let's go on very carefully we had 2 but let's go on very carefully we had 6 and 10 and 10 actually become 5. now 6 and 10 and 10 actually become 5. now observe very carefully it is 6 and 5 and observe very carefully it is 6 and 5 and what is the answer now the answer is 1 what is the answer now the answer is 1 why because this is the minimum possible why because this is the minimum possible value that we can get right so the idea value that we can get right so the idea is that every step that we are dividing is that every step that we are dividing the number by 2 we also have to keep the number by 2 we also have to keep track of the answer keep track of the track of the answer keep track of the answer for example 1 in this case what answer for example 1 in this case what do we do we keep track of the answer do we do we keep track of the answer initially it was 4 now that we have 1 initially it was 4 now that we have 1 which is actually lesser than 4 will be which is actually lesser than 4 will be updating our answer so that is the updating our answer so that is the additional step that we'll be doing and additional step that we'll be doing and one more thing see at every point we are one more thing see at every point we are finding the maximum value and we are finding the maximum value and we are divided git by two so what is the data divided git by two so what is the data structure that we'll be using here the structure that we'll be using here the data structure that we have to use is a data structure that we have to use is a maximum Heap or a priority Cube why maximum Heap or a priority Cube why because it's very easy or it just takes because it's very easy or it just takes constant time or one to get the maximum constant time or one to get the maximum element from in heat so that is what we element from in heat so that is what we will be doing we will be using a Max will be doing we will be using a Max Heap to accompany this Heap to accompany this okay now let's discuss this step by step okay now let's discuss this step by step approach the first step is we will add approach the first step is we will add all the elements in the priority queue all the elements in the priority queue but before adding that remember we have but before adding that remember we have to convert all the elements into its to convert all the elements into its maximum possible value that is if it is maximum possible value that is if it is an even number we can add it directly or an even number we can add it directly or else we will multiply it by 2 and then else we will multiply it by 2 and then we will add it we will add it also we have to keep track of the also we have to keep track of the minimum elements while adding because minimum elements while adding because this is a maxi we cannot go and directly this is a maxi we cannot go and directly get the minimum value so we need to keep get the minimum value so we need to keep track of the minimum value ourselves track of the minimum value ourselves what is the third step that we'll be what is the third step that we'll be doing while the maximum element is even doing while the maximum element is even we will divide it by two that is what we we will divide it by two that is what we were doing here right while the maximum were doing here right while the maximum element is divided by 2 divisible by 2 element is divided by 2 divisible by 2 we were dividing it by 2 but don't we were dividing it by 2 but don't forget you have to again add it back to forget you have to again add it back to the priority queue that is what we are the priority queue that is what we are doing but with addition to that we also doing but with addition to that we also keep track of the difference between the keep track of the difference between the now maximum element and the minimum now maximum element and the minimum element at every point and also we have element at every point and also we have to update the minimum value at every to update the minimum value at every Point finally we will return the answer Point finally we will return the answer so let me take you through the code so so let me take you through the code so before taking you through the code before taking you through the code please do subscribe to our channel uh we please do subscribe to our channel uh we do here discuss the patterns and not do here discuss the patterns and not just the problems for example if you just the problems for example if you have carefully listened to this problem have carefully listened to this problem and if you are aware of the maximum and and if you are aware of the maximum and mean Heap these are the problems you can mean Heap these are the problems you can go and solve it straight away actually go and solve it straight away actually these are actually two of them are hard these are actually two of them are hard level problems and two of them are level problems and two of them are medium level problems but you have medium level problems but you have understood the concept of minimum and understood the concept of minimum and Maxi you can directly go this and solve Maxi you can directly go this and solve this problem what is the concept the this problem what is the concept the concept is very simple at every point we concept is very simple at every point we want to find the maximum value or at want to find the maximum value or at every Point what we are trying to do is every Point what we are trying to do is sort the array sort the array right so if you know this particular right so if you know this particular pattern it is very easy to solve these pattern it is very easy to solve these four problems four problems let me dive into the code what we are let me dive into the code what we are doing is we are doing is we are initializing a priority queue why initializing a priority queue why collections.reverse ordered because this collections.reverse ordered because this is a Max Heap okay maximum priority is a Max Heap okay maximum priority queue that will give you the maximum queue that will give you the maximum element now we are adding all the element now we are adding all the elements into the priority queue one by elements into the priority queue one by one that is if it's an odd number we'll one that is if it's an odd number we'll multiply by 2 and we will add it and we multiply by 2 and we will add it and we are keeping track of the minimum element are keeping track of the minimum element at every point at every point then once you are done with this what we then once you are done with this what we do we get we just Peak them in maximum do we get we just Peak them in maximum element and we see if it is divisible by element and we see if it is divisible by two or not for example here this became two or not for example here this became five right we no longer can divide it five right we no longer can divide it any further this also became Phi so we any further this also became Phi so we no longer can go below this so that is no longer can go below this so that is what we are trying to do until and what we are trying to do until and unless the maximum element is divisible unless the maximum element is divisible by 2 we are going through the while loop by 2 we are going through the while loop and we are pulling it and we are again and we are pulling it and we are again adding Top by two back to the priority adding Top by two back to the priority queue but we also keep track of the queue but we also keep track of the answer and the minimum possible values answer and the minimum possible values finally we'll be returning the answer finally we'll be returning the answer thank you for watching the video please thank you for watching the video please do like share and subscribe | 2024-03-20 10:56:24 | 1,675 | LeetCode 1675 Minimize Deviation in Array |
|
HfFC3S_7y10 | hey guys welcome back to our channel so this channel every data science is all this channel every data science is all about trying to learn the different about trying to learn the different concepts involved in designs by concepts involved in designs by practicing a lot of questions in this practicing a lot of questions in this video i am going to solve this question video i am going to solve this question on lead code regarding the number of on lead code regarding the number of employees which which report to each employees which which report to each employee and try to walk you through how employee and try to walk you through how we can develop solutions to such we can develop solutions to such problems the difficulty level of this problems the difficulty level of this question is easy okay let's jump right question is easy okay let's jump right in we are given a table called employees in we are given a table called employees with four different columns employee id with four different columns employee id name reports to an age employee id being name reports to an age employee id being the primary key for this table this the primary key for this table this table contains information about the table contains information about the employees and the idea of the manager employees and the idea of the manager they report to some employees do not they report to some employees do not report to anyone and therefore reports report to anyone and therefore reports to is none okay to is none okay for this problem problem we will for this problem problem we will consider a manager an employee who has consider a manager an employee who has at least one other employee reporting to at least one other employee reporting to them okay them okay we are asked to write a sql query to we are asked to write a sql query to report the ids and the names of all report the ids and the names of all managers and what is a manager an managers and what is a manager an employee who has at least one other employee who has at least one other employee reporting to them the number of employee reporting to them the number of employees who report directly to them employees who report directly to them and the average age of the reports and the average age of the reports rounded to the nearest integer the rounded to the nearest integer the result should be ordered by employee id result should be ordered by employee id okay let's go to this example right so okay let's go to this example right so here if you see uh these are the here if you see uh these are the different employees and where they different employees and where they report to right so for example report to right so for example uh hershey do not report to anyone alice uh hershey do not report to anyone alice and bob report to hersey and winston and bob report to hersey and winston also do do not report to anyone now the also do do not report to anyone now the definition of a manager is definition of a manager is at least one person should report to at least one person should report to them right so for example alice and bob them right so for example alice and bob they report to hersey right so hersey is they report to hersey right so hersey is a manager a manager winston does not report to anyone but winston does not report to anyone but is it necessarily that winston is also a is it necessarily that winston is also a manager no because in this employees manager no because in this employees table you don't have any employee who table you don't have any employee who who reports directly to winston so the who reports directly to winston so the only person who is a manager in this only person who is a manager in this case is employee id 9 hersey and who how case is employee id 9 hersey and who how many people report directly to them too many people report directly to them too right alice and bob and what is the right alice and bob and what is the average age so 41 plus 36 divided by 2 average age so 41 plus 36 divided by 2 it is 39 right so that is going to be it is 39 right so that is going to be the output right okay so the first thing the output right okay so the first thing that we should do is from this employees that we should do is from this employees table we should find out all the table we should find out all the managers right so managers basically is managers right so managers basically is manager ids right so the so nine is a manager ids right so the so nine is a manager id right based on our discussion manager id right based on our discussion and then based on that we can also find and then based on that we can also find the number of employees who report to the number of employees who report to that manager and the average age right that manager and the average age right and we can store that in a common table and we can store that in a common table expression so let me just write start expression so let me just write start developing this this query it will be developing this this query it will be more clear so from more clear so from this employees table right where this employees table right where reports to reports to is is not not null right where reports to is not null null right where reports to is not null what we are doing is let's group by what we are doing is let's group by the reports to the reports to column right so reports to so for column right so reports to so for example nine nine will be one group example nine nine will be one group right so and this nine how if we count right so and this nine how if we count the employer ids so basically there are the employer ids so basically there are going to be two employees who are going to be two employees who are reporting directly to that reporting directly to that report id right nine so that is what we report id right nine so that is what we are trying to do so are trying to do so here we are grouping by reports two then here we are grouping by reports two then if we return if we return the report the report to to right right then count then count the the employee id right and since uh it is all employee id right and since uh it is all already a primary key so we don't need already a primary key so we don't need to write distinct because to write distinct because primary key means no null unique values primary key means no null unique values right so count employee id and this is right so count employee id and this is going to be basically going to be basically number of reports right so reports number of reports right so reports count we can aliase this with anything count we can aliase this with anything like it does not matter and then we also like it does not matter and then we also need the average age but rounded to the need the average age but rounded to the nearest integer right so how do we nearest integer right so how do we calculate the first lead average of age calculate the first lead average of age right and this should be rounded to right and this should be rounded to the nearest integer so round this entire the nearest integer so round this entire thing and if you just write comma 0 this thing and if you just write comma 0 this will round it to the nearest integer so will round it to the nearest integer so basically the basically the two zero decimal places and this should two zero decimal places and this should be the average age right the average age be the average age right the average age okay okay let me just run this to see okay okay let me just run this to see like what we are trying to do here are like what we are trying to do here are we getting that or not obviously this is we getting that or not obviously this is not complete so it will be a wrong not complete so it will be a wrong answer but let's see what we are getting answer but let's see what we are getting right so for example here you have right so for example here you have reports too so write reports to id this reports too so write reports to id this is nine and how many people are is nine and how many people are reporting two and the average is 39 so reporting two and the average is 39 so if you see you have the if you see you have the this this and this part right so all you this this and this part right so all you need is the name part right so need is the name part right so all we can do is just all we can do is just store this in a common table expression store this in a common table expression so with ct as this entire thing goes so with ct as this entire thing goes into parenthesis and then from this into parenthesis and then from this common table expression let's aliase common table expression let's aliase this as c this as c let's left join let's left join again on the employees table a list as e again on the employees table a list as e on c dot reports on c dot reports to to is equal to e dot employee is equal to e dot employee id because these are the employee ids id because these are the employee ids only right so that is why this equal only right so that is why this equal equivalency is correct so reports 2 is equivalency is correct so reports 2 is equal to e dot employee id and then once equal to e dot employee id and then once you are joining you are only required to you are joining you are only required to keep certain columns not all of them keep certain columns not all of them right so for example we need employee id right so for example we need employee id right so we can write c dot reports right so we can write c dot reports to to and a list this as employee and a list this as employee id then we need the name name is going id then we need the name name is going to be in the employees table so right we to be in the employees table so right we can write e dot name then we need the can write e dot name then we need the reports count and average age right so reports count and average age right so reports count averages in this common reports count averages in this common table expression so we write c dot table expression so we write c dot reports reports count and then c dot average count and then c dot average h okay one thing that is left to do is h okay one thing that is left to do is we need to order this by employee id we need to order this by employee id right so order right so order by by employee employee id id okay so this looks good let me go ahead okay so this looks good let me go ahead and run this to see what happens and run this to see what happens okay so this is accepted our output is okay so this is accepted our output is same as expected output let me go ahead same as expected output let me go ahead and submit it to see if it passes all and submit it to see if it passes all the test cases so this passes all the the test cases so this passes all the test cases and this is how i do it again test cases and this is how i do it again very simple question all we had to do very simple question all we had to do was you know firstly find out the was you know firstly find out the definition of the manager rights and the definition of the manager rights and the definition of manager is here that at definition of manager is here that at least one employee should be reporting least one employee should be reporting directly to them so we found out the directly to them so we found out the managers the average number of average managers the average number of average age of the direct reports the number of age of the direct reports the number of direct reports right and then we since direct reports right and then we since in the output we also need the name in the output we also need the name right so that is why we are joining is right so that is why we are joining is back to the employees table so that we back to the employees table so that we can get the name as well and that is how can get the name as well and that is how we do it let me know if there is a we do it let me know if there is a better way or a more efficient way you better way or a more efficient way you can think of can think of to solve this push question let the to solve this push question let the solution be in this comment section solution be in this comment section below and until then i will see you guys below and until then i will see you guys in the next video | 2024-03-20 17:45:11 | 1,731 | LeetCode 1731 "Employees Which Report to Each Employee" Interview SQL Question with Explanation |
|
P0Fz-ZIVY5k | management coding on the site So today we have to do number of balance sub address this question 21 What to do then name will get a chance There will be some elements in it Reverse proposal 132 So what to do in one question Basically all the sub If there If there If there were four such tights in the morning, then the first were four such tights in the morning, then the first bandh should not be bigger than any of the elements coming next. bandh should not be bigger than any of the elements coming next. Okay, this should Okay, this should not be bigger than any of the elements and for not be bigger than any of the elements and for example if I share all the addresses in the morning example if I share all the addresses in the morning 138 138 hands free. hands free. hands free. will be all over the world, okay, if we look at this survey, the first one is closed, if the rest is not bigger than any number, then this is also correct, okay, two guys got the cut, It is It is It is not bigger than any number coming next. not bigger than any number coming next. Okay, so this is also viral. The only guy Okay, so this is also viral. The only guy next is the invalid. If you look at Vishal Savere, then take this next is the invalid. If you look at Vishal Savere, then take this first element. first element. One of the remaining elements is Monkey Two and if it is bigger than that, then One of the remaining elements is Monkey Two and if it is bigger than that, then this is wrong. this is wrong. this is wrong. one guy would be velvet 12345 so there were five velvet savers in this okay if you don't in that 1425 three if you had if you don't in that 1425 three if you had got this then all the got this then all the episodes starting one time one this is velvet episodes starting one time one this is velvet episodes starting one time one this is velvet 1142 also one 114 125 and 1425 three plate diet all this white time lived that first Vrindavan Remaining was not smaller than anyone till was not bigger than anyone that is okay if that again that The first number has come, the coming ones The first number has come, the coming ones The first number has come, the coming ones should come next, Ankita, giving even, it has should come next, Ankita, giving even, it has become bigger than this, it means it is not in balance, become bigger than this, it means it is not in balance, it has gone wrong, okay, let's write further, now it is about to change, so 425, this value Jhala was Jhala was Jhala was not bigger than this but it was two sevada, this is also wrong not bigger than this but it was two sevada, this is also wrong and it is also wrong for 253. Okay, if we and it is also wrong for 253. Okay, if we look at the one starting with two, then two look at the one starting with two, then two is correct. is correct. This cigarette is 125, you are Pavitri Devi carat, This cigarette is 125, you are Pavitri Devi carat, so it is not bigger than any of these. so it is not bigger than any of these. so it is not bigger than any of these. at the end five 183 EFA which is it became bigger than the next one number this is wrong free this absolutely that in this whole 123456789 10 11 11 11 which is actually another one and if here because of these two So if we go back this much time, So if we go back this much time, So if we go back this much time, it is closed on 221, it is it is closed on 221, it is not bigger than any of the elements coming next, okay here not bigger than any of the elements coming next, okay here Lebanon or without Lebanon or without value and equal to like this, value and equal to like this, then the right thing is okay, in the first comparison, it is then the right thing is okay, in the first comparison, it is bigger here. bigger here. bigger here. should not be boiled like you will succeed, you will fail, you will go wrong, okay, so the question was, now call this, you can check it as soon as you get the ad, how can you install it, This was This was This was done last morning, it done last morning, it is okay to take out the first person, the quota should be equal to all the others or it should be is okay to take out the first person, the quota should be equal to all the others or it should be equal to this one, let's do two, equal to this one, let's do two, how far can it extend, how far can it extend, how two or the only person, after the correct sa two, how two or the only person, after the correct sa two, an elder son is tight here. an elder son is tight here. an elder son is tight here. because if it is increased to 1 liter later, then after 242, you can see here that there is a number about you which is great, subscribe to it and 876, if So So So how far will we actually be valid, how far will we actually be valid, I have 420 value or from that onwards I have 420 value or from that onwards if I if I subscribe here for this digit, then you subscribe here for this digit, then you can subscribe, it can become ghee, so can subscribe, it can become ghee, so see this here and after that. see this here and after that. see this here and after that. how to process, its small can be made and here is one ok lattu can only be made, ok ok, how many digits can be made, how long can it wait, its small is here, there is no editing smuggler, so One can also own and one-day and One can also own and one-day and One can also own and one-day and test and then test and then share to A so let's see this decision. If share to A so let's see this decision. If I talk about becoming 4K smart about how to work, I talk about becoming 4K smart about how to work, then here is the free white white then here is the free white white ship kitne bane valid hai work but when will ship kitne bane valid hai work but when will These two together are coming to 251 and 205. Out of These two together are coming to 251 and 205. Out of these Force for Banna, none is these Force for Banna, none is valid, we will pour one, valid, we will pour one, see here, I can stop my work here, I have to see here, I can stop my work here, I have to do my daily point hr hr element, do my daily point hr hr element, all of them can subscribe. all of them can subscribe. all of them can subscribe. me, then subscribe to all the upcoming ones later so the same message has come, the pipe will also so the same message has come, the pipe will also melt after drinking, free mode is closed, there melt after drinking, free mode is closed, there is no one here, okay, so three sticks straight, is no one here, okay, so three sticks straight, this will go till the end and further. this will go till the end and further. this will go till the end and further. take that one you try to do with pipes pipes and this is the alliance 59 This is correct scholar form 595 This is also correct I got it in the condition that the first stop tax value should not be that I someone now take this right and here So now this is 20 minutes next on okay let's see once how we can do this through induction that if I have come out of all here zero one two three four five six seven 8 That friend, there That friend, there That friend, there was a smallr on Riya, okay, so you here the was a smallr on Riya, okay, so you here the index reel of saliva jarad scholar value - index reel of saliva jarad scholar value - 02, so three is basically telling you something completely 02, so three is basically telling you something completely or you can go till November three and or you can go till November three and how to write pottu oil and 425 tight one more. how to write pottu oil and 425 tight one more. Write on 548 but these Write on 548 but these three temples are being built here, its current three temples are being built here, its current affairs and rally rally are fine - don't do this also affairs and rally rally are fine - don't do this also and you and you can subscribe using 'Pitra Lag Rahein' and complete it. can subscribe using 'Pitra Lag Rahein' and complete it. Well, if it is not there, then there is no meaning. Well, if it is not there, then there is no meaning. Well, if it is not there, then there is no meaning. limit is not tight for this if I 1111 - 21806 see 1234567 and if there is 1111 - 21806 see 1234567 and if there is no element I can fix the length no element I can fix the length subscribe subscribe element will be found for the element but here element will be found for the element but here element will be found for the element but here Pem Log Light So what can we do here like we have done before Next Greater Element on Bright Okay so this time we are going to use pretty much the same programs, if you haven't seen then you will get it in the gender description now. Okay, so let's take the stress crispy, what do we have to do, so by the way, if you want to find this modal element, then you can use the extract on the directions, travel in this dress and travel with this, you can extract it from both, okay What are we going to look like? We will cover it the way we did the Next Greater Element online right hand. We will travel in this year and we will remove those brothers who do not require us to check. Okay, complete What is going to happen is basically a What is going to happen is basically a What is going to happen is basically a strike, we are ok, first of all I am going to work for the last Sawan, 600, there was no smaller element here, pride, so ay in flight was considered after this, We will keep We will keep We will keep this quarter inch and the value here - it is not my government to keep the soil value, okay, I have just kept it here for viewing, not my government to keep the soil value, okay, I have just kept it here for viewing, okay, so its small size Banda okay, so its small size Banda Dahi 11 Index Pratha - Infinity, so Dahi 11 Index Pratha - Infinity, so write its minimum index here. write its minimum index here. write its minimum index here. then this guy is the one who is the 10th paintings screw okay okay who is the next monkey who comes next guy is no we are traveling through this okay 6 will check this basically check who is this 600 value in the track To your tank index indirectly or directly say so this guy go and check this is this he saw that the size is he is not bigger than me then there is no smaller than there now I want this volume un tight this From here From here From here this guy was fired and now now there is no one in his small early stages means there is no requirement to do any chatting ok if there was no question then we will withdraw the cash eleventh no question then we will withdraw the cash eleventh index got Lavanda 1615 Ismail index got Lavanda 1615 Ismail index got Lavanda 1615 Ismail this is non-inducting and has value, so we will keep it here, okay, the next round has come, what else will we do and basically it is lying in the track, we will check the next to-do list, okay, that one is not there, that too has been chopped, Jhaal Did it and then now there is no one in the style Did it and then now there is no one in the style Did it and then now there is no one in the style means there was no one with space means there was no one with space then we will consider these flight ones then we will consider these flight ones 1190 it is smaller and it itself is affected by 8 and 1190 it is smaller and it itself is affected by 8 and research and value now basically research and value now basically look there is no report of doing these two settings look there is no report of doing these two settings If you see a guy If you see a guy like this going into this dress where he is like this going into this dress where he is looking for the smaller element then if the hole looking for the smaller element then if the hole is smaller then for 6 if the pixels are smaller than that is smaller then for 6 if the pixels are smaller than that then the for resolution will be smaller right to then the for resolution will be smaller right to calculate it from these days calculate it from these days This requirement will not be required, basically we had This requirement will not be required, basically we had seen this logic chair on natural treatment, so seen this logic chair on natural treatment, so let's see and also got the description of let's see and also got the description of insight, drink water, insight, drink water, it will cook, 8 injections will be visible on strike, it will cook, 8 injections will be visible on strike, fiber is also going and chatting with it, fiber is also going and chatting with it, he is the one after me. he is the one after me. he is the one after me. then it will not become 80. This is cancer and put it on some tracks. Let's put the seventh in the next value. Let's click on five algorithms I was the only person who came. He saw that there I was the only person who came. He saw that there is one behind the strike. is one behind the strike. is one behind the strike. is here Hans 72 died of cancer and he blew himself up from this or from this or write again that we take the work from here, see what to do, first saw it on this track Six index is lying there and if there is no value then big value police checked this article there is no postmortem if it is not known then redwrap it and remove it from here tight basically what were we doing now Okay, the Okay, the Okay, the value of pick value of pick was one more than your current current value, so we referred that guy, was one more than your current current value, so we referred that guy, here five current one, so you and here five current one, so you and strike pick nine were placed it and strike pick nine were placed it and not, stopped the next guy 1705 not, stopped the next guy 1705 is also not difficult. is also not difficult. is also not difficult. I have typed Greater, so what have you done? Okay, the previous one has become Virat. Now we have the requirement to check from only one person, Siddhi. We saw that strike pet Its Its Its use has been stopped. 8 minutes tight use has been stopped. 8 minutes tight means keep locking all the guys, here means keep locking all the guys, here Looper keep locking everyone and after this, whichever Looper keep locking everyone and after this, whichever child's young cricketer will be this master child's young cricketer will be this master element. Okay, so here you will element. Okay, so here you will get your small Valentine's Day. get your small Valentine's Day. get your small Valentine's Day. small inducts will be behind the track and Africa is guaranteed so we will accept the length okay what to do after this so here before we have never seen that you should have got more and now we keep so basically What was the index of the modeler What was the index of the modeler What was the index of the modeler - index of the current, so many are made - index of the current, so many are made right, so here we will add some more answer forces right, so here we will add some more answer forces on it, this is the index of the model on it, this is the index of the model - but the current index is fine, so - but the current index is fine, so share it. Amazing share it. Amazing that till now we have spoiled everything. that till now we have spoiled everything. that till now we have spoiled everything. what all the work has to be done and on the last it has some time effect. This work has to be done on this track dots I. Okay, so let's that we have to do elastic travel. Right on the IS GREATER THAN IF IT IS GREATER THAN IF IT IS GREATER THAN IF IT GOES UP TO 200 SO GOES UP TO 200 SO OK OK WHAT SHOULD BE THE CURRENT VALUE OK OK WHAT SHOULD BE THE CURRENT VALUE OUR NAME [ __ ] OUR NAME [ __ ] KI AND BY THE PACK KE KEE BANDA HAI BACK KI AND BY THE PACK KE KEE BANDA HAI BACK DOT CIGARETTE NOW 0 KI AND TAKE CARE PICK I HAVE A VALUE MEANS UP TO Or Or Or is it equal to the current value then turn it off Okay Baba it will be done and then we will do our work small index now by default name start length that if there is any guy left in my step practice is great 210 for respond It will be 626 WhatsApp, It will be 626 WhatsApp, It will be 626 WhatsApp, my dear, now you can adopt it here my dear, now you can adopt it here that this is how it got small indexing - but it came that this is how it got small indexing - but it came and then after putting it on the track on the field, after washing it and and then after putting it on the track on the field, after washing it and acting it came, then this work is completed, acting it came, then this work is completed, midding is done from here, Especially Especially Especially cancer and this course work is being done on it. Let's see the cancer and this course work is being done on it. Let's see the time complexity of Ramesh. Okay, let's time complexity of Ramesh. Okay, let's see how much time it takes to Check the thread. Well, a little before this cute but time Intercity Express Salim. How to calculate so if I have so this day's tour and travel so this day's tour and travel agent I plus plus here one more loot here if this is going from zero to J also less Ben10 or Now let's ask if this is also a parameter, then we will get a variable, so basically it is fine, let's write for this portal - Adhya honi chahiye thi main tere ko 12:00 loop hai, that end time And And And here I and there, some consistent work is being done. here I and there, some consistent work is being done. Okay, so what will be the time complexity of this entire court, Okay, so what will be the time complexity of this entire court, how do we decorate it? The how do we decorate it? The value of I will be 0a, so what will value of I will be 0a, so what will happen to K is that this will not be 0, JJ will be that zero. happen to K is that this will not be 0, JJ will be that zero. happen to K is that this will not be 0, JJ will be that zero. right will go from 0 to KK, the right will go from zero to cricket and every time a contract worker of semen comes in tight, then if I write in the time returns directly the tweet in which I write, then this will be the work of K Times of C1 and we can remove it too. I know that this is the whole people, he will unite K Times and is going to do semen's work every time, it is okay, when Bigg Boss was zero, K's work was done, this is Times Lucknow Asiwan Ka Aayi Aayi, Jab Hogi To If there is a semen test for the content of the youth of Times and Ka, If there is a semen test for the content of the youth of Times and Ka, If there is a semen test for the content of the youth of Times and Ka, then there will be creative work. The then there will be creative work. The value of semen will grow like this, the value of semen will grow like this, the value will come - it will go till the end, it will stop tight and value will come - it will go till the end, it will stop tight and even in the end - CEO, if this much work is going to be done, even in the end - CEO, if this much work is going to be done, then how many times will it happen? then how many times will it happen? then how many times will it happen? call me, what should I do, the but each time it has reduced. Cricket, but each time it has reduced. Cricket, today's time, soldier's time, C's, today's time, soldier's time, C's, WiFi Plus's time, CEO 5 Plus's WiFi Plus's time, CEO 5 Plus's times, CO's, this is how the endtimes went. times, CO's, this is how the endtimes went. times, CO's, this is how the endtimes went. difficult if I remove this End Times Where Times COAI and this Contest Monday now, then it is time to take the End Times decisions where N and Ki are both parameters of my input. Okay, that's why Year, we apply all the methods Year, we apply all the methods Year, we apply all the methods here, so here, so if we look at this group here, the values of I if we look at this group here, the values of I were babbar and minus one, so were babbar and minus one, so how much work did we do inside, if I look at so many people before this one, then this one how much work did we do inside, if I look at so many people before this one, then this one who was this right here, he is who was this right here, he is becoming a teacher and we have trained him, becoming a teacher and we have trained him, here we have here we have presented the stars on the Pandit, here is the presented the stars on the Pandit, here is the mathematical calculation and the tractor alam has mathematical calculation and the tractor alam has also opened to put it, okay, also opened to put it, okay, all the work can be done by oven story or speak. all the work can be done by oven story or speak. all the work can be done by oven story or speak. content and some of it is fine and the quantity will depend on this look. How many children will these people have? This look will work only when there is a person on the track and also this is the condition rule of the rallies. If this is the condition then So we ca So we ca So we ca n't bring Agri. How many times are these people going to run on? n't bring Agri. How many times are these people going to run on? Right, they are proud that this loop Right, they are proud that this loop will run only once or will run once. will run only once or will run once. Okay, now we have done how many more, Okay, now we have done how many more, we have done one work or When the value of i When the value of i When the value of i becomes minus 2, then again I becomes minus 2, then again I cannot give an in-depth review. Therefore, it can be said cannot give an in-depth review. Therefore, it can be said that it must have happened in the last few years and that it must have happened in the last few years and Sita must have been touched at the end minus 3. As the i Sita must have been touched at the end minus 3. As the i grows, it will become a challenge, so let's grows, it will become a challenge, so let's assume i20. assume i20. assume i20. person like this if I also cutlet how I went before I had added endtimes to all of them this time if I add all of these then I know that Adding Adding Adding tight end times by doing plus b plus c plus d like this tight end times by doing plus b plus c plus d like this but I don't know what is but I don't know what is their time, okay if you their time, okay if you look at the year condition and look back at the WhatsApp message, if look at the year condition and look back at the WhatsApp message, if I had given it, you would have found someone in the track. I had given it, you would have found someone in the track. I had given it, you would have found someone in the track. also pop it. All right, if this condition falls then this task will not happen and the loop will not run. Okay, so let's take a look in my entire code that Have Have Have done end done end here and this line runs total end here and this line runs total end time, so you can say that there can be time, so you can say that there can be maximum elements on this track. maximum elements on this track. Okay, if I Okay, if I can have maximum elements on this track, then this can have maximum elements on this track, then this loop is loop is loop is mean that the sum of all these is that the director of lesbian equal to bank, it is not surgery that elements were inserted 1234 by doing this and all of them passed tight, it is not like that, Also, if you Also, if you Also, if you look at the time, then either there will be no one on this track of yours look at the time, then either there will be no one on this track of yours or there will be no contract in the set or there will be no contract in the set or then it will not happen that internally we will go or then it will not happen that internally we will go tight, so A+B+C these people, the tight, so A+B+C these people, the number of times an accident is going to happen, it is number of times an accident is going to happen, it is always from the end. always from the end. always from the end. Actually it should be and minus one. This is because when you last played Law of Attraction, you put value on this track and after that you never sinned. It's fine. If you look at the complexity of this one, now Values on doing are that Values on doing are that Values on doing are that less Daily Quiz 2nd end is coming so if we less Daily Quiz 2nd end is coming so if we look at the year condition then now you can say that look at the year condition then now you can say that N request O A plus B plus C It will be something like this N request O A plus B plus C It will be something like this All the people have left Okay so it is off All the people have left Okay so it is off bank workers Overall bank workers Overall bank workers Overall okay then Congress is such a mess, this is the solution that if you have learned something from this video then definitely like it or try our channel so that you do not do this in such videos. Thanks for watching. | 2024-03-25 16:37:55 | 1,063 | Number of Valid Subarrays | Leetcode 1063 |
|
yc8pexYKOW0 | hey hi my name is today i'm trying to solve the july the new month juliet coach new challenge so the question is maximum units on a track and the question number is one seven one zero so the problem is came as a liquid easy so the problem is given there the vector of vector has been given which has a uh the given uh data of the box type and i have a uh track size as an integer format and we'll have to return the maximum number of unit that can put uh onto the uh truck so basically let's take an example so there is an um list of list or the vector vector box type has been given so first part that is one that is the number box and the second one that is the number of unit per box has been present so the two of two has the same uh the first the number of bugs that is two and the number of unit has been present that is uh also two and the third one that is the number of blocks that is three and the number of units per box that is one so if i've been taking all of them and in that case the number of unit will be here there are some of them so basically that's eight so how i'm trying to solve that let's make first round then after that i am trying to implement first of all i am taking the input first of all i am taking the input basically basically one and three one and three then then two and two two and two and then and then three and one three and one so what is given there basically i need to short according to the number of unit has been present as a reverse format but i am trying to reverse so basically i am trying to reverse because of i need the i need the maximum number of unit i need the max number of number of you need in my truck so that's why i am shorting the array sorting resp resp with respect to with respect to with respect to the with respect to the unit per unit per box so uh i wrote down the uh list of list so as a reverse moment so there is no required to short there but if the any and the vector breaker has been given in that case we'll have to first short according to the reverse format of the number of unit has been present there so after that reverse format has been present so first i will check and also the track size is that is four so first i will traverse the ready and check there basically the number of box in boxes that is one and the in unit will be that is three right now and i am uh initializing a variable first there is the uh taking that the answer format so first i will check that that number of box is greater than or equals to not first so basically the format has been fulfilling so in that case i am adding the value with that unit into multiply with the number of box number of blocks into the number of unit so you need so 1 into 3 so that will ends uh 0 plus 3 that is basically the 3 and it will deduct the number of blocks from the track size that is four minus one that is three right now and the answer is updated to and second case and second case in second case in second case that is that is now that is 3 is greater than or equal now that is 3 is greater than or equal to 2 yes to 2 yes 3 is greater than or equal to 2 right 3 is greater than or equal to 2 right now now i am adding the answer that is answer is i am adding the answer that is answer is equals to 3 plus 2 into 2 equals to 3 plus 2 into 2 because i am taking that both of them because i am taking that both of them both so that will answer the region 7 both so that will answer the region 7 so and so and the unit the unit reduced to it is 3 minus 2 i am taking reduced to it is 3 minus 2 i am taking the 2 box so 3 minus 2 that is one the 2 box so 3 minus 2 that is one and after that right now so answer and after that right now so answer become seven so i have only one in it i become seven so i have only one in it i have only one unit so i can only take have only one unit so i can only take the one top box only so the one top box only so one into one that is one so seven plus one into one that is one so seven plus one that is eight one that is eight so basically i am trying to there so basically i am trying to there uh as i updated that and then after that uh as i updated that and then after that as well as when the as well as when the that condition has not been fulfilling that condition has not been fulfilling in that case i am updating with there in that case i am updating with there the answer and then after that i will as the answer and then after that i will as possible return the answer possible return the answer so basically the so basically the time complexity is order of in time complexity is order of in log log n n where n is the number of uh list and where n is the number of uh list and that means not number of lists that is that means not number of lists that is the length of the list the length of the list and uh i am not taking any extra space and uh i am not taking any extra space uh so basically that the order of one is uh so basically that the order of one is the uh space complexity so the uh space complexity so i am right now trying to implement there first we will have to make an custom okay okay and return and return the key of one open that is the basically the uh greater than format uh if i've been taking that that's the uh shorting will be reverse format so first i will short the error begins not end and cmp that's done and now i'll for auto box type now type basically that is the box each box here i have been taking the for each loop basically so integer inbox is equals to boxer 0 and integer unit box unit per box is basically if the if the truck size is greater than or equals to number of blocks in that case in that case answer will be updated to inbox into unit box and after that the minus of inbox and else case there is a terminator i mean that condition in that case the the the truck size into bar bar box box and after that i will directly return and after that i will directly return the answer the answer and suppose you have been all the and suppose you have been all the returning uh i mean travelers in the returning uh i mean travelers in the array so after that that is also an array so after that that is also an option because in some condition uh truck sales has been much more bigger than the capacity of the box type so i in that case um the after all traversal that will be returning as an answer so i am right now trying to run my code to check if any compile time yeah it is accepted in the run code i am yeah it is accepted in the run code i am trying to submit thank you so much thank you so much [Music] foreign | 2024-03-20 15:13:40 | 1,710 | 1710. Maximum Units on a Truck Leetcode July Challenge 2022 |
|
ZkmKsxls0Rs | today we will solve a problem called world ladder and this is the second world ladder and this is the second version of this problem version of this problem so feel free to check the first version so feel free to check the first version also also so here we have a number of words in a so here we have a number of words in a list list and we have to reach from word one which and we have to reach from word one which will be called will be called the starting word and then the starting word and then end word so we have to reach from end word so we have to reach from here to here and there can be multiple here to here and there can be multiple paths so it's not really a ladder paths so it's not really a ladder it's like a graph and there can be it's like a graph and there can be multiple multiple paths so uh the paths paths so uh the paths have a length so if we have multiple have a length so if we have multiple cities cities let's take some practical example city a let's take some practical example city a b b c d and we have to go from city a to d c d and we have to go from city a to d then maybe we need to go like a to b then maybe we need to go like a to b b to c then c to d so this path has a b to c then c to d so this path has a length of length of 3 but maybe there are a few more paths 3 but maybe there are a few more paths a to c c to d so this path will be a to c c to d so this path will be two length and next two length and next let's say a two b and b two d this will let's say a two b and b two d this will be also of length two be also of length two so there are two parts of length two so there are two parts of length two and one path of length three so we are and one path of length three so we are interested in the shortest one interested in the shortest one and there are multiple such paths so we and there are multiple such paths so we have to return have to return the list of all those paths so here the list of all those paths so here instead of cities we have words instead of cities we have words and we have to transform one word to and we have to transform one word to another another and let's see some rules so uh and let's see some rules so uh if we have a word let's say abc just if we have a word let's say abc just three characters in this word three characters in this word then from this word i can go to either then from this word i can go to either a b and some wild character here a b and some wild character here i am writing asterisk or maybe i am writing asterisk or maybe a asterisk c or asterisk a asterisk c or asterisk b c and this asterisk can again take b c and this asterisk can again take multiple values multiple values so here the meaning is that just so here the meaning is that just one character in the word is changing so one character in the word is changing so from abc we can go to abd from abc we can go to abd abe abf so just one character change is abe abf so just one character change is fine fine similarly ac acc similarly ac acc adc and so on so you get the idea so we adc and so on so you get the idea so we are allowed to go to are allowed to go to a word w one two w w2 a word w one two w w2 where there is a change of just one where there is a change of just one character character and this word w2 will be called adjacent and this word w2 will be called adjacent to w1 to w1 because there is a path between these because there is a path between these two and these two will be said to be two and these two will be said to be connected connected so in a graph we have notion of so in a graph we have notion of connected connected nodes so we can only go to connected nodes so we can only go to connected nodes nodes so if 1 2 3 4 so if 1 2 3 4 is there from 1 we cannot go directly to is there from 1 we cannot go directly to 4 4 we have to go via 2 so from any node we we have to go via 2 so from any node we can only visit can only visit its neighbors or adjacent nodes and in its neighbors or adjacent nodes and in the terms of words the terms of words this is what it means so now let's come this is what it means so now let's come to the problem to the problem so we have one starting word so this is so we have one starting word so this is the starting word the starting word that i was talking about this is the that i was talking about this is the destination which we have to make destination which we have to make and it it will it can contain a sequence and it it will it can contain a sequence of words of words so words means nodes so it will denote a so words means nodes so it will denote a path path so hit from hit we can go to so hit from hit we can go to we cannot go to dot because if you we cannot go to dot because if you compare hit compare hit and dot you see that t matches and dot you see that t matches but this first character does not match but this first character does not match second character does not match so there second character does not match so there is a difference of is a difference of two but we can have a difference of at two but we can have a difference of at max one max one and these words the neighbors have to and these words the neighbors have to become from this list become from this list so these are all the nodes of the graph so these are all the nodes of the graph or here in this problem it's the list of or here in this problem it's the list of words so starting is hit words so starting is hit that is fixed ending is cog that is also that is fixed ending is cog that is also fixed fixed so we have to reach from hit to cog so so we have to reach from hit to cog so from it from it which node we can take if there is no which node we can take if there is no node which we can take node which we can take then we will return an empty result then we will return an empty result there is no path there is no path so in the graph terms if this is a graph so in the graph terms if this is a graph uh and this is the starting node s uh and this is the starting node s and there are a few other nodes and there are a few other nodes and these are connected among themselves and these are connected among themselves and let's say this is and let's say this is destination but s is not connected to destination but s is not connected to any of those any of those so no path exists from s to t similarly so no path exists from s to t similarly if no such word exists in this list then if no such word exists in this list then straight away return straight away return this empty list also here this empty list also here the adjacent word should be of the same the adjacent word should be of the same length so it's not that length so it's not that abc is a word and then a b is a word abc is a word and then a b is a word so we can go here because this is just so we can go here because this is just one character difference one character difference no no the length should be same only the no no the length should be same only the value can be different value can be different so this we have to keep in mind and it's so this we have to keep in mind and it's given that given that you don't have to worry about this you don't have to worry about this length difference that will not be in length difference that will not be in the input so from heat we can go to hot because there is hit hot so the difference is just here all the two words are same so we can go too hot from hot can we go to any other world from it no not no dog no no no other word from hot we can go to uh dot is one because there is just one character change so you see a graph is forming so you see a graph is forming lot and any other no from dot we can go lot and any other no from dot we can go to to dog and no other word from lot we can go to log from dog we can go to cog and from log also we can go to cog and this is the final word so we don't need to check further if we go further and maybe there is another path that will be longer so if even if uh from log there is some other word uh let's say talk and from talk there is cog so this path will be longer so we we will stop once we process this so let's draw the graph from this so it is there let's draw the nodes hit dog then we have lot dog then we have lot then we have log cog now then we have log cog now it is connected to hot so there is a it is connected to hot so there is a edge between these two edge between these two hot is connected to a lot and dot then dot is connected to hot and lot and similarly log is connected to dog and cog and dog is connected to cog and log is connected to lot so this is the graph we are talking about so starting node is given so this white node is the starting one and this is the so this is a simple graph problem we so this is a simple graph problem we have to find the shortest path have to find the shortest path from source to destination from source to destination and there can be multiple paths of the and there can be multiple paths of the same length same as the shortest one same length same as the shortest one so we have to find all such paths so so we have to find all such paths so from s we go to hot from s we go to hot from hot we can go to either from hot we can go to either dot or not both so you see dot or not both so you see we are proceeding in breadth first we are proceeding in breadth first search manner so we start from a source search manner so we start from a source we go to all the neighbors so just one we go to all the neighbors so just one neighbor so we come neighbor so we come to heart from hot there are two adjacent to heart from hot there are two adjacent neighbors neighbors dot and lot so these two comes next uh so let me redraw here so we have hit from hit we can go to hot from hot we can go to lot and dot if there would have been any other adjacent node we would have listed that also because this is the first node in the path the result this is the second node these two are candidate third nodes and we don't know from maybe from one of these we don't reach the destination so we will not include that but these three are all equidistant from this so we are wasting in breadth first such manner this node then its neighbors all the neighbors that are one unit distance from here this is level 0 level 1 this is level 0 level 1 level 2 and so on and let's say level 2 and so on and let's say destination was here destination was here and there are multiple paths leading to and there are multiple paths leading to this this at level 4. so shortest path will be of at level 4. so shortest path will be of length 4 length 4 and there are multiple of those so we and there are multiple of those so we don't need to check further don't need to check further below this so this is what we are doing below this so this is what we are doing so this is clearly a so this is clearly a breadth first search so uh if you are breadth first search so uh if you are not familiar with not familiar with breadth first search i would recommend breadth first search i would recommend to check my uh video on to check my uh video on breadth first search before coming to breadth first search before coming to this because you can understand it this because you can understand it but while writing the code you may get but while writing the code you may get stuck stuck so the idea is that we push the source so the idea is that we push the source to the queue to the queue so this node is listed the source here so this node is listed the source here then we see all its neighbors and we then we see all its neighbors and we push all of them to the queue push all of them to the queue so we pop this node from the queue and then push all all its neighbors so at any time point of time so this three nodes are in the queue these three nodes are at level one now we take a counter that three nodes are there so we run a loop for i equal to zero to two uh keep popping them and keep pushing the neighbors to the queue so uh these white ones will be pushed after this yellow ones irrespective of whether their neighbor of this one this second one or third one but we have already taken the count what was the count before we started uh processing the next level that was three so for the next three we know that we are processing the earlier level now when this loop ends these all three will be from the queue and only level two nodes will be there in the queue again we will take the count and then keep pushing that so that elements are traversed in level by level in order so this is the essence of breadth first search in sort now here we are doing the same thing so dot and lot and dog n log and then we have cog and cog and this is essentially the two parts so we have to return here hit hot lot log cog this is one and hit so a list of lists so a list of lists so this is what we have to return so how so this is what we have to return so how we are doing we are doing let's start again so we have initially a let's start again so we have initially a list of list of words which contains uh words which contains uh so this it's given that this initial so this it's given that this initial word word or the end word may or may not be in or the end word may or may not be in this list it may be or it may not be this list it may be or it may not be so we will create an exhaustive list so we will create an exhaustive list where we include all the words or we can where we include all the words or we can skip the first one because this will be skip the first one because this will be the first word the first word that will go into the queue so no need that will go into the queue so no need to insert and then pop to insert and then pop back again but we can do that for back again but we can do that for completeness so let's create a bigger completeness so let's create a bigger list list so hit so hit hot dog hot dog lot uh cog lot uh cog and 2 4 5 and so this is the exhaustive list so we so this is the exhaustive list so we will keep them all in a will keep them all in a hash asset or unordered set in c hash asset or unordered set in c pluses because we will be pluses because we will be need to check access need to check access or find some words so we can keep them or find some words so we can keep them in a set and then what we will do we will pull out the first word and put it into the queue so now queue contains hit and in the queue we keep track of the running path so when we are at hit we are denoting all the paths starting with whose first word is hit we are extending this path until the last node is cog so this is a running path we are maintaining all candidates running paths so till here it was hit then when we reach here we have hit and hot so all the paths have to start with these two words only this is the only path now here we have two paths so this will fork track track so after this level so after this level when we reach this this level we will when we reach this this level we will have two paths have two paths hit hot and hit hot and lot and also hit lot and also hit hot and dot these two are running paths hot and dot these two are running paths path one path two path one path two so we have to process this entire thing so we have to process this entire thing and we will we need to extend this path and we will we need to extend this path so when we so when we when we are extending it we are only when we are extending it we are only interested in the last word interested in the last word because this path is already built and because this path is already built and what next word can come here so we have what next word can come here so we have w1 w1 w2 w3 in a path p w2 w3 in a path p and we are looking for what is the next and we are looking for what is the next word that can come here word that can come here so we will only be comparing the last so we will only be comparing the last word in this word in this running path and check what are the running path and check what are the neighbors of this neighbors of this w3 and we will append all of w3 and we will append all of those so let's say first word is w3x those so let's say first word is w3x second word is w3y third word is second word is w3y third word is w3 z these three all are neighbors of w3 w3 z these three all are neighbors of w3 so this path will result in three more so this path will result in three more paths maybe uh some of these lead to the maybe uh some of these lead to the target some of these does not lead so target some of these does not lead so which whichever leads to the target that which whichever leads to the target that will be part of the answer will be part of the answer so you see uh we are keeping track of a so you see uh we are keeping track of a running path this you have to keep in running path this you have to keep in mind mind while writing the code and we are while writing the code and we are extending it extending the path based on extending it extending the path based on the last word the last word so that it forms a sequence w one two w so that it forms a sequence w one two w two two w two to w3 and so on so w two to w3 and so on so initially hit is there in the queue initially hit is there in the queue then we run then we run we write a simple bfs we write a simple bfs code while not q dot empty code while not q dot empty till the queue is not empty keep doing till the queue is not empty keep doing it it so uh we have path which so uh we have path which pop it from the front so get the front and also pop it so now hit is removed so this path is denoting hit and this is not the complete path it's the incomplete running path so currently it has just one word but this will get extended now we pick the front and we see what are its neighbors the same thing we do in normal bfs we pop a node and then look for all its neighbors so we will better to define a function in the code and we will pass a word and in the code and we will pass a word and this word list this word list and this will return a list of all the and this will return a list of all the neighbors or you can neighbors or you can write here also but better to create a write here also but better to create a separate function separate function so this find neighbors will return so this find neighbors will return so its neighbors are hot and nothing else just one so we will append if this is multiple words then just see here so hit hot hot has two neighbors lot and dot so this path will fork into multiple paths the same as number of neighbors so currently it has just one so the new path will be uh hit and hot and this will be pushed to the hit and hot hit and hot now again q is not empty so we will pop now again q is not empty so we will pop this one this one so now path contains hit so now path contains hit hot and this is popped so this one is hot and this is popped so this one is gone gone next this is the path so we only check next this is the path so we only check the neighbors of last word the neighbors of last word we are not bothered about this this is we are not bothered about this this is already a already a semi path so what are the neighbors of semi path so what are the neighbors of what those are the candidates which can what those are the candidates which can come here come here so again we will call find neighbors it so again we will call find neighbors it will return uh will return uh heart has neighbors lord heart has neighbors lord so these are neighbors so these are neighbors lot and dot so two neighbors this time lot and dot so two neighbors this time so we will have two new paths so we will so we will have two new paths so we will insert insert all of these two in the queue again so q all of these two in the queue again so q is here empty is here empty but we have not went till the end of but we have not went till the end of this while loop so this while loop so before reaching here again these two before reaching here again these two will be pushed in the queue will be pushed in the queue so the new path will be hit so the new path will be hit hot then lot hot then lot so this will be pushed to the queue so this will be pushed to the queue here and here and hit hot dot this will also be pushed hit hot dot this will also be pushed now the queue has two parts hit hot hit hot dot hit hot dot these two are in the queue so again q is these two are in the queue so again q is not empty so not empty so this we will uh this we will uh first remove the first path so p first remove the first path so p is hit is hit hot lot then we will find the neighbors hot lot then we will find the neighbors of lot which are of lot which are [Music] [Music] dot and log but dot we have already here so when we but dot we have already here so when we process a no process a no label we also remove all the nodes which label we also remove all the nodes which we just processed so here uh we just processed so here uh when we included this lot and dot when we included this lot and dot into it and we are now ready to go back into it and we are now ready to go back to the beginning of this loop to the beginning of this loop before that remove this lot and dot from before that remove this lot and dot from the the this list so dot this list so dot and lot removed similarly in the and lot removed similarly in the beginning it was removed beginning it was removed next hot was removed so that we don't next hot was removed so that we don't reach to that node again reach to that node again in the next level so it's okay that so this is node 1 node 2 node 3 so this is node 1 node 2 node 3 node 4 node 5 and let's say this is also node 4 node 5 and let's say this is also connected connected so it's ok to have reach this node 4 so we can reach this node 4 from multiple nodes in a previous level so once we process this we have to remove this four once we have processed both otherwise if we just process two and remove four then we will never find this edge so once you process all the nodes in a given level you remove all the nodes which we just visited so we will have a visited error also which we will remove from the list so that next time now 4 is gone so in the next level when we reach 5 we will not include this edge because from 1 to 4 there are two parts of length 2 so there is no point in reaching 4 with 3 edges that will never be the shortest maybe from 4 we are reaching the target so this path the white one this is 5 let's so 1 2 4 5 this is a path of length 3 similarly 1 3 4 5 but if we allow this edge also here this one then the path will be one three five four maybe this length is bigger so that's why we this length is bigger so that's why we are not bothered about are not bothered about this length so as soon as we this length so as soon as we uh process all the nodes in a given uh process all the nodes in a given level remove all the visited nodes from level remove all the visited nodes from the list so that we the list so that we these are never discovered again these these are never discovered again these are already listed are already listed uh so dot will not be included here uh so dot will not be included here since we would have removed this dot since we would have removed this dot after after third level or second level so dot will third level or second level so dot will not be here not be here so uh so uh log will be here just one neighbor and the next we will pop this one the second path so it will be hit hot dot and then dog so now these two are removed from the queue so q is now again empty and now we have processed again a new label so we will remove which words log and dog from the list so this list dog and log are removed now in this list just cog remains now again these two are in the queue so the queue has hit hot lot log and hit hot dot dog these two paths are in the queue so again the queue is not empty and we have also not reached the end word so you will see that we will later keep track of whether we have reached the target word or not using just a boolean flag now we pop the front element so path is hit hot lot log so what are the neighbors of log we will search in this list so we will find cog just one neighbor so we will append just one neighbor and push it to the queue and next one and also since this is equal to the destination we can now be sure that next level we don't have to process this is the last level we are processing so this is removed from queue next this one is popped hit hot lot dog next we find neighbors of dog which will be cog so you see why we are not removing uh this in between we remove the nodes only after we process all the nodes at a given level because there can be same thing multiple paths from previous level to a given node if we remove after wasting this first one we will never discover the second one so again it will find a neighbor just one neighbor cog so we will just append cog and again uh we will add this so as soon as we reach a destination the last word we add this running path this running path is now complete so we will add it to result similarly again here cog is reached so again we push it to the result so in this case two parts will be there so you get the idea now once you are comfortable with this reasoning why this is so we are ready to start the code so you can go through a few more so you can go through a few more examples so in this case examples so in this case the path is empty there was no path from the path is empty there was no path from heat heat there is no neighbor of it here or a heart is never then we can go to dot a cog is not in the word list okay so a cog is not in the word list okay so cog is not in the word list therefore cog is not in the word list therefore there is no valid transformation there is no valid transformation sequence sequence so if the last word is not there then so if the last word is not there then again it cannot be formed and begin word does not need to win the word list okay so that should not affect anything what we have seen now uh we will need a function to find the neighbor so first let's complete that so that should return a list of neighbors or a list of words and words are string so vector of strings neighbors neighbors [Music] so this should take from the word and so how do we find one ways that you pick so how do we find one ways that you pick all the words all the words in the reward list one by one and start in the reward list one by one and start comparing comparing so that should also work one another way so that should also work one another way is that is that uh using this logic so what we were uh using this logic so what we were seeing here you have this one so we were saying that this asterisk character so first we are b c d try all the letters so these are b c d try all the letters so these are made of made of small english letters so we can try small english letters so we can try replacing all of those and then match replacing all of those and then match whether that word exists in this whether that word exists in this list or not so we said that we will convert this to a set so that searching is easy so instead of vector we can have an ordered set of this one and here we will create non-ordered set otherwise searching in this vector will you so first we will replace the first letter with all the letters in english alphabet smaller letters then the second letter third letter and so on and then we need to restore the word back so that's why we are saving what you so what we are doing here so we replaced first character with letter a the new word is different from the the new word is different from the original word by just one character original word by just one character and we then find whether it exists in and we then find whether it exists in the word list or not the word list or not if it exists then it's never if it exists then it's never and if it does not exist we do nothing and if it does not exist we do nothing then we replace the second then we replace the second character again by character again by a to z we try all the combination and a to z we try all the combination and again the third character in the word again the third character in the word by all the combination and then find in by all the combination and then find in this this has set and finally when we are done with it we restore that character back now we have the function ready we are now we have the function ready we are ready to write the ready to write the main function so result is a vector of a strings then cube so this is the running path initially just in the begin board all the parts will start with this node and this will get extended and then reach to then reach to end this we have to keep track when we end this we have to keep track when we reach end reach end we add that path to the result and also we add that path to the result and also we don't proceed further to the next we don't proceed further to the next level and remember we need to remove all the nodes once we are we have processed all the nodes at a given level we will remove all the new words that we reached so this will we will keep track invested so this will we will keep track invested now the normal bfs thing while not now the normal bfs thing while not q dot empty so this loop so initially we find how many nodes are there in the queue if it's let's say five then this loop will run five times and it will also be pushing the neighbors back to the queue so we will not be able to segregate which one was from which level but before starting that pushing any node from next level we keep track of how many nodes are there in the queue that's how we process all the nodes at a given level together and then after this loop this queue will only hold the nodes at the next level and again we will find the size and again so this helps in so this is the path we can write p for so this is the path we can write p for path path running path which the same thing we running path which the same thing we used in the explanation used in the explanation so this is the running path or prefix of the path not the complete path ah then q dot pop and then the neighbors neighbors of the last word last word author not back the last word last word author not back the last word and then we need to pass the word list and then we need to pass the word list not this vector but this not this vector but this set so that this function is faster if set so that this function is faster if we find we find in the vector again it will work but it in the vector again it will work but it will take off and time will take off and time here it should take lesser time since here it should take lesser time since it's a hash set so these are the neighbors so if there are three neighbors we will append all the three words to this path so this path will grow and it will break into three more paths but if there is just one neighbor then so uh so we have to append all the neighbors all the words in this list at the end of this path and then push so vector string so this is the current path so here it's just a copy of this path so here it's just a copy of this path then we have to append and so this neighbor was included this neighbor j was newly included in this running path so once we are finished with all the nodes in this level we will remove it from the original list and this is which we keep track in this widget and this is unordered set so it will not allow duplicates if a node is reached from multiple nodes this will be inserted only once you cannot remove more than once visited visited dot insert this neighbors j and one more thing we need to keep track of maybe this neighbor's j was the target word or the end word then if we don't keep track of that if we don't compare that we will keep processing it till we reach the maximum level so we have to also check whether so if end word then this should be added to end word then this should be added to the result the result so result dot so result dot push back and this is the complete path now also and this is the complete path now also we will make this reached end equal to true and once we process all the nodes at this level we will check whether reached end is true or not if it is true break out of this while loop so we are pretty much done here uh we need to come here uh so now we have removed the nodes that so now we have removed the nodes that were just were just visited in the previous visited in the previous level so that we don't reach there again level so that we don't reach there again with a longer path and then uh widget also needs to be cleared otherwise it will have unnecessarily and finally we return the result and let's see if it uh it's a long code so don't get too uh it's a long code so don't get too worried if you get some worried if you get some compilation issues in the beginning compilation issues in the beginning push back new path result should not be this you can see result should not be this you can see the return type it the return type it vector or vector of a string so vector vector or vector of a string so vector of a string denote of a string denote one path it's a it's a vector of one path it's a it's a vector of those paths uh hit hot dot dog uh hit hot dot dog cog and the solution is accepted here and the solution is accepted here so you can try in other languages also so you can try in other languages also it's a very long code it's a very long code writing in python and java again would writing in python and java again would take take maybe 10-15 more minutes maybe 10-15 more minutes so if you have any better solution you so if you have any better solution you can share can share your comments thank you | 2024-03-21 11:26:12 | 126 | Word Ladder II | LeetCode 126 | C++ |
|
GiTt33u7GF4 | hello hello everybody this is larry this is day 25 is day 25 of the august record daily challenge of the august record daily challenge hit the like button hit the subscribe hit the like button hit the subscribe button join me on discord let me know button join me on discord let me know what you think about dave's farm i have what you think about dave's farm i have some like some like allergy stuff yeah allergy stuff yeah tree allergies what am i gonna do tree allergies what am i gonna do my choice problem is peaking iterator my choice problem is peaking iterator design an iterator that supports the design an iterator that supports the peak on an existing elevator what's an peak on an existing elevator what's an iterator just iterator just okay okay so that you're given an iterator and so that you're given an iterator and you're basically you're basically trying to do a layer such that it um trying to do a layer such that it um it has a supports a peak function that's it has a supports a peak function that's okay that's basically okay that's basically um um hmm what do you want me to do iterated hmm what do you want me to do iterated oh i say this is what this is okay i oh i say this is what this is okay i mean this seems pretty straightforward mean this seems pretty straightforward it's just about it's just about you know pre-caching one answer i you know pre-caching one answer i suppose um and that's basically the idea suppose um and that's basically the idea i i think i i think so it should be okay so it should be okay um it's kind of a tricky thing to um um it's kind of a tricky thing to um conceptualize around to be honest conceptualize around to be honest because i think iterator is definitely because i think iterator is definitely not not necessarily a beginner's necessarily a beginner's um um thing i mean it i guess it's like thing i mean it i guess it's like beginners but it's not necessarily like beginners but it's not necessarily like i don't know i don't know uh so i think being able to this and uh so i think being able to this and this is maybe somewhat it's not this is maybe somewhat it's not specifically language specific but it is specifically language specific but it is um like understanding of your language um like understanding of your language will help a lot you know technically will help a lot you know technically this is not how you do iterator in this is not how you do iterator in python but yeah we'll live uh yeah and then now what do we want to do okay so first we keep track of the iterator but this is all implementation so i'm gonna instead so i don't have anything like overarching talking about it i'm just going to go over it as we solved them uh also uh my neck still hurts a little bit so bear with me as i maybe struggle a little bit in uh in agony but oops okay so peak what we want so what we want to do is create the next item right so maybe something like next item is you go to iterator.next um [Music] i don't know if i want to write it this way but conceptually something like this uh uh peak cache peak cache is you go to is you go to uh uh self dot peak maybe someone like that i don't know and the idea here for us is just and the idea here for us is just that that we already have self.iterator right um so now we want to do um then this we said this is you go to well then this we said this is you go to well next object as you go to next object as you go to um next is you go to self.iterator.next um next is you go to self.iterator.next so now we we get the next element and so now we we get the next element and then in the peak cache we just set it to then in the peak cache we just set it to the next element um the next element um [Music] [Music] yeah i mean i think it i was going to do yeah i mean i think it i was going to do something like an explicit has next flag something like an explicit has next flag but maybe this is fine and then else but maybe this is fine and then else self.peak cache is self.peak cache is you go to none because it doesn't have you go to none because it doesn't have an x right and then now that's pretty an x right and then now that's pretty much the idea here or i don't know about much the idea here or i don't know about like this naming but maybe like this naming but maybe uh uh check next uh check next uh p cash p cash cash peak maybe i don't know naming is cash peak maybe i don't know naming is hard so definitely absolve yourself hard so definitely absolve yourself there peak okay there peak okay now that we have that ready peak then is now that we have that ready peak then is just returning um just returning um let's see let's see let's peek without moving the pointer i let's peek without moving the pointer i was just curious what happens if there was just curious what happens if there there isn't uh the next element there isn't uh the next element so okay well so okay well i guess it just assumes that there's i guess it just assumes that there's always a next element okay all calls are always a next element okay all calls are valid so okay so then that means i sell valid so okay so then that means i sell that peak cache that peak cache and we can just return this it will just and we can just return this it will just be the next number uh the next then is be the next number uh the next then is just just uh uh result is to go to self.peak result is to go to self.peak cache and then self.um cache and then self.um you know do the thing where we you know do the thing where we repopulate it and then we turn result repopulate it and then we turn result and then has next is just return self and then has next is just return self dot peak cache is dot peak cache is not none not none right because if it's not none that right because if it's not none that means that we have a next element that means that we have a next element that we can fetch um you can of course we can fetch um you can of course separate this into two explicit separate this into two explicit variables you like um here i'm a little variables you like um here i'm a little bit lazy today maybe uh hopefully this bit lazy today maybe uh hopefully this is good uh okay so this is wrong why is this one seems like this is mostly right except for the first next wait hmm oh i i think i just messed up here because i i think i wanted this to write a different way so i wrote this thing but actually what i need what i just needed is this but because this returns none it actually flushes the first thing to none uh but this is why you test code because you know silly things like this happen and of course this isn't type safe because this is python so it was harder to spark than maybe normally but as you can see this is good yeah i mean is that good yeah i mean is that good i guess technically i guess technically we didn't test the thing where we have we didn't test the thing where we have has next return true but i feel like has next return true but i feel like this is mostly what i this is mostly what i want so let's test that really quick and let's give this a minute apparently i did it about a year ago hopefully this is right yes 755 everybody uh cool uh just to go over the thing i mean i don't think there's that much to go over um this is go everything is all one this is all one because just return variable this is technically of one in the sense that everything else other than the the cat this functions of one this function technically speaking you don't know the cost of getting the next i object in the iterator it may take a while there may be some amortized cost but the extra cost would be all one so this is you know the same as the iterator itself um so yeah it has next is obviously all of one so yeah so everything is over one maybe some ammonization with respect to whatever the original iterator is you can think of for example if this was like next permutation or something like that um i mean i i guess this is always intimate but if you have an iterator that returns all the permutations for example it we might have an over n where n is to the size of the collection in terms of the running time in the worst case but amortize all one or something like that right but even then that's just depends on the iterator so this is not your responsibility per se so so this is going to be close enough everything outside of the the original function cost is all one so yes i'm super happy about this uh that's all i have for today though uh let me know what you think i'm gonna lie down and just rest my neck uh oh people problem so take care of your posture i need to do something about anyway stay good stay healthy to good mental health i'll see | 2024-03-22 14:10:28 | 284 | 284. Peeking Iterator - Day 25/30 Leetcode April Challenge |
|
hFNmfr8zmBE | hello everyone welcome to my you programming club today we will be programming club today we will be solving another daily El Cod solving another daily El Cod Challenge and the name of challenge is Challenge and the name of challenge is find in Mountain find in Mountain array so it is mentioned that it is a problem uh you can recall an problem uh you can recall an array you can recall that array is a array you can recall that array is a mountain array if and only if the mountain array if and only if the following condition following condition satisfies so there should be at least satisfies so there should be at least three elements in the three elements in the array and array and basically there should be a peak element basically there should be a peak element in the array there should be element I such element uh the till that particular element uh the till that particular element the array is in increasing element the array is in increasing order so from 0 to I you can see that order so from 0 to I you can see that the array is in increasing order and the array is in increasing order and after that the ARR is in decreasing after that the ARR is in decreasing order order so two adjacent elements cannot be equal so two adjacent elements cannot be equal here the equality is not mentioned here the equality is not mentioned here okay so something like this could be there till a particular index let's I the are should be in increasing order I the are should be in increasing order and after that it should be in and after that it should be in decreasing array return return the minimum index array return return the minimum index such that mountain array. get index equal to Target if such an index does not exist you should return minus one okay so you cannot EX access the mountain array directly you may only access the mountain array interface so Mountain array interface methods one will be Mountain array do methods one will be Mountain array do get Returns the element at index get Returns the element at index K okay and another will be Mountain K okay and another will be Mountain array do length Returns the length of array do length Returns the length of the mountain the mountain array so your submissions making more array so your submissions making more than 100 calls to this particular than 100 calls to this particular function Mountain array. function Mountain array. getet will be just wrong getet will be just wrong answer also it is mentioned that any answer also it is mentioned that any solutions that attempt solutions that attempt to circumvent the judge uh will be to circumvent the judge uh will be resulting in resulting in disqualification let's have a look at disqualification let's have a look at the the constraints according that uh we will be constraints according that uh we will be forming our forming our solution so the length of mountain array solution so the length of mountain array is ranging from 3 to 10 to power 4 is ranging from 3 to 10 to power 4 elements and the target is between 0 to elements and the target is between 0 to 10 to^ 9 and the mountain array do get index will range from also range from the same range in which the target is 0 to 10^ 9 okay so we will try to solve this particular problem in the most optimal way possible so without further delay let's problem so to solve this particular problem what we will do limit on get write answer that we so if we have to search in this particular Mountain search linear search will require you at search linear search will require you at Max order of let's say n Max order of let's say n calls where n can be the size of your calls where n can be the size of your Mountain array n will be your size of mountain okay so to reduce the number of calls to okay so to reduce the number of calls to get search binary search of L and calls it will be uh little more than that but uh the order Remains the Same so it will reduce your number of calls so this is the most optimal solution I can think of as of now which will be there but you may ask the array that we will be given will not be in sorted form so it can be something like then then let's say it is 4 3 let's say it is 4 3 1 so as you can see the whole array is 1 so as you can see the whole array is not not sorted but uh I would say is sorted but uh I would say is that this portion of array and this portion of array these two are sorted the whole array is not sorted I sorted uh it is sorted in decreasing order and this one is sorted in order binary search can be easily order binary search can be easily applied here we just have to find the applied here we just have to find the peak peak element for Peak element also to reduce the FS number of FS number of calls to get search so in total how many binary search will be used uh one then two and then three so three binary searches will give us the index of the mentioned given a mountain array you mentioned given a mountain array you have to the minimum index yeah minimum have to the minimum index yeah minimum index you should return index you should return return minimum so let's try to implement the so let's try to implement the solution those of you who are not solution those of you who are not familiar with binary search I will familiar with binary search I will be providing a be providing a link of uh an article describing what link of uh an article describing what binary search is can explore that link and you will be able to understand the problem in a much clearer way so this particular article will be provided to article okay here it's uh mentioned in article okay here it's uh mentioned in that how B search works and it that how B search works and it implementations in various implementations in various languages so let's move back to the languages so let's move back to the problem let's try to implement it first of all we will find the peak element of array finding the peak element array finding the peak element of aray we are using binary search on the search space comprising indices of indices of the M AR okay and is yeah I think it's fine let's is yeah I think it's fine let's proceed uh let's declare the left and the right ranges of binary first of all let's capture the size of first of all let's capture the size of the mountain name m ARR will be I think name m ARR will be I think fine okay so the limit is only on the get function okay not on the length function but we are using it only once okay and then last index from zeroth index to last index we will be and this is just a standard binary and this is just a standard binary search with some little twixs here it is search with some little twixs here it is to be noted that I not uh allowing left to be noted that I not uh allowing left to be equal to write since I will to be equal to write since I will require at least two elements to make require at least two elements to make comparison comparison what will be the comparisons I will uh what will be the comparisons I will uh tell you along tell you along the way so we will find the mid the way so we will find the mid index which will be nothing but left index which will be nothing but left plus right minus left by 2 this uh left plus right minus left by 2 this uh left + right minus left by 2 is nothing but + right minus left by 2 is nothing but if you simplify it left plus right all if you simplify it left plus right all divided by two this is just to avoid divided by two this is just to avoid integer integer overflow okay and yeah so we will be comparing the mid element and the element element at the mid mid mid index index and one element next to it if let's index m index m r dot get r dot get mid index is lesser than m.g mid index + one so the next element very next element to the mid index is is left of your left of your range will be shifted to Mid index + one range will be shifted to Mid index + one so why we are shifting the left of your so why we are shifting the left of your range to Mid index + one so consider range to Mid index + one so consider this this case if let's case if let's say you are index index and the element next to very next to it and the element next to very next to it is greater than this so to find the peak is greater than this so to find the peak element you should be moving in this element you should be moving in this direction so to move in this direction direction so to move in this direction your left of your your left of your range will be shifted to your mid index range will be shifted to your mid index + + one one okay that's why we are doing so and so and also uh let's Define a variable also uh let's Define a variable Peak Peak Peak Peak index basically initially it will be index basically initially it will be having a value of let's having a value of let's say last element okay you can give it any value it will change so Peak index will be will also be this mid index + one since we are uh required to find the integer of index so this particular binary search index so this particular binary search will will be to find be to find the index of B the index of B element in Mountain array okay and yeah let's proceed further and if that's not the case and if let's region okay region okay so if that's not the case and your mid element is uh it uh two elements cannot be equal so this will be that uh your mid index element is greater than uh this particular element which is nothing but mid index + one okay the uh you are in the decreasing you are in the on the uh descend uh not on the Ascend part so you are in the decreasing part then you will uh what you will do is uh El index M or Mountain array do get mid index M or Mountain array do get mid index or we can index or we can avoid the call of get avoid the call of get here we can just use else here we can just use else only since it is well understood that only since it is well understood that you are trying you are trying to implement a condition something like this so just to avoid this call we are using else okay uh this get what call I talking about the a call of get function okay and since we have are not index it uh it can be our Peak index why it can be our Peak index uh because uh this particular condition that we are checking also index uh this element will be uh greater index uh this element will be uh greater than uh the uh very than uh the uh very much next element to much next element to it so uh array of I will be greater it so uh array of I will be greater than array of I + 1 because after the than array of I + 1 because after the the peak the peak element uh the array will be in a element uh the array will be in a decreasing Trend okay so that's why we are doing so and so we will just index not + one only mid index index not + one only mid index okay and then what you will do is uh we will try element element index in right part index in right part first you can choose left part first first you can choose left part first also that will not matter uh by using also that will not matter uh by using binary search in uh right part right part will be comprising of uh of indices uh from index size minus index size minus one one okay so let's define Let's uh redefine okay so let's define Let's uh redefine the values of left and right so your the values of left and right so your left will be now pick left will be now pick index and right will be having value index and right will be having value of size minus one okay and in this particular part we are not interested in comparing two adjacent values so we will be using the condition left equal to okay and we will be uh using a standard okay and we will be uh using a standard binary search implementation without any binary search implementation without any Twix so Twix so let's solve the problem uh first we will be finding our mid index which will be nothing but left plus right minus left by two uh if you are still not able to understand why I'm using this condition I think it should be mentioned in this article why they use why we use this particular condition mid is equal to to as you can see this particular uh way of finding the mid is also used here so I think it should be mentioned in the article if uh it's not there uh please ask in the comment section I will be more than happy to answer uh with further elaboration so we are done finding the mid index and Target Target if your let's Target if your let's say mid index than Target than Target value value then what you will do is oh first of all let's if if uh mid index is having the value of uh mid index is having the value of Target or I think it's Target or I think it's fine we will check it at last so left will be shifted to Mid index + one okay and then if that's not the your let's your let's say value at Mid say value at Mid index happens to be greater than the index happens to be greater than the target target then you will shift your right to then you will shift your right to basically uh in these two cases you are basically uh in these two cases you are just reducing your search space just reducing your search space okay okay so mid index minus one it will be and as so mid index minus one it will be and as if you have hit the target target then you will then you will return return true or not return true uh you will be true or not return true uh you will be returning the mid returning the mid index so this will be the index of your index so this will be the index of your target target okay and similarly you will okay and similarly you will do uh binary search to find the Target in left hand side if it's not there in the right hand search and we try to find the peak search and we try to find the peak element in left left side of peak part which comprise of the indices part which comprise of the indices from 0 from 0 to P index okay so these values will be changing instead of peak index left will be at your zeroth index and right will be at your P index I think rest all should same I think we have done a mistake here uh since we were doing binary search in the right part we should have uh considered that it is in decreasing signs only then it will give you correct answer so I think uh you understood that uh why we are reversing the signs because this binary search we will considering for the increasing array so to uh accommodate the decreasing array we are reversing the signs uh this one is correct for the increasing array okay index and then yeah pretty that's pretty index and then yeah pretty that's pretty much it I much it I think uh at last you can return any think uh at last you can return any value or if it's mentioned that if value or if it's mentioned that if answer does not exceed you should return answer does not exceed you should return a particular value let's a particular value let's check uh yeah it's mentioned then you check uh yeah it's mentioned then you should return return minus one if the should return return minus one if the target is not target is not existing so we will do as the problem existing so we will do as the problem ask return minus one I think there is one brace extra in the implementation that I have used yeah uh we have implemented these two binary search search anyhow uh we will Rectify anyhow uh we will Rectify that by moving it out of these two binary searches will be one so this is your first binary search one so this is your first binary search and these will be and these will be the other two binary searches the other two binary searches so let's try to so let's try to submit for the sample test cases it's giving some compilation error okay here I by mistake took at n minus one one one so for one test case it's giving so for one test case it's giving incorrect result I think I found out the mistake here we are getting wrong answer uh because we are finding the occurrence of three here this particular occurrence we are finding but we should be giving this answer so we should be checking in the left part first instead of checking the right part first so order really matters here I thought the order will matters so left side will be checked matters so left side will be checked first left side of peak element first uh return return minimum minimum index of index of occurrence of Target occurrence of Target value okay so let's try to submit again value okay so let's try to submit again for sample test cases as you can see it's getting EX accepted now so the mistake that we did was Finding for the right part first so you should be finding checking the Target in left part first in order to give the minimum index possible of Target occurrence so Target can be existing here also and it can exist here also as you can see in this particular example or sample test case three is existing here and three is also existing here so this is the your Peak element so it is existing on the left part and the right part if you uh do binary search on right part first then you will give the higher index So to avoid that case we will do binary search in left part first evaluation as you can see the solution evaluation as you can see the solution is getting accepted so the code will be is getting accepted so the code will be available in C++ and Java both uh and I available in C++ and Java both uh and I will also try to make it available for will also try to make it available for Python 3 so thank you for watching if Python 3 so thank you for watching if you are still having any doubts please you are still having any doubts please feel free to ask them in the comment feel free to ask them in the comment section I will be more than happy to section I will be more than happy to answer them | 2024-03-25 17:32:10 | 1,095 | 1095. Find in Mountain Array | October | C++ | Java | Python 3 |
|
z1hcUrWQxMg | hello and welcome today we are doing another another liquid problem on binary search liquid problem on binary search okay okay so this is the problem find the positive so this is the problem find the positive integer solution integer solution for a given equation for a given equation let's see what is the problem statement let's see what is the problem statement it says that given a it says that given a given a callable function if given a callable function if y function f which have parameter X and y function f which have parameter X and Y with a hidden formula and value set Y with a hidden formula and value set okay reverse engineering the formula and okay reverse engineering the formula and return all return all positive integer pair x y positive integer pair x y where where X Y is equal to function of X Y is equal X Y is equal to function of X Y is equal to to Z okay Z okay you may return the pair in order okay we you may return the pair in order okay we have to return the pair in order let's have to return the pair in order let's see what is the see what is the explanation of this explanation of this so here we have function ID we don't so here we have function ID we don't know in in the function which formula is know in in the function which formula is used used we don't know okay so we don't know okay so the function ID is one function ID is the function ID is one function ID is one and it says that the target value is one and it says that the target value is 5. so 5. so here here if we send one by one a value from 1 to if we send one by one a value from 1 to any number okay that way we'll decide in any number okay that way we'll decide in future in the further video future in the further video uh the limit of the x or y okay uh the limit of the x or y okay the follower it says that the following the follower it says that the following positive integer x value of X and Y positive integer x value of X and Y makes make function of x y equal to 5. X makes make function of x y equal to 5. X Y X is 1 Y is 4 equal to that gives X Y X is 1 Y is 4 equal to that gives X Plus 1 that is equal to 5 yeah it is Plus 1 that is equal to 5 yeah it is equal to 5 which means it This Is The equal to 5 which means it This Is The Answer 1 comma 4 means Answer 1 comma 4 means X is equal to 1 and X is equal to 1 and Y is equal to 4 gives six five for the Y is equal to 4 gives six five for the function id1 function id1 let's understand in the both let's understand in the both we have for question is saying that we we have for question is saying that we have a custom function function which take X and Y and we have to find 5 okay suppose we have to find Target 5. 5 okay suppose we have to find Target 5. let's start let's take the limit let's start let's take the limit let's X start from 1 to let's X start from 1 to n n or we can say let's take hundred or we can say let's take hundred let's take 100. let's take 100. let's take hundred and why will you let's take hundred and why will you start from start from 1 to 100. okay what it's saying that we 1 to 100. okay what it's saying that we call the we call the function we call call the we call the function we call the function the function we call the function click on the function X and Y okay so suppose for first I is X is equal to I and Y is equal to sorry X is equal to 1 and Y is equal to 1. so if suppose let's say that let's let's take function will give will get some of two number two number but it is not the case because the function is the the rule of the function is unknown okay there is a hidden formula we don't know what is the formula inside the function but it can be addition it can be multiplication it can be division okay so let's we are taking the uh let's we are taking the function will give sum of two number okay so what this one if we suppose we are giving one comma one so suppose we are giving one comma one so what it will return it will fit to okay what it will return it will fit to okay let's check with Target let's check with Target this is equal equal to Target this is equal equal to Target this is equal equal to Target no no this is not equal to Target so let's increment the X let's increment so let's increment the X let's increment the X the X so so let's say increment rights let's take X let's say increment rights let's take X is equal to 2 now is equal to 2 now it will give 3 it will give 3 this is equal to equal to Target this is equal to equal to Target no no no no let's take let's take Y is equal to Y is equal to 3 now so Target so Target this is equal to Target no this is equal to Target no okay let's take Y is equal to 5 Y is okay let's take Y is equal to 5 Y is equal to 4 sorry equal to 4 sorry this will give now 5 this is equal to this will give now 5 this is equal to Target Target yes because Target is 5 Target is 5. it yes because Target is 5 Target is 5. it means we record the first pair we got means we record the first pair we got the first pair let's store in the answer the first pair let's store in the answer stored in the answer we got the first stored in the answer we got the first pair pair okay we got the first pair now okay we got the first pair now we we have to actually Store the store we we have to actually Store the store in the ascending order okay means in in the ascending order okay means in order means we cannot uh uh actually we order means we cannot uh uh actually we have to store in ascending order which have to store in ascending order which means means the first first means we cannot store the first first means we cannot store like this 2 comma 4 like this 2 comma 4 then 1 comma 4 because in the answer here we can see that this is in the increasing order the first letter is 1 then 2 first element is one two and three then four okay so we use this order so for this order we got the for the for this function we got the we got the Answer 1 comma 4 now now after getting the answer after getting the answer let's increment X increment X now now increment X call the function increment x x is 2 and this will start from one this will start from one means i y again start from one now this will give three which is not equal to Target now change it to the 2 so this this is not also not equal to Target not this is not also not equal to Target not equal to Target equal to Target now make it three now make it three now this will give five yeah it is equal now this will give five yeah it is equal to Target it is equal to Target so our to Target it is equal to Target so our next pair is 2 and 3 our next pair is next pair is 2 and 3 our next pair is two and three okay we got the answer we two and three okay we got the answer we got the answer okay then again increment got the answer okay then again increment X then again increment X and and increment the X let's see and this y become one again okay now this will give this will give four not equal to okay now I increment the y then 2 then this will give five which is equal to equal to Target which is equal to Target this means this means we got the another pair like three comma 2 3 comma two okay now increase the increase the 4 increase the four sorry increase the X increase the X and make Y is equal to X now become 4 and Y is equal to 1 this will give this will give 5. this will give 5. this will get 5 okay which is equal to Target so we got another pair that is 4 comma 1 that is 4 comma one this is for we got the four pair okay now after getting we increase the we increase the 5 we increase the X sorry to the five now y become what now it will give six it will give six it means it means they exceed the off it means ah every it means that if we increase whether value of x or y this will give always increasing means a larger number then Target value okay so we have to solve from up to this only oh oh let's solve this problem using binary let's solve this problem using binary search concept okay search concept okay let's take it now here one more thing there is a constraints function ID should be one two nine that is means there are nine formulas okay and the answer will generate from one to thousand between one two thousand and the value of X and Y it up to 1 2 000 okay so we are taking here x is equal to in X is equal to 1 and in y is equal to 1 okay and we are taking the answer we have to return the answer Vector of vector so we are taking this variable okay now we are looping through from we start from X up X is equal to 1 and X will is smaller than equal to thousand and it will run up to Y is smaller than equal to 1000 okay now let's find int f is equal to we call the function that is function function dot f dot f that will give X and Y which return any that will give X and Y which return any solution let's check if solution let's check if f is equal equal to f is equal equal to Z that is the target value if it is Z that is the target value if it is equal equal to Target will then our equal equal to Target will then our answer is equal to answer is equal to answer dot push pushback we have to give the Vector okay X and Y X and Y so here is it now after getting the answer we have to increment the X we have to increment the X and Y become 1 as we discussed as we discussed in the explanation okay now if if Z is greater than Z is greater than F if Z is greater than f which means which means which means that if we say that we are sending 1 comma 2 1 comma 3 1 comma or a one comma one so in this case we are getting two we are getting 3 we are getting 4 and we are getting five okay so up to here up to here up to here the the answer is smaller than Target means the answer is smaller than Target so we have to increase the Y okay we have to increase the Y here we are increasing the Y okay so we are increasing the Y so here also we increase the Y okay now else part else part else part else if Target is greater if sorry if if answer is greater suppose answer is greater here we got the answer here we got the answer that is 6 that is here we got the answer that is 6 that is 6. you got the answer 6. you got the answer that is six that is six okay okay so what we can say here so what we can say here we can increase the X we can increase we can increase the X we can increase the X okay make Y is equal to 1 okay make Y is equal to 1 okay or we can break it or break we can break or we can break it or break we can break it or we can break it okay it or we can break it okay we can break it here because there is no we can break it here because there is no use if the answer comes use if the answer comes uh uh greater than this then we can break it greater than this then we can break it but but there is an also chance but but there is an also chance I have it we can break it let's check it I have it we can break it let's check it let's check let's check if you want to break if you want to break from here from here check the answer will come here or not let's run this class solution solution okay oh sorry for the other okay we got the wrong answer why we are getting long answer so we do not need to actually break it here we can increment the X and put Y is equal to 1 okay we got wrong answer why we are getting we got wrong answer why we are getting romance so let's check our solution romance so let's check our solution okay let's check our solution yeah actually the problem is that here we are checking the if else condition uh okay actually here we are using IF else condition but we forget to give else if here okay so first we this will check this and after this condition if this condition will fail then this condition will run after that this condition Builder okay so we have made a uh the mistake that we do not put there else actually so we correct it yeah we got the correct answer okay for yeah we got the correct answer okay for two case cases let's two case cases let's submit the answer yeah now we found the characters okay | 2024-03-19 16:06:32 | 1,237 | #leetcode : Find Positive Integer Solution for a Given Equation. |
|
CAfCkBlpvkw | Jhaal 500 Hi I love you doing well 100 grams people are going to 500 Hi I love you doing well 100 grams people are going to start Elbow master sheet start Elbow master sheet is ok and for this I is ok and for this I will make a dedicated play list separately ok so this is a very will make a dedicated play list separately ok so this is a very good thing man this is a great practice good thing man this is a great practice algorithms and for interview purpose so algorithms and for interview purpose so Ashram, let's see how much we can solve Ashram, let's see how much we can solve and how much consistency we and how much consistency we can maintain and today we raise the first question, can maintain and today we raise the first question, okay like I told you that it is okay like I told you that it is very important to learn the festival, so the very important to learn the festival, so the first topic is the festival's apk file. first topic is the festival's apk file. If you have read this then refer this video otherwise there If you have read this then refer this video otherwise there is also a video of that driver is also a video of that driver of this serial, you can do it on that page so of this serial, you can do it on that page so we will see the first question of first we will see the first question of first unit character industry re 100 dec o unit character industry re 100 dec o my straight and this is my question of first my straight and this is my question of first unit character. unit character. unit character. last video I made was above on time and I had said that time is a very important topic for the purpose of interview, what kind of concept is there on time that when you don't understand anything then come and there is It is applied on everything, it is applied on every It is applied on everything, it is applied on every It is applied on everything, it is applied on every question, but the maturity of question, but the maturity of the questions which is inside the online assessment, which is the questions which is inside the online assessment, which is inside the test, it is inside the test, it is solved by SMS, okay so it is a solved by SMS, okay so it is a very important data structure at the time. very important data structure at the time. So the key stores our data for the pressure key So the key stores our data for the pressure key and this is what we and this is what we need to know. Okay, so first of all, need to know. Okay, so first of all, reading the question, first unique character in the spring gives a spring reading the question, first unique character in the spring gives a spring is finder for is finder for not repeating character and returned and foreign not repeating character and returned and foreign delegates did not have any effect. delegates did not have any effect. Exist Today - Well, do Exist Today - Well, do n't put the question first, okay, first of all, understand n't put the question first, okay, first of all, understand what the question is by asking only then you will be able to make what the question is by asking only then you will be able to make optimum use of your resources, optimum use of your resources, its ok, otherwise I will give you 500-600 its ok, otherwise I will give you 500-600 questions by mixing Saasu questions and questions by mixing Saasu questions and that later. that later. that later. given me some system, I know the list is okay, I know this is the system, I know, you have given me this trick and my spin is the list and okay, now I have a So So So before that, I will hit Inducts, before that, I will hit Inducts, take 0123 and it take 0123 and it is 536, you approach every question in the same way, is 536, you approach every question in the same way, whatever index you have given to this Tinder stuffing, whatever index you have given to this Tinder stuffing, accept it from your side, accept it from your side, then you try something further, Phone then you try something further, Phone Finder. Finder. Finder. and first not repeating character see that is repeated aapke not repeated most of which is repeating N T V F ok std od but in this the first character which is not repeating what The President, The President, The President, what will be my return on dowry? It is 208 what will be my return on dowry? It is 208 and if I do not get such an contact and if I do not get such an contact then what will I return - then what will I return - One is ok, ok now like see she One is ok, ok now like see she is my friend this also now in this repeat this repeat and more is my friend this also now in this repeat this repeat and more repeat repeat repeat not able to find any character which is not repeating, then what will I return - I will make 110, ok fine, then we will see, how could we approve this question? First of all, I am the So what will I So what will I So what will I say, I told you, I say, I told you, I will make Christmas first of all. Okay, first of all, I will make Christmas first of all. Okay, first of all, I will make one. There is time, then smell that loan, will make one. There is time, then smell that loan, Ponting Chest and I will do it. Agri Care Ponting Chest and I will do it. Agri Care Correspondent has come once. Okay, Correspondent has come once. Okay, how many times have I come? Three. how many times have I come? Three. how many times have I come? Three. keep me in the team, how many times has he come, once has come, how many times has he come, once has he come, how many times has he come, once has he come, how many times has he come, once has he come, okay, so there Now it will be done, Now it will be done, Now it will be done, I don't know how to subscribe to it, I had I don't know how to subscribe to it, I had asked three questions in the last video, with asked three questions in the last video, with great love for the prohibition, go and understand it, great love for the prohibition, go and understand it, okay, so this is a, this is okay, so this is a, this is my last message, okay, this is my his my last message, okay, this is my his weapon, what is NDTV COD, we are one weapon, what is NDTV COD, we are one weapon, what is NDTV COD, we are one point the first unit character in it, then how will I point the end in the first unit character? Which contact of mine is the President? Zero Intex Service Center, so it is okay, so what will go in my answer, it will come in my answer, it is okay Zero will come, okay, A will Zero will come, okay, A will Zero will come, okay, A will come in my answer. Okay, so let's come in my answer. Okay, so let's try to court him. First of all, try to court him. First of all, what has happened? It happened on time, okay, what has happened? It happened on time, okay, alert map in unwanted, okay is aroma alert map in unwanted, okay is aroma int okay, take care of me. int okay, take care of me. int okay, take care of me. MP is ok, I have made it, now what will I do after that for ITI course 208 Lenin I Plus Plus Ameer has entertained you, what is my and when is that, what is the size of my spring, the I I I will update on this and get its mapping shown. will update on this and get its mapping shown. Plus Plus of MP offices. Plus Plus of MP offices. What have I done here? No, but I have created it in debate. What have I done here? No, but I have created it in debate. Okay, here I have created a Okay, here I have created a smell. Okay, smell. Okay, what should I do now? What should I do now? I have had enough of that. what should I do now? What should I do now? I have had enough of that. Which of my inductions means look, Which of my inductions means look, rather support cricket, that point, the rather support cricket, that point, the first thing which is unique is the loan repeating, that is first thing which is unique is the loan repeating, that is this, so what return will we get for it, will we get the this, so what return will we get for it, will we get the induction done, then again I will induction done, then again I will hydrate on my skin. hydrate on my skin. hydrate on my skin. ID is equal to zero on the first day, plus plus, now what will I put this condition inside it, if whatever is mine inside my map, okay, whatever is my character inside yours, okay, whatever is my character inside yours, its frequency is one, okay, that is what it its frequency is one, okay, that is what it means. means. means. look at MP on Facebook, what is there in MP, this is the complete map of MP, what is the help on SFI 100, MP of a lamp of calculus, one and a half inches youth is fine, so if my first character is I will get him back, I will get I will get him back, I will get I will get him back, I will get his tax return done his tax return done and if it doesn't happen for me, then even after doing all this, and if it doesn't happen for me, then even after doing all this, if nothing happens for me, then if nothing happens for me, then I will get him returned - Okay, I hope I will get him returned - Okay, I hope you have understood, okay now you are you have understood, okay now you are SFI. SFI. SFI. can use that also, it is not used, this is the only way for us, okay, so let's and tell us whether it happens while watching the digit chapter and tell us whether it happens while watching the digit chapter or not, and Udan also submitted, so okay, Udan also submitted, so okay, Udan also submitted, so okay, first of all, what did I do, I first of all, what did I do, I made it in my hair, okay, I made it in gas, made it in my hair, okay, I made it in gas, and then and then I checked every character, the I checked every character, the first event was held on S0, is God first event was held on S0, is God in like and comment? in like and comment? in like and comment? MS Word, what is my lion's zero, is it less than my side, how much is the size, calculate here, how much is the size, but the kid is 34567, now the scalp hangs to the manager or again to the poison, Lead so 8 Lead so 8 Lead so 8 Mera Shahjahan This zero is my work with add here Mera Shahjahan This zero is my work with add here Now this is what is the zero of mine Now this is what is the zero of mine Okay is such a zero What is my Enter MP4 is Okay is such a zero What is my Enter MP4 is full One is mine Yes is a Mere ko full One is mine Yes is a Mere ko first time which was MP of hair first time which was MP of hair first time which was MP of hair strength that now I have found the first character, what is its frequency, which is not a repeating character, it is ok and who is that one, then what will I return, I will return pal1 Despite doing so much, I am Despite doing so much, I am Despite doing so much, I am not getting the answer, so not getting the answer, so what will I return - I will return one what will I return - I will return one and if we look at its time complexity, and if we look at its time complexity, then its time complexity is then its time complexity is stupid, then it is okay, it is stupid, and stupid, then it is okay, it is stupid, and space complexity. space complexity. space complexity. complexity, why did it become a stupid man? Vikash Bihar is using this map to get that power data and process it, so come home, the question is page, thank | 2024-03-24 12:01:08 | 387 | Leetcode 387 : First Unique character in a string | C++ | Algo Master Sheet |
|
VpkTcCg6F-c | hey guys welcome back to the Advent and this is Nixon today we are going to this is Nixon today we are going to solve a new problem from lead code it is solve a new problem from lead code it is the 145th problem binary tree post order the 145th problem binary tree post order traversal given the root of a binary traversal given the root of a binary tree return its post order traversal of tree return its post order traversal of its notes value let me explain this its notes value let me explain this problem guys and before solving this problem guys and before solving this problem we just need to know about what problem we just need to know about what is binary tree and what are all the is binary tree and what are all the components available on binary tree and components available on binary tree and what are the traversal methods available what are the traversal methods available on binary tree if you don't about binary on binary tree if you don't about binary tree data structure please go through tree data structure please go through some videos about binary tree data data some videos about binary tree data data structures and and then come to solve structures and and then come to solve this problem guys now let us get into this problem guys now let us get into the problem initially we will be given a the problem initially we will be given a root of a binary tree and what we have root of a binary tree and what we have to do is we just need to Traverse that to do is we just need to Traverse that complete binary tree using post order complete binary tree using post order traversal methods what is a post order traversal methods what is a post order traversal postorder traversal is a traversal postorder traversal is a traversal methods of binary tree and traversal methods of binary tree and what what is the concept used in post what what is the concept used in post order traversal is nothing but it start order traversal is nothing but it start it traversing from the left value and it traversing from the left value and then it go to to the right value moves then it go to to the right value moves through the right value and then at last through the right value and then at last it comes to the root root of the binary it comes to the root root of the binary tree this is the concept first initially tree this is the concept first initially it will be go to the I mean initially it it will be go to the I mean initially it will go to the left left of the binary will go to the left left of the binary tree and then it go through the right of tree and then it go through the right of the binary tree and then it end up with the binary tree and then it end up with the root value root of the binary tree the root value root of the binary tree this is this is the concept this is the this is this is the concept this is the traversal method uh followed on post traversal method uh followed on post order traversal method now what I'm order traversal method now what I'm going to do is I'm just going to create going to do is I'm just going to create a universal list and then what I'm going a universal list and then what I'm going to do is I'm just I just solve this to do is I'm just I just solve this problem using a recursive option so I'm problem using a recursive option so I'm creating a I'm just going to create a creating a I'm just going to create a new uh recursive function and then I'm new uh recursive function and then I'm just going to Traverse this complete just going to Traverse this complete binary tree from the left side and then binary tree from the left side and then I'll go through the right side and I'll I'll go through the right side and I'll be end up with the root node this is the be end up with the root node this is the concept I'm going to follow now let us concept I'm going to follow now let us solve this problem guys now as I told solve this problem guys now as I told I'm creating a universal I'm creating a universal list here yeah now I'm just going function function start yeah [Music] and then I'm going to check whether the root root equal to null or not it's going to return here then what I'm going to do is post order first I'll Traverse the left right side of the binary tree and then just going to Trav the right side of the minary tree and and then I am adding the value on the root here what I'm going to do is I'm just here what I'm going to do is I'm just call the recursive function here and then I'm going to return the yeah yes got guys yeah guys anded successful thanks for watching please do subscribe to the Advent and if you had any suggestions please don't hesitate to comment us guys bye-bye | 2024-03-21 12:50:24 | 145 | 145. Binary Tree Postorder Traversal | Leetcode | Tree | The Advent |
|
I8h_hI_BF3Y | of D link list is easy level question is ok 76 ok so let's see it is quite popular in my respect company is ok Amazon Microsoft Flipkart Johan me peacock is ok and many more we have not mentioned So you So you So you go to my GitHub wrap, go to my GitHub wrap, I have mentioned it in the description also. Okay, so let's I have mentioned it in the description also. Okay, so let's see the question. It is a very simple see the question. It is a very simple question, you must have been given a link list, right? question, you must have been given a link list, right? You have to return the middle load. You have to return the middle load. Which is the middle note? Which is the middle note? Here it is five and it is of OD size. Here it is five and it is of OD size. If we take main and size then If we take main and size then its middle is two. And if we have to its middle is two. And if we have to return the second one in size return the second one in size then the second one will become three in this. then the second one will become three in this. then the second one will become three in this. is fine for us, like we take main, if six notes are is fine for us, like we take main, if six notes are 1234 56, then the middle two will go in this, otherwise we have to send it to the other one, okay, we take main, there are punches, one, two, three, four punches, Let's Let's Let's see how we can solve this. see how we can solve this. Okay, so see, the first approach is that Okay, so see, the first approach is that this will come in your man, and there is a very simple this will come in your man, and there is a very simple approach too that we take your man, we have given a linked approach too that we take your man, we have given a linked list, one is three four, one is three list, one is three four, one is three four, then it is the best. four, then it is the best. four, then it is the best. iterate or track it and find out the size. Okay, will be the size? Keep a counter so that will be the size? Keep a counter so that as soon as I come to the second one, I will stop the counter as soon as I come to the second one, I will stop the counter and return it. Okay, so and return it. Okay, so one thing is simple. one thing is simple. one thing is simple. in this you are paying attention, you are highlighting it twice, on your link list, you find out what will be the medal element. find out what will be the medal element. Okay, so see friend, Okay, so see friend, in the question, I told you the method one in which in the question, I told you the method one in which What do we do, a slope pointer What do we do, a slope pointer What do we do, a slope pointer does that and a fast pointer does that, does that and a fast pointer does that, okay, this is called hair and okay, this is called hair and break toise approach, also called linked list, okay, how can we make it, see, you already knew that slow fast pointer. How to move the slope pointer used to move one step and the fast pointer used to move one step right so slow is here If you move If you move If you move one point or one step then slow will come one point or one step then slow will come here but fast one will here but fast one will move two steps or fast will come here move two steps or fast will come here ok ok sorry fast has come here so now we have come here and fast will do two main and fast will do two main and fast will do two main come here and then here, neither is the slow one here, nor is the fast one here, so after this we cannot move forward because there is nothing else before fast. Okay, so the note. see whether it is reducing here or see whether it is reducing here or not, okay, our slow was here, fast not, okay, our slow was here, fast was here, slow came here, fast came here, we have to face two faces, fast has come out of here, look, We have stopped and this is We have stopped and this is We have stopped and this is also our answer, okay, so there will be a very simple also our answer, okay, so there will be a very simple code like this, what will happen is that slow mine will code like this, what will happen is that slow mine will start from the head, okay how long will we run, okay, then what will we do, we will increase the slope once. okay, then what will we do, we will increase the slope once. Fast is equal to you fast is next to next and what is the guarantee that it will not break this code will not break because look we have checked that ok if we go out then we will return slow ok if we go out then we will return slow simple returns slow thinks it simple returns slow thinks it simple returns slow thinks it very simple question? Okay, but it is popular and you need more of this technique. This is a slower fast technique. It doesn't take up much space, so let's code it. Okay, so the question is simple. It's the Linked list is given, you have to Linked list is given, you have to Linked list is given, you have to find the middle, okay, the solution comes directly, I don't think it will take find the middle, okay, the solution comes directly, I don't think it will take more time, it is more time, it is quite simple, what I said was quite simple, what I said was that I will create a slope pointer which will that I will create a slope pointer which will point to the head and a fast point is point to the head and a fast point is created which is created which is created which is then what did I say that till the time fast is not equal takes one step and the one who is fast takes two steps, fast is next to next and so on. I told you that we don't have a fast connection, that's why we are using the next infrastructure, right, and in the end, what do we have to do, nothing else, just return it to slow, slow will be automatically Let's Let's Let's run and see the example test run and see the example test cases. You should pass. Submit it and cases. You should pass. Submit it and see. video. Thank you. | 2024-03-22 17:29:18 | 876 | Middle of the Linked List | Hare and Tortoise | Leetcode 876 |
|
rrW8F1FgzrI | [Music] hi hello so today we'll talk about top hi hello so today we'll talk about top key frequent element key frequent element so given an integer ray nums an integer so given an integer ray nums an integer k k we have to return k we have to return k most frequent elements most frequent elements and the answer could be in any order so and the answer could be in any order so let's understand with an example so let's understand with an example so if if we have in this example we have three we have in this example we have three one one one is repeated three times two repeated one is repeated three times two repeated two time and three once two time and three once and they're and they're asking that find asking that find tell us two tell us two most frequent element most frequent element we can see we can see one repeated tries two twice and three one repeated tries two twice and three one one so these are the two most frequent so these are the two most frequent elements so we will return the answer elements so we will return the answer one and two one and two let's better understand let's better understand all right so all right so in this question we have to tell k in this question we have to tell k most most frequent frequent elements now what we already know so elements now what we already know so what is noun to us what we know already what is noun to us what we know already we know that there we know that there when we have some collection when we have some collection and from that collection kate and from that collection kate element is expected element is expected so we can go with so we can go with top k element top k element coding pattern now in this question they coding pattern now in this question they have some collection have some collection and they were expecting and they were expecting k k most most frequent elements so we can go with frequent elements so we can go with top k element coding pattern let's see top k element coding pattern let's see how we can go how we can go how we can implement that take some how we can implement that take some example let's suppose example let's suppose this is four four four this is four four four two two two two and three four is repeated and three four is repeated three time three time two repeated two time and three is only two repeated two time and three is only repeated once repeated once so we can see this is three to one so we can see this is three to one and most frequent and most frequent and like answer should be four and two and like answer should be four and two answer answer two and four is also correct because two and four is also correct because order is not expected we already know order is not expected we already know that that for solving top k element what are the for solving top k element what are the steps the first we already talked about steps the first we already talked about that we have to decide that we have to decide min min or or maxi in second we will consider maxi in second we will consider what are the bases what are the bases like what are the grounds on which like what are the grounds on which something is considered most something is considered most frequent frequent or largest or smallest or something or largest or smallest or something third that we have to iterate third that we have to iterate on on it is some iteration so the the this is it is some iteration so the the this is the whole block diagram for top key the whole block diagram for top key element if if you look here element if if you look here so they're providing us these number of so they're providing us these number of elements elements and they were asking that which are most and they were asking that which are most k most frequent element you have to k most frequent element you have to pretend to answer this pretend to answer this now now if we make a map let's suppose we can if we make a map let's suppose we can say 4 say 4 is repeated 3 time is repeated 3 time 2 2 is repeated 2 time and 3 is repeated 1 is repeated 2 time and 3 is repeated 1 time time so this is so this is we can see that this is a number we can see that this is a number and that is and that is its count its count right right and if we can make some and if we can make some like oh like oh the first thing we will decide the first thing we will decide that either we have to use that either we have to use min heap or maxip so k min heap or maxip so k most frequent element we will use some most frequent element we will use some min here min here but so the first thing is clear but so the first thing is clear now the second now the second what are the bases what like we how we what are the bases what like we how we will order that mean heat or maxi will order that mean heat or maxi so they're asking k most frequent so they're asking k most frequent so that should be so that should be the the ground for ordering so order by the ground for ordering so order by the count count we will order by account we will order by account and that is their expected result so and that is their expected result so answer by this so that is the answer answer by this so that is the answer what they are expecting what they are expecting and we will order and we will order by overheat by overheat using using this count so we will order by count and this count so we will order by count and answer would be expected in this answer would be expected in this so what so what we can do we can make some map we can do we can make some map a map of num a map of num and count so let's suppose like we can and count so let's suppose like we can use tuple but use tuple but for the sake of simplicity we can see for the sake of simplicity we can see that we can say we can make a class that we can say we can make a class which has which has now now and and it has account and we will make a map that map will keep class sorry uh that it will be num count so that map will keep num and and that will be the basis so we will order that will be the basis so we will order by this and the third by this and the third we will iterate we will iterate as we were doing before as we were doing before now let's see how we can code this now let's see how we can code this question all right so we already know we are going to solve this question using top k element coding pattern and we know the template how we have to use it so first step we will decide either we have to use min heap or maxi in the second phase we will uh we will fill our heap feel heap and keep k element and third we would return required required answer now to follow the same step first we will talk about either we have to use a min heap or maxip they're expecting k most frequent element so we will use min heat its ordering is dependent on what we already talked about that its ordering could be abandoned on the count of numbers so we can make a class let's suppose case class num count and the first element would be none and second element would be count so we will make a priori queue of num count ordering by ordering by count count so we so we order by account the main heap order by account the main heap and and now now we talk about that we need something we talk about that we need something that that some mapping that says some mapping that says uh that this character has this uh that this character has this frequency this character had this frequency this character had this integer has this integer has this frequency so we will prepare that that frequency so we will prepare that that map map we say map we say map that would be that would be nums dot nums dot group group by by identity identity uh in scala so what is this identity uh in scala so what is this identity means it's a means it's a like a morphism you can say x arrow like like a morphism you can say x arrow like arrow goes from x to x again arrow goes from x to x again so that is that is its identity so it so that is that is its identity so it means 2 is 2 means 2 is 2 3 is 3 so they are that is their 3 is 3 so they are that is their identity identity so scala so scala in from that array in from that array group them by the identity group them by the identity and then we say and then we say map map values values by size whatever the group by size whatever the group size you have we will make the value so size you have we will make the value so actually this will create a map map that would let's suppose in our case we have an example of one one one two two and three and that make our map like this make our map like this where where one says i have count of three two says one says i have count of three two says i have count i have count two and three says my count is on two and three says my count is on now once that map is ready we will keep now once that map is ready we will keep on going with the second step we will on going with the second step we will say map dot for each say map dot for each we will iterate on it and we will say we will iterate on it and we will say because when we i trade we get num because when we i trade we get num it is a key value we say num and it's it is a key value we say num and it's count count that's a key that's a key and that's value so we were saying num and that's value so we were saying num and and count and here we will say min heap and q and q and we will make our and we will make our non count class i can save even in tuple non count class i can save even in tuple but for the sake of readability i'm just but for the sake of readability i'm just using num count using num count so i can say num and count so i can say num and count now in the next step we will check if now in the next step we will check if min min heap dot size is greater than k heap dot size is greater than k if the size increase if the size increase from from the required size of k the required size of k we will decay we will decay and finally we have to return the answer and finally we have to return the answer i already told you about i already told you about uh first thing that like we already talked about that we have to order by the count but we have to return the answer so to currently in the mean heap we have num count so we need num not the count so we will say min e dot map map the values with num and make it an array i think i also forgot to ins import because import scala dot collection not mutable now if i run the code that's it | 2024-03-24 11:10:35 | 347 | 3. Top K Element | Leetcode | 347 | Top K Frequent Elements |
|
ehuSoUJ4Bfk | Hello friends uh welcome to my channel let's have a look at problem 297. let's have a look at problem 297. she realized and the serialized binary she realized and the serialized binary tree this problem or this video is a tree this problem or this video is a follow-up for problem follow-up for problem 652 so here we practice both 652 so here we practice both serialization and this serialization serialization and this serialization so in between we are going to use so in between we are going to use recursion here for Simplicity or recursion here for Simplicity or neatness neatness so so this problem asks us to do serialization this problem asks us to do serialization or deserialization of banner tree or deserialization of banner tree so here are two examples for example so here are two examples for example this example one so it can this is a this example one so it can this is a tree structure and example two is an tree structure and example two is an edge case which corresponds to a null edge case which corresponds to a null tree the constraints for this problem tree the constraints for this problem are the following first the number of are the following first the number of nodes in the tree is in the range given nodes in the tree is in the range given by the closed interval 0 to 10 to the by the closed interval 0 to 10 to the power 4 and the node value is in between power 4 and the node value is in between negative one thousand and positive 1000 negative one thousand and positive 1000 so with that said let's look at the code so with that said let's look at the code so here we are given a class called so here we are given a class called codex so this class uh the problem asks codex so this class uh the problem asks us to fill up two methods one is us to fill up two methods one is serialized and the other is the reverse serialized and the other is the reverse the D serialized the D serialized so here unlike problem so here unlike problem 652 we need to also take this 652 we need to also take this serialization into consideration when we serialization into consideration when we do serialization do serialization so this actually is slightly more so this actually is slightly more demanding comparing with problem 652 demanding comparing with problem 652 so here first we are going to do serial so here first we are going to do serial addition with the help of traversal so addition with the help of traversal so here we can use depth first search as in here we can use depth first search as in problem 652. problem 652. so for the first method we're going to so for the first method we're going to do the similar thing as in problem 652. do the similar thing as in problem 652. um first I'm going to initialize a um first I'm going to initialize a result variable which is an empty list result variable which is an empty list so we are going to write a DFS function so we are going to write a DFS function or a worker to modify this one and then or a worker to modify this one and then later we do string John on this results later we do string John on this results list to get the representation of the list to get the representation of the whole tree whole tree so with that overall structure done now so with that overall structure done now let's first look at the hyper function let's first look at the hyper function so here I'm going to use the fs again so so here I'm going to use the fs again so which accepts in three node that is root which accepts in three node that is root and an argument name and then first if and an argument name and then first if not root not root in other words so we are meeting a mouse in other words so we are meeting a mouse so in this case so we can pinch the so in this case so we can pinch the result with some special string let's result with some special string let's say now or none so let's use a comma so say now or none so let's use a comma so this comma is used to distinguish digits this comma is used to distinguish digits so you you notice that soon so here so you you notice that soon so here let's return if this is the case so let's return if this is the case so otherwise so we're going to otherwise so we're going to um um first add this first add this string representation of the node value string representation of the node value to the result so this is string to the result so this is string let's add root value and then let's also add a comma here so to distinguish digits and then we do the that first search in the left subtree and the restore tree recursively so let's call this function DFS root left and DFS root right so this way after we finish this recursion we're going to get a result a list which can be regarded as a representation but in a list format so then we just need to do string drawing method so as we have already initialized the results variable so we don't need to do here now we just call this function right DFS root so after that so actually we can return the full screen so we are going using string join method so here the separator is um empty string or empty scene so here we get the results so this is what we return so actually here we can add something we can print out the result or this jaunt uh string so this is the serialization so with this theorization method we can write a deserialization function let's do this here um so here we are going to first Define a hyper function which is going to do the split and do building the to build the tree so here and then we are going to call this function and then we are going to finally return this result so first I'm going to define a hyper function so this is the Builder right so first let's undo this one if on Q naught so is um so here Q you can see you can think of Q at the list here before the joining right so if Q naught is um as now so then we are going to do pop left and then we are going to return so the reason here we use this now because lastly place the data into this kind of format where the separator for this split will be the comma right so we just have not with no comma so this is the one step otherwise the first one Q naught will be a number so corresponding to a number let's see um what we are going to do is um we're going to write the root will be our tree node so the value will be pop left so this one or you can regard it as a string so it should be um still okay and then um what we are going to do next is to call this helper function recursively if actually following the here similar way so L will be um helper 2. so because of here we are using pop actually the stage of the um the skill changed right yes hyper q and then we're going to set the root of left to be left and root right to be red and then we are going to return the tree so this is the hyper function so which accepts a list of strings so with this function ready so now what we are going to do first we get to the list right so we are going to let's write it like this so list so we're going to get split so here as we used a comma as separator so here in the separate Direction comma again and then we're going to in order to use pop left or pop right or pop from the right so let's first make build collections on Deck so we can make a deck out of this list and then we're going to make out of similarly we can print the um the queue and then what we are going to do is to return to help her oh Q so this is the ROV of doing the um doing the D serialization so let's first do a it passes one example now let's look at it passes one example now let's look at the generic case it passes all the general cases so here advancing I guess at Melody interesting is that we can change this one to be Let's test again Let's test again yeah so it also passes so because here we are actually use some tab conversion like here string so here we can reach inch so meanwhile so we can do the print so here you will see the serialization and deserialization procedure more clearly so let's see this is the tree corresponding to this here one two three four five so we're going to get something like this so this is the list before John so if we join we are going to have a string long string like this and then when we input this string format of this list into the destroyalization function or method so after we do this step we do a split so we're going to get something like this right so here if we do not put integer here the value will be in a string format but um in a proper sense maybe it's better to change it to be um um integer but you know it's not a big problem here because this um is not very strong in tab so with that stage I guess that's about it for this specific problem so here the thing is that so when we do a serialization we need to keep in mind so this sterilization so because this serialization method depends on how we do serialization so here in both the two methods so we used um recursion so this actually um is very neat or in some sense we we actually which actually which actually hits some details but if you prefer I'll hits some details but if you prefer I'll encourage you to write encourage you to write um the two method in um um the two method in um in the iterative format so for this one in the iterative format so for this one it's it's not not hard at all so it's it's not not hard at all so similarly with some effort writing a similarly with some effort writing a recursive format for this one is not not recursive format for this one is not not easy if we are very familiar with when easy if we are very familiar with when retreat traversals retreat traversals so with that said I guess that's about so with that said I guess that's about it for this specific problem in this it for this specific problem in this video thank you | 2024-03-22 14:34:38 | 297 | leetcode 297. Serialize and Deserialize Binary Tree - (de)serialization |
|
WXPmTShiFcI | hey everyone welcome back and today we'll be doing another lead code four we'll be doing another lead code four one four third maximum number and easy one four third maximum number and easy one given an integer array numbers one given an integer array numbers return the return the district maximum number in this array if district maximum number in this array if the third maximum does not exist return the third maximum does not exist return the maximum number the maximum number so in this case you can see here like so in this case you can see here like three to one the third maximum is one three to one the third maximum is one and in this case where there is no third and in this case where there is no third element you can just return the maximum element you can just return the maximum so there are many methods to do this but so there are many methods to do this but what we'll be doing is just making a set what we'll be doing is just making a set then making that set into a list and then making that set into a list and then sorting that list and after that then sorting that list and after that we will see if it's its length is less we will see if it's its length is less than than two three yes if the if less length is two three yes if the if less length is less than or equal to two less than or equal to two uh then what we'll be doing is just uh then what we'll be doing is just returning the last index otherwise returning the last index otherwise values at la da at the last index values at la da at the last index otherwise it will be returning in any otherwise it will be returning in any case if it is larger than three or equal case if it is larger than three or equal to to the third the third last index so that's it last index so that's it so we will be making a num list list and then setting the nums so we can get rid of the duplicates so then after we are done with this we can just sort sort ok we will sort so if length of nums is less than or equal to 2 we can just return the last index value otherwise we can just return index value otherwise we can just return nums at the very last so that's it this nums at the very last so that's it this should work you | 2024-03-22 10:54:08 | 414 | 414. Third Maximum Number | Leetcode | Python |
|
z9e-tGD7Z8g | so question 76 of leake code minimum window substring so given two strings s window substring so given two strings s and t of lengths m and n respectively and t of lengths m and n respectively return the minimum window substring of s return the minimum window substring of s such that every character in t including such that every character in t including duplicates is included in the window if duplicates is included in the window if there is no such substring return the there is no such substring return the empty string empty string so the test cases will be generated such so the test cases will be generated such that the answer is unique a substring is that the answer is unique a substring is a contiguous sequence of characters a contiguous sequence of characters within the string so in the first within the string so in the first example example we have adobe code bank and t is equal we have adobe code bank and t is equal to abc to abc so we need to find the shortest so we need to find the shortest substring with an s that contains all substring with an s that contains all the values of t the values of t so in this there are multiple substrings so in this there are multiple substrings but the shortest one is bank which is but the shortest one is bank which is found at the end here found at the end here containing one b one a containing one b one a and one c and that is the output that we and one c and that is the output that we need to give in the second example we need to give in the second example we have a as the output have a as the output because because t contains only one a t contains only one a the string itself only contains one a so the string itself only contains one a so that meets the requirement so it meets that meets the requirement so it meets all of the values that are in t all of the values that are in t within the string of s within the string of s and finally in example three we have an and finally in example three we have an answer of an empty string and the reason answer of an empty string and the reason for that is is t length is greater than for that is is t length is greater than the length of s so we will never find the length of s so we will never find two instances of a within a string that two instances of a within a string that only contains one a so could you find an only contains one a so could you find an algorithm that runs in om plus n time so algorithm that runs in om plus n time so let's discuss a potential solution with let's discuss a potential solution with that time complexity so this is a pretty that time complexity so this is a pretty difficult question and there's so much difficult question and there's so much to take into consideration here and to take into consideration here and especially with the fact that we've got especially with the fact that we've got a hit om plus n time complexity so with a hit om plus n time complexity so with this time complexity we can have a this time complexity we can have a trade-off so we can increase our space trade-off so we can increase our space complexity in order to hit this time complexity in order to hit this time complexity complexity and one great way of utilizing more and one great way of utilizing more space to improve time complexity is by space to improve time complexity is by using something like a map data using something like a map data structure when comparing two values so structure when comparing two values so we're going to have we're going to have a frequency map a frequency map that is going to store that is going to store all the values of t and the amount of all the values of t and the amount of their occurrence so their occurrence so we're going to have a we're going to have a which is pointing to one b which is pointing to one b which also has one and c is also going which also has one and c is also going to be equal to one to be equal to one right and the great thing about right and the great thing about frequency maps or map data structures is frequency maps or map data structures is they have constant lookup we can say they have constant lookup we can say that this map is the m within this time that this map is the m within this time complexity and this n we can actually complexity and this n we can actually update that to be s update that to be s and that's going to be this string right and that's going to be this string right here that we're going to loop through here that we're going to loop through and because we're only allowed to loop and because we're only allowed to loop for it once a great technique that we for it once a great technique that we can use is the two pointer technique can use is the two pointer technique where we have a left and right pointer where we have a left and right pointer that way rather than traversing the that way rather than traversing the string multiple times and increasing the string multiple times and increasing the time complexity to something quadratic time complexity to something quadratic we can keep it linear we can keep it linear and compare values together so how this and compare values together so how this solution is going to work we're going to solution is going to work we're going to loop through this string we're going to loop through this string we're going to check check at each point whether the value that at each point whether the value that we're on is within the frequency map if we're on is within the frequency map if it is we're going to decrement the value it is we're going to decrement the value associated with that letter and once the associated with that letter and once the frequency map is all equal to zero we frequency map is all equal to zero we then know we have found a substring then know we have found a substring within the string of s so we can update within the string of s so we can update our minimum window substring so before our minimum window substring so before we do that we need a couple more we do that we need a couple more variables to take into consideration variables to take into consideration so we need a count which is going to be so we need a count which is going to be equal to equal to the size of this frequency map which is the size of this frequency map which is three and we also need to declare three and we also need to declare our minimum window which is going to be our minimum window which is going to be set initially set initially as an empty string as an empty string and the great thing about setting it as and the great thing about setting it as an empty string is it takes care of that an empty string is it takes care of that case where we do not find a substring case where we do not find a substring within the string s because we're going within the string s because we're going to be returning this so we will return to be returning this so we will return an empty string so let's give this an empty string so let's give this solution a run free at our right pointer solution a run free at our right pointer we have the letter a is a within the we have the letter a is a within the frequency map yes it is so what do we do frequency map yes it is so what do we do we decrement a we decrement a to zero to zero now once a now once a or any of these values point to zero we or any of these values point to zero we can decrement the count because we have can decrement the count because we have found all occurrences of that letter found all occurrences of that letter within the substring that we're looking within the substring that we're looking for so we found all the currencies of a for so we found all the currencies of a so we can decrement the count we only so we can decrement the count we only need to find two more letters need to find two more letters b and c b and c in order to find in order to find a potential solution now we can a potential solution now we can increment the right pointer so increment the right pointer so right pointer moves to d d is not in the right pointer moves to d d is not in the set we move over to o set we move over to o o was not in the set we move to b b is o was not in the set we move to b b is within the set so we decrement b within the set so we decrement b b goes to zero so we found the required b goes to zero so we found the required amount of b within our string amount of b within our string so we can decrement count now so we can decrement count now so count goes to one and we can so count goes to one and we can increment the right pointer so we go to increment the right pointer so we go to e is not within the map so we can move e is not within the map so we can move along we go over to c along we go over to c c is within the map so we decrement c c is within the map so we decrement c and now c is equal to zero so we and now c is equal to zero so we decrement the count and we move the decrement the count and we move the right pointer along one more now here is right pointer along one more now here is where we have to add additional logic where we have to add additional logic because count is equal to zero we have because count is equal to zero we have found all the currencies of a b and c so found all the currencies of a b and c so we have found we have found one a one b and one c those are the one a one b and one c those are the requirements that are needed for t requirements that are needed for t within this substring so we have within this substring so we have a b and c so we have this a b and c so we have this as a substring as a substring and i say it's adobe c rather than adobe and i say it's adobe c rather than adobe c o because we are going to slice from c o because we are going to slice from the left pointer to the right pointer so the left pointer to the right pointer so s dot slice left right s dot slice left right is going to give us adobe c because the is going to give us adobe c because the right value here within slice is right value here within slice is non-inclusive okay great so we have non-inclusive okay great so we have found a substring a potential solution found a substring a potential solution so we need to update the minimum window so we need to update the minimum window to that solution but we have another to that solution but we have another issue here we have an empty string here issue here we have an empty string here and usually what we do in a case like and usually what we do in a case like this is we compare the minimum length of this is we compare the minimum length of the minimum window with the minimum window with the length of this substring we have the length of this substring we have but we can't do that here because the but we can't do that here because the minimum window is much shorter than the minimum window is much shorter than the substring substring and it will always be the result so we and it will always be the result so we need to create another variable so we need to create another variable so we have a len variable and this is going to have a len variable and this is going to be set initially to infinity so whatever be set initially to infinity so whatever length substring we have as our initial length substring we have as our initial substring substring it will always be less than that so it will always be less than that so minimum window will always update to the minimum window will always update to the first substring we find first substring we find so we can do that now so we can do that now we can update our substring to equal we can update our substring to equal adobe c and now we have to carry out a adobe c and now we have to carry out a slide-in window technique in order to slide-in window technique in order to increment the left pointer to find all increment the left pointer to find all possible substrings within this string possible substrings within this string so while count is equal to zero we check so while count is equal to zero we check the map the map if the map has if the map has the value at the left pointer so it has the value at the left pointer so it has a so we increment a to one a so we increment a to one and if this value increases or if any of and if this value increases or if any of these values increase above zero we can these values increase above zero we can increment the count basically saying increment the count basically saying that we need to find that we need to find one occurrence of a to find another one occurrence of a to find another substring now and we can increment the substring now and we can increment the left pointer so once we have done that left pointer so once we have done that we can repeat the process with the right we can repeat the process with the right pointer so we can check if o is within pointer so we can check if o is within the frequency map it's not so we can the frequency map it's not so we can move that along d is not within the move that along d is not within the frequency map is not within the frequency map is not within the frequency map so we get to b b is within frequency map so we get to b b is within the frequency map and what do we do when the frequency map and what do we do when we find a value within the frequency map we find a value within the frequency map we decrement it so b moves to minus one we decrement it so b moves to minus one now usually we decrement count but b is now usually we decrement count but b is not equal to zero b is equal to minus not equal to zero b is equal to minus one so we have two occurrences of b one so we have two occurrences of b within the substring so we do not within the substring so we do not decrement count because the only value decrement count because the only value we're currently looking for is a we want we're currently looking for is a we want to decrement this to zero so we can just to decrement this to zero so we can just carry on we can move the right pointer carry on we can move the right pointer to a we have finally found a we can to a we have finally found a we can decrement that to zero and now we can decrement that to zero and now we can decrement count to zero we can increment decrement count to zero we can increment the right pointer and now that count is the right pointer and now that count is equal to zero we have found another equal to zero we have found another substring so d substring so d all the way through to a here so we have all the way through to a here so we have a we have b and we have c we can check a we have b and we have c we can check if this is less than the minimum window if this is less than the minimum window it's not so we'd carry out the slide in it's not so we'd carry out the slide in window technique we checked to see if window technique we checked to see if this point here is within the frequency this point here is within the frequency map it's not map it's not we move it along we move it along o is not within the frequency map b is o is not within the frequency map b is within the frequency map so we increment within the frequency map so we increment b so this goes to zero however b so this goes to zero however b is not greater than zero so we do not b is not greater than zero so we do not increment count because remember we increment count because remember we still have an instance of b over here so still have an instance of b over here so we move the left pointer along to e that we move the left pointer along to e that is not within the frequency map we move is not within the frequency map we move it along to c it along to c that is within the frequency map so we that is within the frequency map so we update c to one and now c is greater update c to one and now c is greater than zero we can increment count then we than zero we can increment count then we can increment the left pointer and now can increment the left pointer and now we can repeat the process on the right we can repeat the process on the right side side so is n within the frequency map no it's so is n within the frequency map no it's not so we move the right pointer along not so we move the right pointer along right is at c right is at c c is within the frequency map so we c is within the frequency map so we decrement c decrement c great that's now equal to zero we great that's now equal to zero we decrement count now count is equal to decrement count now count is equal to zero so we have a current zero so we have a current minimum window substring which is equal minimum window substring which is equal to to this string right here is this less than this string right here is this less than adobe c no it's not adobe c no it's not so we check the left pointer we see if so we check the left pointer we see if that's within the frequency map no it's that's within the frequency map no it's not we move along not we move along we now have a new substring we now have a new substring which is equal to this substring is that which is equal to this substring is that less than the minimum window no it's not less than the minimum window no it's not so we increment the left pointer and we so we increment the left pointer and we check if the left pointer is within the check if the left pointer is within the frequency map no it's not but at this frequency map no it's not but at this point we have a new window substring point we have a new window substring ebank is that less than minimum window ebank is that less than minimum window yes it is so we can update that yes it is so we can update that to be equal to ebank now we check to see to be equal to ebank now we check to see whether e is within the frequency map whether e is within the frequency map it's not so we move the left pointer it's not so we move the left pointer along we now have a new substring along we now have a new substring which is equal to which is equal to bank bank and that is less than e bank so we can and that is less than e bank so we can update that and we check to see whether update that and we check to see whether b is within the frequency map it is so b is within the frequency map it is so we update b to one we update b to one b is now greater than zero so we update b is now greater than zero so we update count to one and then we increment the count to one and then we increment the right pointer and then that is out of right pointer and then that is out of bounds so we exit this loop and we bounds so we exit this loop and we return return bank so time complexity for this bank so time complexity for this algorithm is algorithm is as stated in the question as stated in the question o o t plus s t plus s where t is all the values within t where t is all the values within t string because we need to create this string because we need to create this frequency map frequency map and s is all the letters within the s and s is all the letters within the s string okay so let's start writing this string okay so let's start writing this out so let's initialize the map data out so let's initialize the map data structure structure so map is equal to new map so map is equal to new map let's loop through the values of t and let's loop through the values of t and create that frequency map create that frequency map so that letter so that letter t t so if the map doesn't have letter so if the map doesn't have letter then we can initialize it with one then we can initialize it with one so map.set so map.set letter one letter one else we just need to add to the current else we just need to add to the current value within the map so map dot set value within the map so map dot set letter map.get letter map.get letter plus letter plus one one so that'll populate the frequency map so that'll populate the frequency map then we need to initialize all the then we need to initialize all the variables so the left and right pointer then which is going to be equal to count which is going to be equal to count which is going to be equal to map.size so map.size so the map the map has has and the count which is going to equal to and the count which is going to equal to map.size map.size so map has a size property so map has a size property which will be equal to free which will be equal to free within the first example and then we within the first example and then we also need min window also need min window to initialize as an empty string to initialize as an empty string and then we can start the loop so while and then we can start the loop so while right is less than s dot length we can extract the letter at the right pointer so our letter is equal to s dot right make it a bit easier to read if map has our letter so if the frequency map has the letter at the right pointer we can decrement the value of that and then we can do an additional check and then we can do an additional check to see whether to see whether that value is now equal to zero and then we just need to increment the and then we just need to increment the right pointer there right pointer there so while the count is equal to zero so so while the count is equal to zero so we have found if right minus left if right minus left is less than len which we will be is less than len which we will be updating so the first time we check updating so the first time we check right minus left it'll be checking right minus left it'll be checking against infinity so it will have to be against infinity so it will have to be updated updated we'll update the length we'll update the length two equal right minus left two equal right minus left so this is the current length of the so this is the current length of the substring substring and then we need to update minimum and then we need to update minimum window variable two equal s dot slice and slice from left up to but not including the right pointer because remember we incremented right on line 32 then we can use the slide in window technique and increment the left pointer here so let's extract the left pointer to make it easier to and let's check to see whether the map and let's check to see whether the map has the value at the left pointer if it does we can increment the value within the and then we can do an additional check and then we can do an additional check to see whether to see whether the value at the letter the value at the letter is greater than zero and if it is we can increment count then we just need to increment the left pointer and finally we can return min let's give this a run let's give this a run okay let's submit okay let's submit it and they have it | 2024-03-20 11:42:04 | 76 | Minimum Window Substring - LeetCode 76 - JavaScript |
|
qdeMliPI7po | hello and welcome to this problem number 968 968 binary tree cameras so as you would have binary tree cameras so as you would have seen i have actually changed in the seen i have actually changed in the camera setup a bit camera setup a bit instead of the left side my face you instead of the left side my face you will see on the right side will see on the right side uh that's simply because i realized that uh that's simply because i realized that the way lead code ide is set up the way lead code ide is set up a lot of the space is actually taken up a lot of the space is actually taken up by this this entire thing by this this entire thing and rather you know more focus should be and rather you know more focus should be on the coding window and less focus on the coding window and less focus should be on the question wind because should be on the question wind because once you've read the question you don't once you've read the question you don't need it as much need it as much so this is going to be the um set up so this is going to be the um set up here of course there is the run code and here of course there is the run code and the submit code button which is hidden the submit code button which is hidden but but i could just say it and you would know i could just say it and you would know right so uh right so uh let's get started so this problem says let's get started so this problem says that given a binary tree very very that given a binary tree very very important important given a binary it's a binary tree we given a binary it's a binary tree we install cameras on the nodes of the tree install cameras on the nodes of the tree right each camera at a node can monitor right each camera at a node can monitor its parents its parents itself and its immediate children so itself and its immediate children so three things its parents three things its parents itself and intermediate chip calculate itself and intermediate chip calculate the minimum number of cameras needed to the minimum number of cameras needed to monitor monitor all the nodes of the tree right so you all the nodes of the tree right so you what you're supposed to do is you're what you're supposed to do is you're supposed to put in cameras you could put supposed to put in cameras you could put cameras on any node cameras on any node and the cameras have this property that and the cameras have this property that the camera can monitor the node which the camera can monitor the node which it's it's on it's like intermediate children like on it's like intermediate children like all the children all the children and it's right this is what the and it's right this is what the camera can do and you want to find out camera can do and you want to find out the minimum number of cameras the minimum number of cameras you you need to put a given binary so you you need to put a given binary so that all the nodes are that all the nodes are monitored right so uh monitored right so uh actually a simple uh like actually relatively a simple question so uh really like it's basically not a very complicated question this is really a simple question but this this function is it's it's actually gives you a detailed discussion of how you should think when you have problems like these with you know including the children of the node the parents or the nodes are all you know also involved so this is one category of problem i wanted to cover so let's look at this example quickly uh example one now here as you see that um this is the pine tree if you put camera here this camera would uh wait a minute this this camera here would make sure that the the it's apparent so this is this is under view this is this is also uh you know this this is also uh you know something which is covered so the camera covers this node itself the upper nodes the lower node and uh also so this entire tree is covered by just one camera right so you only need one camera for this tree in the second example you might actually need more than uh you know one camera so let's look at that case so in this tree you could have put camera anywhere here but look at this camera placement if you put a camera here what happens is that uh a camera placed here is covering this thing or this like it's immediately filed its parent camera port here covers its immediate panel and it also covers this now this is actually covered two times and we want to minimize such instances where it is covered two times but it so happens that in this configuration this is the best possible we can get you cannot do anything with one camera because if you put one camera even here these two nodes would be left from being covered right if you need at least two cameras uh you know but to do this so the answer to this is two right so this is actually a very you know it's it's if you know has you know you have to have two very important observations to handle this problem so this is the structure of the binary tree there is a left there is a right and there is a value you don't need to uh like let's not remove this because i mean it's not needed in some problems it's actually needed a lot but you just need to know left right and so on so like now see in this problem what we need to realize [Music] [Music] a node can affect a node can affect its children children and its parents this is a very important statement in this problem a node can affect its children and its parents in a lot of the problems the node can only affected children and it is very easy because for it for for the tree you know we have nodes which are pointing downwards like for every node we have a left node and a right node and so you could very easily access a left node and the right node you could do it very easily but if you want to let's say given a tree which has like those links how do you access a parent of a word so this actually makes the problem a little bit more challenging and these these classes of problems which actually need to you know dealing with parents of the trees so uh there are many techniques of actually doing that you know actually storing keeping things in stacks and storing that but you know one good heuristic when you see such problems is to remember that the way you do it is the way you do whenever you have the you know you from the children you want to go to their parents the best way to do it is do it via efs a depth first search what does a dfs guarantee right so now what happens in a dfs dfs what happens is you start with the root node you go to the most bottom part of it and then by recursively stack calling you come back you come back you come back right so dfs is intuitively one way in which you could go down the tree you could go down to the the leaf nodes and from the lymph nodes you can come back right so basically if you don't want to use dfs you could use you could store the parents in some data structures and there are many fancy algorithms and fancy ways of doing it but i think the the structure remains the same even if you use a data structure it's like dfs when you're doing dfs it actually uses recursion to come back and it you know back in the recursion actually uses stack right to uh handle this so it's like we need some sort of a storage to actually go you know go back you need some sort of a storage when we have children affecting their parents right in a binary right so uh this problem actually is a very straightforward problem because if you look at this problem what you need to do is you just need to excuse me you just need to go down the excuse me you just need to go down the tree and you just need to see tree and you just need to see okay there are two properties a node can okay there are two properties a node can like what are the two properties in like what are the two properties in organelles there are important don't mind the spelling it might be wrong i'm not an english nerd so the two properties the first property is that it has a camera right and the second property is that it is money third right so the first property implies the second one if the node itself has a camera then it's all it's one area and it's pointed by itself and the second thing is that if the uh you know if the node is monitored then what we get is that we we don't need to put a camera there right so you could the combination if this is this is a all of these are like bulls right these are boots this is a this is a boolean variable and this is a boolean variable whether a node has a camera or is its momentum so what we want to do is we want to make sure we want to place the cameras in such a way that the second variable is monitored is true for all the uh you know the entire tree right and what we do is we actually we actually do a depth first search and when we do a depth first search we need to uh we actually for every node we have this this property it has a camera and like it it is monitored and what we do is if like so we have you're gone you're coming from bottom up so like yeah so the advantage of this is bottom up right you're filling the the cameras bottom up and if you're coming from bottom up you realize that if you have a node for a node a node if it's if both of its children if both of its then that is the only way you can then that is the only way you can monitor those children monitor those children is by putting a is by putting a on that node on the node so we are on on that node on the node so we are on the node so the only way you could the node so the only way you could monitor if both of your children are not monitor if both of your children are not wanted wanted then the only way you could put a camera then the only way you could put a camera is you know basically why is you know basically why um only way you can solve that is um only way you can solve that is putting a camera and since it's a binary putting a camera and since it's a binary tree you cannot have like more than one tree you cannot have like more than one parent and things like that parent and things like that this is just one parent the only way this is just one parent the only way those two nodes are going to be wanted those two nodes are going to be wanted is by putting a camera on that is by putting a camera on that node of the parent right the second node of the parent right the second characteristic is that let's say if um characteristic is that let's say if um so the second characteristics is yes so so the second characteristics is yes so if if basically the as i was saying the second basically the as i was saying the second property is that if property is that if like if one of the one of the child like if one of the one of the child actually has a camera then you don't actually has a camera then you don't need to do anything you just need you need to do anything you just need you know now know now that the the node in question is that the the node in question is monitored monitored right so uh if one right so uh if one of the children have of the children have uh cameras then you're pretty sure that uh cameras then you're pretty sure that this this node is moni node is moni turd and when you put a camera it turd and when you put a camera it directly implies directly implies that this node is what is node is morning third right yes um money turd right so see what what did you do you if you if you are at a node and if both of the children are not monitored you have to compulsively put a camera there because there is no option for the kids to get pointed so but by doing that you make the node being monitored and you also put a camera on that node right and if one of the when you are coming to a tree and when you have one uh you know node which has two kids two children or one child and one of them has a you know camera if one of them is actually monitored then uh we what you do is you you try to you put a camera there right because you don't need to put a camera there you just see that the node is monitored itself right because if uh like yeah if another children has what then you thought the notice might it's pretty straightforward right here so uh it's just uh you know going back again you're doing a dfs you're coming from bottom to up if you are at a particular node you need to do this for all the nodes so if you are a particular node if both of its of its children aren't monitored you need to put a camera there and that's how the node and the bit skates become monitored if one of the child has a camera then you just know that this node is monitored you don't need to do anything else right and then you do it recursively for all the node so either of the condition will be true so in both of the cases all the nodes will be monitored right and in this greedy fashion you will use the minimum number of cameras because you're going from bottom up if you're going from top up you need to you know check all the possibilities and things like that but if you're since you're going from bottom up it's automatically greedy it's automatically the fact that you're being optimal at putting cameras right so uh there are many ways of implementing this so let's um a decent way of implementing it would be to have a global variable uh let's say n yeah so uh in this you know scope you say first of all you begin with saying that this is zero the number of camera is zero and you somehow have a function okay this is a view one other consideration needs to be done what if what about the leaf nodes or what about the root node so uh i will actually come to that right so the number of cameras now i'll uh have a variable let's call it uh the uh you know answer variable or let's call this you know s a variable to make a temper variable so this m variable is auto temp uh it takes it gets in this function uh you know cnt cam [Music] cameras and this function takes in so it takes in this this uh you know what it does it takes in this the this this function and it does something let's you know basically talk talk about implementing this function and seeing what's the most efficient before so um okay so let's have so you know we need these two so we need it to return two variables uh so auto let's not have auto let's have a pair of uh bull rule right so you have this pair of bull bull attempt the first one says whether the bull leg pair dot first is like whether the camera it has camera and two is like whether it is movement or not right so this is basically the situation of the root node whether the root node is monitored or not so what this will do is it will actually do the dfs from the root there is this external variable called camera it will increase the number of camera like the n camera as and when it finds worth increasing and then finally it will tell us about the root note right now root node needs to be specially cared about because root node doesn't have a parent right if root node does not if basically if the root node is not being monitored by something this is below it the only possibility you have is to put a camera at the root right so this is just that special case of looking at the root node so if you see that if it's this thing this temp is like the condition of the root node is the second value of it so it's not monitored so if the temp dot second is false right so it's like it's not being ordered or the root is not being monitored the only option we have is that we uh you know put a camera on the root so we increase the number of camera we have to increase the number of cameras you put the camera on on the road uh that's the only consideration you have and then you return the end camera variable uh it will be more much more clear when i actually write the uh the proper function to this right so uh let's uh do that as well so we have this uh we'll have some you know we'll have some space for some real estate okay yeah so we uh we're writing this function this function returns a pair of a volume pair of booleans uh what is this function the function is called a cnt camera right cnt camera it takes in a [Music] three node pointer to three node off root right it takes in this now uh when it does take this thing in this thing was not needed because yeah this is what can go down right so cnt camera all right so first now first of all you need to know what is with the root node so if the root like if the root node is null right as generally all three problems what if the root node is not if the root node is null first of all you don't have a tree so in the base case when the root node is null you actually handling it with the you just put a camera on that root node and then you're done so that is handled by this the only case when you need to take care of it when do not is equal to is equal to null is when you are actually at the leaf node and somebody's actually trying to check or you're in one of those nodes which don't exist if node doesn't exist then you just simply say that uh it's it's like you know you there is no camera there so there is no camera here and it's already monitored or you don't need to care about it so this is like is there the first thing is like the first value is these have a camera second is it monitored right the first bull is easier to have a camera and is it so you say the null value doesn't have a camera and true because uh it's actually we just say it's monitored because you don't care about what what is happening to this so if the these the algorithm will totally ignore this if you are at the null position even at the leaf nodes or you are at the one of those side positions right so this is done now let's get into the more interesting cases you are returned uh since this is an explicit uh you know the the function as like pair bull returning this will automatically be converted into a pair of boolean boolean uh if you want to actually do it you could do explicit type conversion but it's not necessary because the return type of the function is paired okay so you have pair uh of left so this is nothing but when you are doing this for the right you're doing this for the left right you're doing this for the left part of the root node and similarly part of the root node and similarly you will have just remember that the first value is i'll put it here as well for anybody that in this function the first thing the you know the function dot one like is is it camera and the second thing is that is it monitored right so left and right so once you so this is this is actually doing the the post on the traversal so when you're doing a dfs you could do it in three ways you could do with you know a pre-order in order or post order this is actually a post order traversal because uh you first need to look at what left and right are and you need to do it to the end of it and then based on the left and the right values you can make a choice whether you want to uh whether you want to put a camera or not right because you need the values for both whether there is a camera on the left and right to make a decision off about the root node so like about the with the node the parent node so this is actually a post order right so now you say that if we just handle this case that if both of the children aren't monitored you need to put the camera if one of the children has cameras not have camera one of the children has camera then the node is monitored so let's say let's check that so if one of the kid has cameras how do you see that so this is the left child so you just save left dot first so this has a camera or write dot first is true or both whatever both will actually not be true like an optimal setup but like if one of them is true you it might also be so if yeah if one of them is true what you do is you just say uh okay you will have to initialize these two bulls bool uh hash cam right which is false by default and uh bull money third is also false right so what you do is you just for like if this is true then you don't need to uh if this is true that you don't need to have a cam so this lets this name involves but you now know that this is actually being monitored right uh that's cool uh if uh there's this other case which in which like if l dot uh second so basically both of them are not there so if uh both of these children aren't monitored so if you want to see both the children are unmonitored so there where you have the second variable so like l dot second is false and a lot like r dot second so both of the uh variables are not pointed then you need to make sure that the hash cam becomes true so this node should have a camera number of camera is monitored also becomes true because this because it has a camera it automatically becomes monitored and the number of camera has to also and right so that's how why we have a global right so that's how why we have a global variable called that camera variable called that camera this has to increase uh this is all this has to increase uh this is all handled this is all handled this is all the case that's pretty much it the case that's pretty much it for the left for the right and so on and for the left for the right and so on and finally you will need to return finally you will need to return the we just say we return uh hascam and monitored right so for whatever the case may be this uh whether this is true whether this is true uh this will be returned hash cam monitor uh what of the values and if nothing is true then both of them will be false will never happen so let's pretty much submit this solution there is a silly mistake we'll debug it okay so there is a silly mistake let's okay so there is a silly mistake let's see what that silly mistake is so actually the silly mistake was uh rather obvious it's actually right here so i just like arrows being left so let's try to do this now let's try to run this now and accept it right it's better than 73 and accept it right it's better than 73 percent memory uses 56 percent so a percent memory uses 56 percent so a decent decent simple uh solution to the question to simple uh solution to the question to this question uh this question uh which was just a brilliant operation for which was just a brilliant operation for like a depth first search followed by like a depth first search followed by like the post-order traversal for like the post-order traversal for a greedy approach of assigning cameras a greedy approach of assigning cameras so it's actually a straightforward so it's actually a straightforward question question but just this this intuition that when but just this this intuition that when you need to have children's that can you need to have children's that can affect its parents you need death per affect its parents you need death per search search and the fact that you know you needed and the fact that you know you needed post order traversal was a little bit post order traversal was a little bit tricky tricky but overall it's a simple question you but overall it's a simple question you could easily have solved this in let's could easily have solved this in let's say half an hour time say half an hour time right and this is a pretty optimal right and this is a pretty optimal solution so solution so it is interesting actually to see for it is interesting actually to see for cases in which you have an energy and cases in which you have an energy and you have like more nodes you have like more nodes how do you how does this generalize how do you how does this generalize because if you have an energy because if you have an energy you still need this by these binary you still need this by these binary variables but you need to do this for uh variables but you need to do this for uh like for all the all the nodes and all like for all the all the nodes and all the trees the trees so this this question can be asked in so this this question can be asked in many many variants where you could have many many variants where you could have like more than one types of cameras each like more than one types of cameras each of them have different properties of them have different properties so then the binary one and zero like so then the binary one and zero like just being hanging a camera and having just being hanging a camera and having monitors is not enough monitors is not enough you'll have to make sure that there can you'll have to make sure that there can be more cameras and more monitoring so be more cameras and more monitoring so let's say we have to put two cameras so let's say we have to put two cameras so like there can be many many variants to like there can be many many variants to this problem but at the core this problem but at the core the fundamentals of this problem is the fundamentals of this problem is about you know post order traversal and about you know post order traversal and this grady approach this grady approach so hope uh you know i you know you so hope uh you know i you know you enjoyed this video and i really want to enjoyed this video and i really want to say that if you're watching until this say that if you're watching until this end please if you have any suggestions end please if you have any suggestions for the videos uh please you know i put for the videos uh please you know i put them in the comment section them in the comment section that you know some new videos on this that you know some new videos on this topic or these questions need to be made topic or these questions need to be made and i'd surely try my best to make them and i'd surely try my best to make them right thank you | 2024-03-25 14:07:25 | 968 | Leetcode 968(Hard) Binary Tree Cameras: Simple C++ Solution |
|
_hxYLD47v18 | hello yours welcome back to my channel I hope you are doing great if you I hope you are doing great if you haven't subscribed to my channel yet haven't subscribed to my channel yet please go ahead and subscribe I have please go ahead and subscribe I have created bunch of playlists to cover created bunch of playlists to cover various categories of the problem such various categories of the problem such as linking list trees graphs as linking list trees graphs breadth-first search binary search breadth-first search binary search depth-first search dynamic programming depth-first search dynamic programming and so on please check them out and so on please check them out I have uploaded the code for this I have uploaded the code for this particular problem to github you can get particular problem to github you can get the link from description below this the link from description below this video let's jump into today's problem video let's jump into today's problem rearrange words in a sentence given a rearrange words in a sentence given a sentence text a sentences string of sentence text a sentences string of space separated words in the following space separated words in the following format the first letter is uppercase format the first letter is uppercase each word in the text are separated by a each word in the text are separated by a single space so basically we are given single space so basically we are given with the sentence and the first with the sentence and the first character is an uppercase letter and all character is an uppercase letter and all the words in the sentences sentence are the words in the sentences sentence are separated by a single space your task is separated by a single space your task is to rearrange the words in text such that to rearrange the words in text such that all words are rearranged in increasing all words are rearranged in increasing order of their lengths if two words have order of their lengths if two words have same length arrange them in their same length arrange them in their original order written the new text original order written the new text following the format shown above so once following the format shown above so once we rearrange we need to make the first we rearrange we need to make the first letter uppercase and all the words in letter uppercase and all the words in the text should be separated by single the text should be separated by single space again once we rearrange basically space again once we rearrange basically so what are the conditions for rearrange so what are the conditions for rearrange there are two conditions right so one is there are two conditions right so one is they should be the word should be they should be the word should be increasing order of their lengths but if increasing order of their lengths but if two words have same length write arrange two words have same length write arrange them in the original order so whatever them in the original order so whatever the original order in the sentence right the original order in the sentence right we will be arranging in that original we will be arranging in that original order so let's go ahead and understand order so let's go ahead and understand this with an example right so leadcore this with an example right so leadcore is cool let's say that's that's the word is cool let's say that's that's the word right so lead code how many how many right so lead code how many how many characters it is eight characters right characters it is eight characters right and this one is two and this one is cool and this one is two and this one is cool is four so now if we saw our thread it's is four so now if we saw our thread it's art or it will be two four eight right art or it will be two four eight right that's what it is so the corresponding that's what it is so the corresponding thing thing is cool is cool Nico right ideally this is the one right Nico right ideally this is the one right he is cool it cool but we need to he is cool it cool but we need to arrange the sentence in the format shown arrange the sentence in the format shown ago that's what it is ready to return ago that's what it is ready to return the new text following the format shown the new text following the format shown above right so what is that first letter above right so what is that first letter he is in the upper case so let's he is in the upper case so let's transform I to the upper case and each transform I to the upper case and each word is separated by a single space I word is separated by a single space I think I already have single space across think I already have single space across so this is our answer right so this is so this is our answer right so this is our answer our answer so that's how we need to do right this so that's how we need to do right this is a simple case where we are arranging is a simple case where we are arranging them in the increasing order of their them in the increasing order of their lands right so that's the first lands right so that's the first condition right condition right so we fortunately there are no words so we fortunately there are no words with same length right so let's see if with same length right so let's see if there is a another thing with same there is a another thing with same lamprey so let's see this one right in lamprey so let's see this one right in this there are some words which are the this there are some words which are the same length right so which a keep is for same length right so which a keep is for calm is for and it's three core is for calm is for and it's three core is for honest too so with that what we are honest too so with that what we are going to do is two three four four four going to do is two three four four four four right so this this is a pretty four right so this this is a pretty complicated situation right we have complicated situation right we have three words of the same length right so three words of the same length right so now let's let's try to fill up the first now let's let's try to fill up the first things right because there is no things right because there is no collision with that so on right and next collision with that so on right and next thing is and all right now for for which thing is and all right now for for which for ready to take is a question right for ready to take is a question right since we have to keep the order right since we have to keep the order right the original order it said right so the original order it said right so arrange them in the original order so arrange them in the original order so what is the original order Keep Calm what is the original order Keep Calm code right so keep is coming first code right so keep is coming first so keep calm is that come incident and so keep calm is that come incident and code is coming and what we are going to code is coming and what we are going to do the first character we need to make do the first character we need to make as as caplets so this is our answer on and caplets so this is our answer on and keep calm core right that's what it is keep calm core right that's what it is so whenever there is a collision between so whenever there is a collision between the length right so if there are more the length right so if there are more words two or more words have same length words two or more words have same length we have to arrange them in the original we have to arrange them in the original order of the sentence so it's like Keep order of the sentence so it's like Keep Calm code Keep Calm curve there in that Calm code Keep Calm curve there in that are right so this is the idea so we are are right so this is the idea so we are given with the sentence and each word is given with the sentence and each word is separated by a single space right so now separated by a single space right so now what we are going to do is since we have what we are going to do is since we have to play with words we need to convert to play with words we need to convert that given sentence into words basically that given sentence into words basically we split the sentence into words now we split the sentence into words now right and we need to know two things right and we need to know two things right right what is that the word position and the what is that the word position and the word length two things if we know two word length two things if we know two things then only we can arrange into things then only we can arrange into another sentence basically a new another sentence basically a new sentence basically right so we need to sentence basically right so we need to know two pieces of information right so know two pieces of information right so what is that the letter V word and also what is that the letter V word and also the position so what we are going to do the position so what we are going to do here is if you have the word we can get here is if you have the word we can get the length of the word pretty easily so the length of the word pretty easily so what we are going to have is a what we are going to have is a placeholder class which will keep track placeholder class which will keep track of the two pieces of information that we of the two pieces of information that we need need what is that the length of the world and what is that the length of the world and the position of the earth right but if the position of the earth right but if you have the word itself right it's easy you have the word itself right it's easy to have the position of the arm I mean to have the position of the arm I mean Linda the world anyway right so what I'm Linda the world anyway right so what I'm going to have is a word and its position going to have is a word and its position in the place for a class right so let me in the place for a class right so let me show you the place code attached first show you the place code attached first for a second right so this is a for a second right so this is a placeholder class which I am calling as placeholder class which I am calling as node ignore the naming for a second so node ignore the naming for a second so it will be public string s and public in it will be public string s and public in position so string is a word here position so string is a word here basically this is a word and the basically this is a word and the position is the position in which I'm position is the position in which I'm position of the word in the sentence position of the word in the sentence basically so if you go back red so basically so if you go back red so position of keep is zero right and comm position of keep is zero right and comm is one and it's two core is three on is is one and it's two core is three on is like that so I will be keeping the like that so I will be keeping the position of those words right that's position of those words right that's what it is what it is so once I have that I will be generating so once I have that I will be generating a list of objects with word and position a list of objects with word and position all right all right and I will sort based on the rules what and I will sort based on the rules what are the rules first rule is increasing are the rules first rule is increasing the order of flames and second role is the order of flames and second role is if they have same length arranged in if they have same length arranged in rows in order so with those two rules I rows in order so with those two rules I will start it so once I sort them right will start it so once I sort them right so I will have basically in this format so I will have basically in this format two three four four four four right and two three four four four four right and they are in this format so once I have they are in this format so once I have them in this particular object list them in this particular object list right what I need to do is I need to right what I need to do is I need to extract the words from this list and put extract the words from this list and put back at the sentence format right put back at the sentence format right put back in the sentence format and make the back in the sentence format and make the first character as uppercase right make first character as uppercase right make the first character as per this so the first character as per this so that's what we are going to do so that's what we are going to do so basically the steps are simple first you basically the steps are simple first you have to split the sentence into words have to split the sentence into words and the second thing is prepare a list and the second thing is prepare a list of objects such as you are keeping track of objects such as you are keeping track of the word and its position so once we of the word and its position so once we have list of objects you sort them that have list of objects you sort them that isn't step number three once you saw in isn't step number three once you saw in the step number four you just join the the step number four you just join the words with space in between them that's words with space in between them that's what it is right that's what the second what it is right that's what the second rule and what you're going to do is rule and what you're going to do is convert the first letter in that convert the first letter in that sentence to uppercase and reckon it sentence to uppercase and reckon it that's it so we will do those four steps that's it so we will do those four steps and come up with the final answer right and come up with the final answer right so let's go ahead and look at the code so let's go ahead and look at the code for this particular idea so I already for this particular idea so I already showed you the place order class which showed you the place order class which keeps that keeps track of the word and keeps that keeps track of the word and it's a position right so let's go ahead it's a position right so let's go ahead and look at one more time word and its and look at one more time word and its position right and next so just for the position right and next so just for the sake of converting this first character sake of converting this first character in to lowercase right so I am taking in to lowercase right so I am taking this text tool over and splitting it by this text tool over and splitting it by space space I have all the words in the strings STRs I have all the words in the strings STRs right so I initialize the position to right so I initialize the position to zero I am declaring a list of words this zero I am declaring a list of words this month month this means list of objects basically so this means list of objects basically so these are the list of objects where the these are the list of objects where the type is node type is node what is it nor exactly node will have what is it nor exactly node will have the word and its position right so now I the word and its position right so now I will go through each string in this STRs will go through each string in this STRs and try to add an object into the words and try to add an object into the words so the object will have the string and so the object will have the string and its position right this position will be its position right this position will be incremented for each string right so now incremented for each string right so now I have a list of objects so these list I have a list of objects so these list of objects will be sorted I am using a of objects will be sorted I am using a custom sort okay I am calling it as new custom sort okay I am calling it as new arrange comfort this is a customs art arrange comfort this is a customs art right we'll go and see what is the right we'll go and see what is the custom start doing so essentially the custom start doing so essentially the custom start has to do two things right custom start has to do two things right and it has to follow two rules one rule and it has to follow two rules one rule is it should arrange in the increasing is it should arrange in the increasing order of their lens second rule is the order of their lens second rule is the two words have same length the they two words have same length the they should be arranging in the original should be arranging in the original order right original order of the order right original order of the positions of the words so that's what positions of the words so that's what this arrange compare is going to do for this arrange compare is going to do for us so I saw it using the custom compare us so I saw it using the custom compare so once I started the words are in this so once I started the words are in this particular format two three four four particular format two three four four four basically I am having the width the four basically I am having the width the length but I assume that these are just length but I assume that these are just the words right so I have the words so the words right so I have the words so now I get the words words start select w now I get the words words start select w dot s so this is the lambda expression dot s so this is the lambda expression to get the words and join by what is to get the words and join by what is that space right so that is what we need that space right so that is what we need right they are separated by a single right they are separated by a single space so we are separating by single space so we are separating by single space now I have the final string and space now I have the final string and one more thing we need to do is convert one more thing we need to do is convert the first letter to the uppercase so I the first letter to the uppercase so I get the first letter and then before get the first letter and then before returning I am converting that to returning I am converting that to uppercase right and returning their uppercase right and returning their strength now go ahead and see what we strength now go ahead and see what we are doing for the arrange compare custom are doing for the arrange compare custom sort sort so this one we are passing in node type so this one we are passing in node type right so node type will have two things right so node type will have two things what are those string and its position what are those string and its position all right so now I will get the length all right so now I will get the length of the string a from node a I will get of the string a from node a I will get the length of a second string in node B the length of a second string in node B so if the lengths are same what I should so if the lengths are same what I should do if the lengths are same you the words do if the lengths are same you the words have same length arrange them in their have same length arrange them in their original order that means whatever the original order that means whatever the position so I am comparing the positions position so I am comparing the positions and returning the position compression and returning the position compression do they are not same then you compare do they are not same then you compare the lengths and return so this is the the lengths and return so this is the custom sort that we are going to use as custom sort that we are going to use as per other word dot sort right so that's per other word dot sort right so that's what will be used to solve the words what will be used to solve the words based on the length as well as the based on the length as well as the position right so now that we are able position right so now that we are able to solve this and return the final to solve this and return the final answer right let's go ahead and look at answer right let's go ahead and look at the time complexity and space complexity the time complexity and space complexity time space so we are given with the time space so we are given with the sentence right the texture is sentence sentence right the texture is sentence not the word but we are playing with the not the word but we are playing with the words we don't know the number of words words we don't know the number of words in the text for example I am assuming n in the text for example I am assuming n is number of words right n is the number is number of words right n is the number of words it's not it's not I would like of words it's not it's not I would like it's not text length right it's not text it's not text length right it's not text length unless unless the whole text is a length unless unless the whole text is a single word okay if it is a single word single word okay if it is a single word then you don't need to do anything of then you don't need to do anything of this order it it's just whatever it is this order it it's just whatever it is right but I'm assuming n is the number right but I'm assuming n is the number of the words not the text length so of the words not the text length so normally in the string algorithms right normally in the string algorithms right you would take n as a text length but you would take n as a text length but here it is the number of words so I am here it is the number of words so I am just assuming n is the number of words just assuming n is the number of words so if n is the number of words right I so if n is the number of words right I am going through the first time am going through the first time splitting and going through the number splitting and going through the number of of right so this will be order of n time right so this will be order of n time complexity right so now I'm sorting complexity right so now I'm sorting these n words right so any sorting these n words right so any sorting algorithm that we take so told so far algorithm that we take so told so far its order of n plus we are sorting I its order of n plus we are sorting I would say the sorting algorithm will be would say the sorting algorithm will be order n log n right so the total order n log n right so the total complexity is order of n log N and if complexity is order of n log N and if you would like to add this one right you would like to add this one right adding or generating the final string adding or generating the final string this would also take plus order of n this would also take plus order of n right order basically order of words right order basically order of words right so that will be totally order of 2 right so that will be totally order of 2 n plus log n right so order of order of n plus log n right so order of order of 2 M plus n log n right so normally n log 2 M plus n log n right so normally n log n is greater than n right n is greater than n right normally 8 log n is greater than and for normally 8 log n is greater than and for a valid M for high number of n basically a valid M for high number of n basically not for like 2 2 or 3 if n is equal to not for like 2 2 or 3 if n is equal to or 3 doesn't matter much but if it is if or 3 doesn't matter much but if it is if n is large maybe n is a million right so n is large maybe n is a million right so then 2 n is much much less than n log n then 2 n is much much less than n log n right for those cases we will remove 2 n right for those cases we will remove 2 n from the Big O notation and we will say from the Big O notation and we will say the total time complexity for this the total time complexity for this particular algorithm is order of n log n particular algorithm is order of n log n right so let's go ahead and look at the right so let's go ahead and look at the space complexity right so how much space space complexity right so how much space we are essentially using right so there we are essentially using right so there is a list of objects that we are is a list of objects that we are generating right the words so each word generating right the words so each word will have the position and the word will have the position and the word itself right so we don't know again the itself right so we don't know again the world length right to start with so world length right to start with so again we will go with number of words again we will go with number of words right n number of words are there so we right n number of words are there so we need n such spaces right I am assuming need n such spaces right I am assuming there will be one unit of space needed there will be one unit of space needed for word that one unit can be anything for word that one unit can be anything it could be 8 bytes or in what's what it could be 8 bytes or in what's what say all right I am just saying one unit say all right I am just saying one unit of space I don't know what is that unit of space I don't know what is that unit is so each each word will have different is so each each word will have different lengths so that unit lengths so that unit be different right so I cannot quantify be different right so I cannot quantify saying okay each word will be taking the saying okay each word will be taking the same number of units right that's why same number of units right that's why I'm just going with a uniform way I'm I'm just going with a uniform way I'm taking one unit of space for each word taking one unit of space for each word so I have n words right so n such so I have n words right so n such objects are there in here so I would say objects are there in here so I would say order of M to start with plus and I have order of M to start with plus and I have this space where I am splitting and this space where I am splitting and storing it in here right that would also storing it in here right that would also be be order n plus we are making the be be order n plus we are making the final string right which will be another final string right which will be another order and right so basically we are order and right so basically we are using order three and space right so using order three and space right so since we are going to ignore the since we are going to ignore the constants we will say the total time constants we will say the total time complexity of this algorithm is order of complexity of this algorithm is order of n so the space complexity is sorry not n so the space complexity is sorry not the despise time down to 58 space the despise time down to 58 space complexity space complexity is order of complexity space complexity is order of n and time bounce it is order n log and n and time bounce it is order n log and if you have any further questions please if you have any further questions please post them in the comment section below post them in the comment section below I have posted the code to the github I have posted the code to the github github repository you can find the link github repository you can find the link in the description below this video if in the description below this video if you haven't subscribed to my channel yet you haven't subscribed to my channel yet please go ahead and subscribe and also please go ahead and subscribe and also share among your friends please click on share among your friends please click on the bill icon so that you will be the bill icon so that you will be notified about all my future videos notified about all my future videos thank you for watching I will be back thank you for watching I will be back with another problem very soon till then with another problem very soon till then stay safe stay safe good bye | 2024-03-21 02:44:19 | 1,451 | Rearrange Words in a Sentence (Leetcode 1451) |
|
3Zoo51aPLY4 | hello everyone welcome to algo simplified let's solve today's lead code simplified let's solve today's lead code challenge that is greatest common challenge that is greatest common divisor of strings in this problem we divisor of strings in this problem we are given two strings and we have to are given two strings and we have to find a string that is a largest string find a string that is a largest string which can divide both the given strings which can divide both the given strings which means on which means on concatenation of the resultant string concatenation of the resultant string one or more number of times we can one or more number of times we can achieve both the strings that is string achieve both the strings that is string 1 and string 2. 1 and string 2. let's say we have a string s and we have let's say we have a string s and we have a string T and for your a string T and for your better understanding let's take a s as a better understanding let's take a s as a b a b a b b a b a b and T as a b and T as a b a b a b now if you just see let's say x is the now if you just see let's say x is the resultant string which can divide both resultant string which can divide both of them now of them now there are certain things the what can be there are certain things the what can be the size of X the size of X can be one the size of X the size of X can be one okay one if like all the numbers are AAA okay one if like all the numbers are AAA and a a a then it can can be one but and a a a then it can can be one but what if there is a pattern what if there is a pattern so the maximum size of that pattern can so the maximum size of that pattern can be the gcd of both the numbers like gcd be the gcd of both the numbers like gcd of of size of s you know you know the gcd will be this only the gcd will be this only so gcd let's take gcd is G so gcd let's take gcd is G so it will be the maximum size can be G so it will be the maximum size can be G because let's say it's 4 and it's six because let's say it's 4 and it's six then the gcd is two it can never be then the gcd is two it can never be greater than 2. greater than 2. it's never possible let's say let's say it's never possible let's say let's say we take four but we cannot add 2 4 to we take four but we cannot add 2 4 to make a six it will be eight so the gcd make a six it will be eight so the gcd is two so the maximum size can only be is two so the maximum size can only be two the minimum size can be two the minimum size can be the minimum size can be any other number the minimum size can be any other number like which divides both of them like which divides both of them but if a number divides but if a number divides now there is one more observation now there is one more observation let's see let's see if this x makes this D with like if this x makes this D with like a number of times a number of times on concatenating X we it makes T and B on concatenating X we it makes T and B number of times x it makes number of times x it makes s s now you would say that a number of time now you would say that a number of time x b number of time x makes this s n t x b number of time x makes this s n t so so since since these two can be made from X these two can be made from X let's say you take a b a b let's say you take a b a b and one more a b a b and one more a b a b so now you can see that let's consider so now you can see that let's consider this one and this one you will see okay this one and this one you will see okay this is of size 4 this is of size 8. so this is of size 4 this is of size 8. so gcd is four so if this a b a b can be gcd is four so if this a b a b can be repeated twice it will make this thing repeated twice it will make this thing then we will consider this a b a b as then we will consider this a b a b as string s we will not consider this a b string s we will not consider this a b even this a b can also make this string even this a b can also make this string on concatenation as well as this string on concatenation as well as this string on concatenation if a string of size on concatenation if a string of size smaller than a b can make this a b a b smaller than a b can make this a b a b and also this a b a b a b a b then it's and also this a b a b a b a b then it's possible that possible that a b a b on concatenation again if it's a b a b on concatenation again if it's forming like this ABAB is forming this forming like this ABAB is forming this thing then we will take the largest one thing then we will take the largest one and the largest one will be the gcd one and the largest one will be the gcd one with the size of gcd with the size of gcd so it's pretty simple that we will so it's pretty simple that we will consider the size of gcd as the possible consider the size of gcd as the possible string either it will be of the size gcd string either it will be of the size gcd or it will not be possible for us to or it will not be possible for us to make a string make a string which can divide both of them now how we which can divide both of them now how we will be checking if we can divide it or will be checking if we can divide it or not you know not you know if it's the number is B and the number if it's the number is B and the number is a like a number of times we can't is a like a number of times we can't concatenate this and B number of times concatenate this and B number of times then if we concatenate s and t like if then if we concatenate s and t like if we just append t we just append t to s to s we will get S Plus T and we if we append we will get S Plus T and we if we append s to T we will get t plus s that is s to T we will get t plus s that is S Plus t and t plus s you will get OK X S Plus t and t plus s you will get OK X is repeated B number of times x is is repeated B number of times x is repeated a number of times so here x repeated a number of times so here x will be repeated a plus b number of will be repeated a plus b number of times and also here times and also here it will be repeated a plus b number of it will be repeated a plus b number of times so you can say that if these are times so you can say that if these are equal equal if these are equal if these are equal this equality holds true it means both this equality holds true it means both the strings are equal the strings are equal it means it means one has a number of times and the one has a number of times and the another one has B number of times another one has B number of times and if we add them they will if they and if we add them they will if they give the same result then it's possible give the same result then it's possible for an X to exist and if it exists then for an X to exist and if it exists then it will be a gcd it will be a gcd So based on this thing let's solve it So based on this thing let's solve it let us code it up let us code it up so let's take the gcd first and so let's take the gcd first and J equal to this is inbuilt C plus plus J equal to this is inbuilt C plus plus STL STL so string 1 dot size comma string two so string 1 dot size comma string two dot size we have taken the gcd now if S Plus t equal to equal to t plus s then we will return str1 Dot substring from 0 to size G otherwise we will return empty string so this should be oh actually oh actually I'll just took variables of my own that I ex explanation time | 2024-03-25 16:44:42 | 1,071 | 1071. Greatest Common Divisor of Strings || LEETCODE DAILY CHALLENGE || ALGOSimplified |
|
VBXcQKzlADs | Hello friends, welcome to your Day 46 of Lead Code Challenge, so let's go straight to the screen and start today's question. So here we are on our screen. Today's question number is The name is Remove The name is Remove The name is Remove Duplicate Letter. Okay, this question Duplicate Letter. Okay, this question is a very interesting question, meaning is a very interesting question, meaning whatever you might be thinking, everything in it will be a whatever you might be thinking, everything in it will be a little bit opposite, a little bit opposite. little bit opposite, a little bit opposite. Okay, there are a lot of Okay, there are a lot of twists in the question and there is not one thing else in the question. twists in the question and there is not one thing else in the question. That this question is exactly the same 1081, That this question is exactly the same 1081, its link has also been put, see what the T code people have done its link has also been put, see what the T code people have done now, the two questions now, the two questions are exactly the same, so you have to watch this video are exactly the same, so you have to watch this video twice because the question twice because the question is quite interesting and the meaning is a is quite interesting and the meaning is a little difficult to understand. little difficult to understand. little difficult to understand. then you may find it a little difficult, okay, that's why you have to watch the video twice and you have to do the dry run two or more times, So let me So let me So let me tell you first, then let's go straight to the question and tell you first, then let's go straight to the question and understand the question. understand the question. So here we have the question. So here we have the question. Now see what we have to do. Basically Now see what we have to do. Basically what we have to do is we have to remove what we have to do is we have to remove duplicate duplicate letters from here. letters from here. letters from here. string from which duplicate letters have to be removed but it is not only that given string remove duplicate letters so every letter appears once letters have to be removed. Duplicate letters and one only once Your result is the smallest Your result is the smallest Your result is the smallest in rexo graphical order among the possible in rexo graphical order among the possible meaning that whatever results I will get from these, meaning that whatever results I will get from these, how many results will come, which one which one will be the smallest among them? will be the smallest among them? will be the smallest among them? talk about what are our duplicate letters in this? One is B, we have duplicate C. These two are duplicates. Now look let's understand this. Late sir, if I have moved these B and C, then C If C If C If I removed this one I removed this one and this C, and this C, what would we have C A B If I removed both of these, if what would we have C A B If I removed both of these, if I removed this C and this I removed this C and this B, what B, what would we have B C And if would we have B C And if would we have B C And if in this, but if I remove this C and this P, then the answer I get will be B. So we will have these four results which are So we will have these four results which are possible results. Out of these, the possible results. Out of these, the smallest one is Laxophile, isn't it? smallest one is Laxophile, isn't it? We have to return the smallest answer in lexophile. We have to return the smallest answer in lexophile. See how the smallest answer will be See how the smallest answer will be formed. So in increasing order, A B C is the formed. So in increasing order, A B C is the smallest, why A is the smallest, smallest, why A is the smallest, after that B is smaller than that, after that C. Look, is there after that B is smaller than that, after that C. Look, is there anyone like this here? anyone like this here? anyone like this here? is before this, B is before this, C is already, so the answer will be A B C. Okay, I hope you understood this part. Now Let's just take one more Let's just take one more Let's just take one more example. Let's take one more example. example. Let's take one more example. B.C.A.C.K. Bar. I took B.C.A. Now the first thing in this is what is duplicate? C and C. Okay, so now we have what result can be made? Its result is only two One can be formed, either remove this C One can be formed, either remove this C One can be formed, either remove this C or remove this C. The results will be B or remove this C. The results will be B C and C and a B C B. a B C B. These two results can be formed. Now, among these two, which is the least These two results can be formed. Now, among these two, which is the least graphically graphically smallest, the most is B. Look, B. smallest, the most is B. Look, B. Both have common A and C, it will be seen Both have common A and C, it will be seen which is smaller, A is smaller, after that which is smaller, A is smaller, after that C is coming, so in this case, it C is coming, so in this case, it is okay to return BC, so now how is okay to return BC, so now how can we do this, for this, neither is the whole one. can we do this, for this, neither is the whole one. can we do this, for this, neither is the whole one. is a story, there is nothing in this question, it is a story, we have to understand it from the story form and that means there are a lot of dryers in it, the code is also very good, it is a good level code, we will dry it a lot, only then we will understand it properly. So this is the type of question, I hope you have understood the question as to how to solve the question, what are we saying, is it okay to solve, the question is a little confusing as to how to maintain the graphical order So what can you do, if you do So what can you do, if you do So what can you do, if you do n't understand, then rewind a little once again, n't understand, then rewind a little once again, then come again and then come again and understand again. Okay, so let's go to the understand again. Okay, so let's go to the screen again and understand our story formation. screen again and understand our story formation. First, what do I do? First, what do I do? First, what do I do? see what example we have. For this example, let's understand that I copied this from Y to N, I put this in Y. Now let's see C and B A C B C B. First, let me explain to you with just a story form. How should we do this question? Okay, after that we will talk about what things are needed. Now, while I am doing the question, you can ask what things we need. Then I will explain, but let us observe you together. I have to understand that I am doing everything from the story form, then look at what I need, first of all the character came to me C, then come C, we kept him, after that came B, now B said to C, are you mine? He said yes C is bigger than B so he asked can you come after me then C said yes I am coming later so I will come later you Wrote it, Wrote it, Wrote it, after this came AA. A asked B, after this came AA. A asked B, can you come later? B said yes, I am also can you come later? B said yes, I am also coming later, so I will coming later, so I will come later, you come come later, you come first, A also came, after that came C, now C. first, A also came, after that came C, now C. D saw that brother A is younger than me and he is D saw that brother A is younger than me and he is already lying, so why should I come directly, already lying, so why should I come directly, C can come after A, absolutely right C can come after A, absolutely right fear came after him, D also thought that fear came after him, D also thought that I can come directly after C, so C. I can come directly after C, so C. I can come directly after C, so C. directly after that came C. Now look C has already arrived so I do n't need to check C. C has already arrived so to me it means it already came in the right order so I don't need to check C. So I made C skip, okay now how will I skip this, I have to go back and see that thing, we will have to maintain it, after that came B. Now B said to D that you are bigger than me, you come to me, so can You will come later. D said, You will come later. D said, You will come later. D said, I would have come later but I was I would have come later but I was not coming later. So what did he say to B? not coming later. So what did he say to B? After that C came again. What did C see After that C came again. What did C see that C had already come? So that C had already come? So we should send C to C. we should send C to C. we should send C to C. what is the answer to this? A CD B Okay, I will do this part again once so that you guys can understand it better. I will do it one more time so that you guys can Okay, look, K Okay, look, K Okay, look, K came first, there was no one there, after that BB came first, there was no one there, after that BB asked C, can you come later? asked C, can you come later? C said, yes, I am coming later, so C said, yes, I am coming later, so you come first because I was younger, so you come first because I was younger, so she said. she said. she said. made it, after that, A came and said, can you come after me? Yes, B said, I am coming later, so I will come later. You come, A also came first. After that, If he is a younger person than M then I would have If he is a younger person than M then I would have If he is a younger person than M then I would have come myself, I do come myself, I do n't need to ask him. After this D came and said C n't need to ask him. After this D came and said C is younger than me so there is no need to ask M is younger than me so there is no need to ask M so I would have so I would have come first. C come again. Now C said. come first. C come again. Now C said. come first. C come again. Now C said. I am not coming, so I have to maintain this thing, I have to find out one thing first, which thing has come to my mind, it is okay if I go and check for it again and again. So in this A is so I have to think about it some more after that I need B B I checked B B asked what are you D asked D can you come later D said I would have come but Not only am I not lagging behind, not only am Not only am I not lagging behind, not only am Not only am I not lagging behind, not only am I not available, so D said, you, I ca I not available, so D said, you, I ca n't come, so n't come, so C, we don't need to check, the answer to this C, we don't need to check, the answer to this is A, C, B, and this is my answer. Now is A, C, B, and this is my answer. Now see, what do I need? see, what do I need? In this question, I will need two things, one In this question, I will need two things, one is when is an element coming last time, is when is an element coming last time, one is the character that is coming last time, that is, one is the character that is coming last time, that is, its last index is the last ex, so its last index is the last ex, so what will I have to do for that, I will have to what will I have to do for that, I will have to basically create it for that. basically create it for that. basically create it for that. will create an array, last index, last index, that will be the whole one of 26 size, okay, I will make the whole array of 26 size, below it is a little bigger, I can show you the last index, which will basically take care of each character, that last time, First it is understood that it First it is understood that it First it is understood that it is okay like this is zero, this is one, is okay like this is zero, this is one, this is two, this is th, okay this is four, okay this is two, this is th, okay this is four, okay up to so no, this goes till 25, up to so no, this goes till 25, now what happens which is zero. now what happens which is zero. It represents a, this b, this c, this e, It represents a, this b, this c, this e, okay, this d and e, I okay, this d and e, I make them small, why I made them small, make them small, why I made them small, I will show you now and this is for z, I will show you now and this is for z, okay, so basically something. okay, so basically something. okay, so basically something. now why have I taken small characters because in the question I have given a consist of lower case letter, lower case English letter, so I do not need to do any conversion etc. in it, If I If I If I know the index know the index of any element then I will be able to do this work. Let's of any element then I will be able to do this work. Let's do it again. Okay, we will do it again. Okay, we will solve the problem one by one. Okay, solve the problem one by one. Okay, like what is the last index of S? First I like what is the last index of S? First I write the indexing here 0 1 2 3 write the indexing here 0 1 2 3 then 5. then 5. then 5. came on the seventh last index, this is how to fill, it is very easy, it means there is no A, there is nothing true in this, six and C then came on F, it is No, it No, it No, it came on a2, okay, there were A CDs in it, so came on a2, okay, there were A CDs in it, so I mentioned it and rest of the I mentioned it and rest of the default value remains zero, you must know that default value remains zero, you must know that inside the array, this zero is inside the array, this zero is ours and this is the character, otherwise we do ours and this is the character, otherwise we do not have any meaning. not have any meaning. not have any meaning. C came for the first time, so C came for the first time, so now BB asked C, will you now BB asked C, will you come later, so we went and checked whether come later, so we went and checked whether we are on One Index now, is we are on One Index now, is C coming anytime after One Index? C coming anytime after One Index? C coming anytime after One Index? means C will come later, so what did I do? I just removed C from here, I wrote B, now I am standing here, I am standing here, after this A came from A. We saw that B is before A, so We saw that B is coming later, B is coming after the second index, B is coming till the sixth index, so we removed B also and who put it here, I saw A, okay, after that came C, we are Now C saw that brother Now C saw that brother Now C saw that brother is a younger person than me, first of all, I do is a younger person than me, first of all, I do n't need to check with him, so C n't need to check with him, so C will come directly, okay, after this will come directly, okay, after this DD also came and saw that he is a younger person than me, DD also came and saw that he is a younger person than me, so I myself so I myself so I myself can be said. How is this small character being said? Graphically, in the dictionary order, the one that comes first is the smallest. A comes first, after that, B, after that, C, after that, Now we have to take care of this thing, Now we have to take care of this thing, Now we have to take care of this thing, how will I check this, I will explain it how will I check this, I will explain it again in the next iteration, again in the next iteration, then I will explain it in the second iteration, then I will explain it in the second iteration, now this duplicate is coming, so now this duplicate is coming, so I need to check it, now BB has come. I need to check it, now BB has come. I need to check it, now BB has come. checked D, when is D coming last, I myself am on six and D came on fourth, so I need to check, D will not come again, I came to know that D will not come again, so I myself come again. If we did not check the duplicate corners, If we did not check the duplicate corners, If we did not check the duplicate corners, then one of our problems got solved then one of our problems got solved that if we save the index and keep it that if we save the index and keep it with us, then my work would be the same. Now with us, then my work would be the same. Now how will I know that I how will I know that I already have a character and check it. already have a character and check it. already have a character and check it. not there, then for this I will make a bullion galleon, this is also I will make basically one of 26 size, this also I will make 26 As in which basically everything will initially fall first, this will be representative for J, this will be for A, This will be for 'C' This will be for 'C' This will be for 'C' till 'J' for 'Ydi'. Keep all the initials false and till 'J' for 'Ydi'. Keep all the initials false and I will make them true as each character comes, I will make them true as each character comes, all these are also false. Okay, all these are also false. Okay, I will also give it indexing from 0 to I will also give it indexing from 0 to 25. Now let's do it again. 25. Now let's do it again. us do the same part again but us do the same part again but now we will do it with the help of Lin Aare, so now we will do it with the help of Lin Aare, so first of all C came, as soon as C came, I made first of all C came, as soon as C came, I made it true, brother, C has come to me, it true, brother, C has come to me, now you make it true. now you make it true. now you make it true. I made C true, now BB came, first of all, checked whether C is bigger than me, yes, if he is bigger then I have to ask C, can C come later, then we Yes, I am Yes, I am Yes, I am standing on one index, C is coming for the last seven times, so standing on one index, C is coming for the last seven times, so C will come later, so I C will come later, so I removed C. When I removed C, what did I do, I made C removed C. When I removed C, what did I do, I made C fall first, fall first, I made C fall first and then I made C fall first and then Later, when I brought B in my answer, I made Later, when I brought B in my answer, I made B true. B true. I made B true first. I made B true first. I made B true. Okay, after this came A. I made B true. Okay, after this came A. Now A got it checked. What is the first Now A got it checked. What is the first thing? A first. thing? A first. thing? A first. A falls already, so we will check A. Now get A checked. I am asking B. Can you come later? Now I am standing at the second index. Will B If it comes later, we If it comes later, we If it comes later, we removed C and B, removed B from the answer, removed C and B, removed B from the answer, then I made B false from here also, then I made B false from here also, and then and then removed it, after that I removed it, after that I removed A from the answer, so A is false. removed A from the answer, so A is false. removed A from the answer, so A is false. I made it true here, now A is the answer, it is ok, now as C has come, first I have checked C, first C is not coming, then C is false, If it is smaller than C then there is If it is smaller than C then there is If it is smaller than C then there is no need to ask C God has no need to ask C God has come D after that D I got it checked come D after that D I got it checked should be said that should be said that C had come earlier so I should make it true. C had come earlier so I should make it true. Okay, D came after this. D said Okay, D came after this. D said that he is a younger person than me, so there that he is a younger person than me, so there is no need to check me. D is no need to check me. D came himself. As soon as D came himself, he was bullion array which is came himself. As soon as D came himself, he was bullion array which is present. present. present. again came C. I checked whether C is already present or not. So I did not have to check. If C is true, I skipped it. Falls So now B asked Falls So now B asked Falls So now B asked D can you come later then d4 is D can you come later then d4 is ok and K himself is standing on b6 so ok and K himself is standing on b6 so can B come later if he can't come then d can B come later if he can't come then d himself come and join here and C came after that C himself come and join here and C came after that C Here I have made B also Here I have made B also true. C is already there, so we did true. C is already there, so we did not add C and we have done this work. not add C and we have done this work. Now look, there is one more problem that Now look, there is one more problem that how will we remove these characters, the ring which would how will we remove these characters, the ring which would be mutations, so for this mutations, so for this we can use we can use what is the stack of the stack, what is the stack of the stack, we will keep adding characters in the stack and will check from there, we will keep adding characters in the stack and will check from there, now let's see how to do that too. now let's see how to do that too. I told you Nana, there is a lot of it in this. I told you Nana, there is a lot of it in this. All the things are being used, okay, so for this All the things are being used, okay, so for this I will use the stack. Okay, so I will use the stack. Okay, so I have used the stack. I have used the I have used the stack. I have used the stack here. Now look in the stack, stack here. Now look in the stack, now how to do it, let's see it first. First, now how to do it, let's see it first. First, I will do it once. I will do it once. I will do it once. again I make it all false, once for all, false, false, falls and false, so I made it all false, first, now what did I do, now what did I do, the tag As soon as A came, what should I do first? As soon as A came, what should I do first? As soon as A came, what should I do first? I made C true. Okay, I made C true. Okay, after that came B. Now B saw the after that came B. Now B saw the peak of the stack. B peak of the stack. B is standing here waiting. Is there a bigger character than me on the peak of the stack? is standing here waiting. Is there a bigger character than me on the peak of the stack? Brother, if he is elder then ask him, will he Brother, if he is elder then ask him, will he come later? B said, ' come later? B said, ' Yes, I will come later. You are standing at one index, Yes, I will come later. You are standing at one index, I can come at seven index too, I I can come at seven index too, I can come from second to end, so you can come from second to end, so you come first.' come first.' come first.' false, I made C false, I made B true, I made B true, and in place of C, who put B? Okay, now I turned to B, now it's A's turn, now it's Asked again, did you understand? A asked again. You have to Asked again, did you understand? A asked again. You have to ask B only if you have a big character. If it is big ask B only if you have a big character. If it is big then you have to ask. B, can you come later? then you have to ask. B, can you come later? He said yes, I can come later He said yes, I can come later because you are currently on the second index. because you are currently on the second index. because you are currently on the second index. and I B is coming till the six index. If the last index is six, then if I come till six, P can come somewhere in between. When I come till six, he said, you get removed, work to remove B from Do it Do it Do it and A came to his place. When A came here, A and A came to his place. When A came here, A marked himself that I had come marked himself that I had come so that he would not come again. So I made I made I made C is saying that you are younger than me so I do n't need to ask you. I came just like that and got myself true I I I came after C. D also came straight away because he was younger than him. He also declared himself true saying that he was okay and came after this again. Now see, when C came again, If there is truth in chaka, If there is truth in chaka, If there is truth in chaka, then there is no work for tr, if there is no work for tr, then si ho has then there is no work for tr, if there is no work for tr, then si ho has come, now b has come, now b has come, now b has come, now b has asked, no, earlier had come to bring ko, now b aa asked, no, earlier had come to bring ko, now b aa b has asked d, can you move away, b has asked d, can you move away, why because b is so. why because b is so. why because b is so. saw D, D is saying brother, I am standing on the fourth and you are standing six, I will not come later, so if you want to come, then you come to me, then B, B, B, I would have come, after that, C came again, now Check it, I checked C, now B is true, Check it, I checked C, now B is true, Check it, I checked C, now B is true, check C, so C is C, it is already true, it check C, so C is C, it is already true, it means it is true, if not again, then means it is true, if not again, then what happened to us, this answer is completely what happened to us, this answer is completely ready, now look at the answer, how to prepare. ready, now look at the answer, how to prepare. First I need to know how to remove all the elements from st, First I need to know how to remove all the elements from st, after that I have to reverse it. after that I have to reverse it. Okay, and this work is very easy. Okay, and this work is very easy. If we do it first, then if I reverse it in the answer, If we do it first, then if I reverse it in the answer, then what will it become? then what will it become? A.D. Okay, this will become my answer. A.D. Okay, this will become my answer. Answer, this part is very simple, Answer, this part is very simple, how to do it, see first of all let's go to how to do it, see first of all let's go to our code and start coding one by one, our code and start coding one by one, so I came here, first I will do everything first, I will have to make it Index Okay first of all let's Index Okay first of all let's Index Okay first of all let's create create it so I created a last index array it so I created a last index array int last index last index equal to int last index last index equal to new int 26 so I created a last index array new int 26 so I created a last index array now how will I put that let's see now how will I put that let's see for int a e 0 a lesson add length a for int a e 0 a lesson add length a p p p convert the character into index, so first of all I take out the character. When I added it, I inserted the character here, after that I take out the index. How will the index come out? I wrote the index, now How does it happen? How does it happen? How does it happen? Look in the convert index. First of all, I Look in the convert index. First of all, I changed the character to 'A'. Okay, now let me changed the character to 'A'. Okay, now let me explain a little how it happened. However, explain a little how it happened. However, it is worth explaining in this question. it is worth explaining in this question. Look, what happens is that we have a Look, what happens is that we have a value of 'A' like lets say. value of 'A' like lets say. value of 'A' like lets say. I don't remember A, from Let's, the value of A is 56, then the value of B is 57, the value of A is 58, so if I go on till A, then I have done here like let's come in the vector, then what is A mine A, 57 56 What will happen to mine A, in 57 56 What will happen to mine A, in 57 56 What will happen to mine A, in this way I will get the Ix this way I will get the Ix which we had made last Ix, he had which we had made last Ix, he had taken G, I was repainting G, A, taken G, I was repainting G, A, so it was getting repainted with this, so in that way, so it was getting repainted with this, so in that way, this part of mine will be done okay. this part of mine will be done okay. this part of mine will be done okay. I am not going to go too deep into this here because by going too deep here, we will miss the main question, what will I do now, see my last index, which is the last index, last index array, index of the last index, What will I put on the index of the last index, I put it What will I put on the index of the last index, I put it What will I put on the index of the last index, I put it which is our frequency which is which is our frequency which is where our character is coming and where our character is coming and last there, after this I will have to create last there, after this I will have to create a bullion present whether it is a bullion present whether it is present or not, otherwise I have created a bullion for it. present or not, otherwise I have created a bullion for it. Present array created Present array created Bullion Present is equals to new Bullion Present is equals to new Bullion In this I also made it of size 26 Bullion In this I also made it of size 26 Look whenever an array of Bullion type Bullion Cy Look whenever an array of Bullion type Bullion Cy is created then what happens in it too is created then what happens in it too Initially falls are always the same Initially falls are always the same Initial falls are fine all the time Initial falls are fine all the time Initial falls are fine all the time we make integer type, what is there in it is initially zero, similarly what is there in bullion type is always false everywhere, so this thing has been done directly, now I have done this thing, what to do now? Now I have to create a stack, what type of tag have I character character character, character character type, I have character, character character type, I have created a stack, I have named it created a stack, I have named it New New New New Stack, okay, so I have created something like this, Stack, okay, so I have created something like this, now what I have to do is to travel through the entire string now what I have to do is to travel through the entire string and create a and create a and create a things according to that character, okay, so first of all, I saw, first of all, I put a loop for aa e 0 aa le addle r l ok i plus ps, first of all, I extract the character of the string, And if I want to extract both the indexes, I And if I want to extract both the indexes, I And if I want to extract both the indexes, I copy it from here, I copied it and pasted it here, okay, so I extracted the character, now I copied it and pasted it here, okay, so I extracted the character, now see when I have to work, when our boolean see when I have to work, when our boolean which is our that which is inside the answer stack which is our that which is inside the answer stack if if if means I put that index inside the present present and if it comes false then only I have to work, that means how since late we already have A in the string, Go and Go and Go and check that it is not there because it is check that it is not there because it is false and whenever any element is false and whenever any element is present in it then it has to be made true, otherwise only if it present in it then it has to be made true, otherwise only if it is false then we have to work is false then we have to work because it is not already present, because it is not already present, it means that it means that it means that will understand better. Okay, so first of all I checked that it is false. If it is false, then we will work. If it is false, then what do we have to check? If the size of the stick is greater than that, then the Only then will Only then will Only then will you go and pop it from it, right? Which is the peak element of the stick. you go and pop it from it, right? Which is the peak element of the stick. If it is big, it If it is big, it is bigger than our character, only then we is bigger than our character, only then we need to pop it. If it is small, then it was going to be need to pop it. If it is small, then it was going to be popped directly. You have seen it. popped directly. You have seen it. popped directly. You have seen it. and what else have to be checked, is it coming later or not? That means we have to check the frequency, the last index, we have to check the last index, we have to check that, so for that I have to call it the peak of the stack. I would make this square dot a little square, widen it a little bit, and subtract the vector that is at the top of the stack. If it's fine with a, then I will get its index and I will check if it is big, if it is big. We had seen that only if it is bigger than me, I can pop it. First, look, the size of the stack should be greater than zero. The It It It should be bigger than our character. Now I have to check should be bigger than our character. Now I have to check whether it is coming later or not. Otherwise, whether it is coming later or not. Otherwise, I checked in the last index. The I checked in the last index. The character which is from the peak of the stack is somewhere character which is from the peak of the stack is somewhere on the element at the last index. It should be bigger only on the element at the last index. It should be bigger only then. then. then. what do I have to do before popping? Before popping, I have to go to our present element and mark it false because if we are popping then that element will be removed from there, so what do I have to do I have to go to the present array, where in the present should I have to go to the present array, where in the present should I have to go to the present array, where in the present should I copy this part, so I copy this part, so that I can get the peak of the present also, I have to that I can get the peak of the present also, I have to go to that array of the present and go to that array of the present and mark it as false, mark it as false, what do I have to do after doing false, what do I have to do after doing false, I have to do I have to do I have to do pop from there, so dot, I made it pop from y. After popping, till the time oh ok, if will not come in it, why will come in it because there may be two or three letters together which we have to pop, okay. Going ahead, we will discuss it in the example, this is also fine, so I have done it, now the character that was there will itself be pushed, it itself was always being pushed, so we have to push it, so I said Cuttack Dot is the push The character was pushed, The character was pushed, The character was pushed, after pushing it, after pushing it, what do we have to do in our present array. If we have to what do we have to do in our present array. If we have to mark it also, then mark it also, then what will I mark in the index of present? what will I mark in the index of present? After marking, when the whole of the After marking, when the whole of the After marking, when the whole of the run then what will I have in the stack and all the eight elements will come. Now what do I have to do? Basically now I have to create my string. If we have to make repeated connections in the string in Java then we should use String Builder. So I have used String Builder here. Do this and initialize the MT string, now what will I do, see while the dot size is greater than zero, what to do till then, keep appending in string builder, pop whom with tag and append in string builder, now see the answer that would have come, If it has come reverse because of , then If it has come reverse because of , then If it has come reverse because of , then what do I have to do with it? Basically, I have to what do I have to do with it? Basically, I have to convert A. B. Dot. First of all, convert A. B. Dot. First of all, I have to reverse it. After reversing it, I also have to convert I have to reverse it. After reversing it, I also have to convert it into string. So, it into string. So, I completed this step all at once, I completed this step all at once, okay. okay. okay. although the code is quite big, once you run it, see if it is working properly or not, just submit it just submit it and let's see in this case, if there is any error. and let's see in this case, if there is any error. So we will see and solve it, okay, So we will see and solve it, okay, maybe it has been submitted, otherwise it would have become red again, maybe it has been submitted, otherwise it would have become red again, okay, once it has been submitted, let's take it to okay, once it has been submitted, let's take it to where on our white where on our white board and do this. board and do this. Okay, so I have this one. Okay, so I have this one. Okay, so I have this one. mainly we want this part, okay, I mainly want this part, so I got it page question is quite good, a lot page question is quite good, a lot of things are being used in it, okay, you will have to of things are being used in it, okay, you will have to see it twice. see it twice. see it twice. so that you can understand it better. If you can understand it in one go, then it is very good. Once I see the example, have they do it, I would have written it down. I would have written it down. I would have written it down. S D T B and I also write down its indexes 0 1 2 3 4 5 A First of all we will have to create a last Now see how many B CDs are there in this, so by the way, let's Now see how many B CDs are there in this, so by the way, let's make this four, make A B CD and make this four, make A B CD and make this four, make A B CD and account, how will it be the last one? account, how will it be the last one? First of all, First of all, what will come if I do C minus sign A? If I come, what will come if I do C minus sign A? If I come, what will happen after coming, but basically after going to T, it will be what will happen after coming, but basically after going to T, it will be indexed in C. indexed in C. indexed in C. then it will come to B, then it will become N, then it will become A, then it will become T again after coming to C, so I did it on Y, then it will so I did it on Y, then it will come to D, it will become F, then it will come to come to D, it will become F, then it will come to C, then it will become C, then it will become F. F. F. in F, after that came in B, C came in in F, after that came in B, C came in B, came in B, came in Si and C came again in Si and C came again in Se Bat Se Bat Bar, Last Index or Last Ix Bar, Last Index or Last Ix D. Now what do we have to do, let's make B, we D. Now what do we have to do, let's make B, we will make B small, its region because will make B small, its region because We have We have four conductors and placed them everywhere, this is for A, four conductors and placed them everywhere, this is for A, this is for B, this is for C, this is for Y, we have also kept this complete this is for B, this is for C, this is for Y, we have also kept this complete false because this is false because this is initially false only, okay, initially false only, okay, after this I made a stack, made a stack after this I made a stack, made a stack now. now. now. two or three things, we are getting the character and we are getting an index. What will come in the index? Okay, now we have seen that present of index is false, present is false. Now see, why is C false? Exactly, because if it is false, it means that it is not present. Not quite present. The size of the stock is zero, which is greater. Yes, If the If the If the condition is zero then if the first phase happens then they get stuck and condition is zero then if the first phase happens then they get stuck and told the conductor to push it, we pushed it and went to present of index present of two and made it true, made true of present of two went to present of index present of two and made it true, made true of present of two then went to present of two and then went to present of two and I did it. I did it. I did it. now it's B's turn. Now look, now B has come in the character and B has come in the index. What has come in the index? One has come in the present of index. Present of one is false. Yes, it is absolutely correct, why The The The size of the stack is not zero. Now what is the size of the stack is not zero. Now what is the element at the peak of the stack? What is the element at the peak of the peak of the stack? stack? stack? So So this is also greater, what does it mean, what did this is also greater, what does it mean, what did they do, it means that you have to pop, so they do, it means that you have to pop, so when we did the pop, when we did the pop, what did I do before the pop, what did I do before the pop, before the pop, I said before the pop, I said go to the peak of the stack, meaning go to the present array, go to the peak of the stack, meaning go to the present array, you mark C as false. you mark C as false. you mark C as false. mark the C as false. After marking it as false, what do you have to do after marking it as false? Pop it from the stick, I have popped it, then remove it from here, what happened as soon as it was removed, it got removed Remove, what are you saying now? If you go to Remove, what are you saying now? If you go to Remove, what are you saying now? If you go to check again, if the size of the stack check again, if the size of the stack is zero, then it will not be is zero, then it will not be able to be checked. Now what happened to the stack, able to be checked. Now what happened to the stack, push the character. It was character 1 and the present index of push the character. It was character 1 and the present index of index was one. Go to it and make true. index was one. Go to it and make true. Make it into two present of index. Make it into two present of index. Look what we understood from true. From true we understood Look what we understood from true. From true we understood one more thing. See one more thing. See what element is there in the stack till now. It is what element is there in the stack till now. It is becoming true for that. Look, there is B in the stack too, becoming true for that. Look, there is B in the stack too, so for B. so for B. so for B. clear to you. Now it is the Okay, now A is stuck, Okay, now A is stuck, so A is in the character. What is the index of A? Is it so A is in the character. What is the index of A? Is it zero? Okay, that means I zero? Okay, that means I hope. hope. hope. index is present then it is false, yes is false, if the size is zero, otherwise this condition is true, it is true that the peak of the peak has reached, BB is greater, yes, is also true then last index chk last is also true then last index chk last is also true then last index chk last index of whose b's last index of whose b's last index of whose b's b's six is sis index of whose b's b's six is sis greater than aa's value kya hai to greater than aa's value kya hai to is 6 greater than is yes to is is 6 greater than is yes to is ok this is also true if ok this is also true if ok this is also true if are correct, then it means that now it can pop from here, all three conditions have become true. Now in the present of int, go from the peak of tuck and subtract one. It is okay, meaning it goes here and says Make it fall, Make it fall, Make it fall, after making the fall, pop it, pop it, pop it, pop it, pop it, now after making the fall, pop it, pop it, pop it, pop it, pop it, now again, is the again, is the stack empty now, Chu Poo's Poo is empty, stack empty now, Chu Poo's Poo is empty, after it is empty, said, push it, push it, push it and said. and said. and said. index and do 'Y' on 'Y', 'I marked 'Y', I understood 'C', then 'C' came to me, 'Y' understood 'C', then 'C' came to me, 'Y' comes to me, comes to me, what is the 'ix' of 'Y', what is the 'ix' of 'Y', now again now again present of index is false, the present of index is false, the size of the half stack is zero. size of the half stack is zero. Go and make it true, I made it true as Go and make it true, I made it true as well, okay, so I hope well, okay, so I hope you understood this part also well, you understood this part also well, after this again after after this again after rotating the loop, it came towards D. When it rotating the loop, it came towards D. When it came towards D, it wrote here D. came towards D, it wrote here D. came towards D, it wrote here D. index of What is What is greater than greater than make it true, then it has been made true. What do you have to do after making it true? The loop will run again. C has come. Now let's see how our work with C will be done. Present of index is false, meaning here also I change it, first came in the first character. What is the meaning of 'C' in C index? So this is false. False means we don't have to do anything but skip it. See how well you understood it. How did you skip it? We came to know because it has come before so we Now B has come, brother, Now B has come, brother, Now B has come, brother, everyone. B has come. B said, I am still everyone. B has come. B said, I am still in the line. B has come, what is the index of B? in the line. B has come, what is the index of B? One is okay, it is a little r. It has come, its One is okay, it is a little r. It has come, its index is false, okay, the size of the stack index is false, okay, the size of the stack is zero. is zero. is zero. greater than zero. Exactly what is the peak of the stack? of the stack? of the stack? index of sorry check last index of stock what is the puck of last index of stock what is fo greater than aa ki valya kya ki sagter hai nahi hai He said brother If you have to come first, If you have to come first, If you have to come first, then push character B in the stack. then push character B in the stack. After pushing character B, tell him to mark it as true. If After pushing character B, tell him to mark it as true. If you do not mark it as true on your own, then there will be a you do not mark it as true on your own, then there will be a problem, so after coming here, problem, so after coming here, I also marked it as true. I also marked it as true. After C, we moved ahead After C, we moved ahead towards C. Now C has come again. The index of C is two. When C towards C. Now C has come again. The index of C is two. When C came again, we came again, we saw again that it is true. In the case of true, saw again that it is true. In the case of true, we do not have to do anything, so we we do not have to do anything, so we finished the thing with this. finished the thing with this. finished the thing with this. ready. Now what I did in the next step is quite similar. What I did was, first of all, I created a spring builder and appended it upside down, BDCA, after that, I made it reverse. What about doing reverse? Made A CD B and converted it into string and returned it. Okay, that part is quite simple. You guys, I hope you must have understood it very well. I tried a lot so that I can explain it to you very well, so it is okay. If you have any doubt then you can come and ask on our Tegra channel, you can give your suggestion in the comment section, whatever is your work, it is ok and see you guys tomorrow where we Then thank you. If you Then thank you. If you Then thank you. If you liked the video then like the video and liked the video then like the video and subscribe the channel. See subscribe the channel. See you guys tomorrow. | 2024-03-24 10:23:05 | 316 | LeetCode 316 | Remove Duplicate Letters | Day 46 | 100 Days LeetCode Challenge | DSA with edSlash |
|
NqIfPH6iJhU | [Music] with lonely Dash and today we're going over toplet's Matrix number 766 of elite code which says given an M by n Matrix return true if the Matrix is dopelets otherwise return false a matrix is toplets if every diagonal from top left to bottom right has the same elements I'm only hoping I'm saying this word right hopelets uh if anybody knows if I'm doing it wrong please let me know uh anyway so here is the example Matrix that was given in the question and I've written it out as an actual Matrix over here to kind of give you the idea of what it would look like in your actual coding and we know that this is a toplets matrix right because up here in the top left hand corner we can see a one and if we go down one and oh right one we can see it's also a one we go down one and right one and I can even show you this this here this diagonal all of the numbers are exactly the same if we do another diagonal all of the numbers are exactly the same and another diagonal all of the numbers are exactly the same so that is a hopeless Matrix now in order to figure out whether something needs to be returned as true we have to start off by identifying two things first we need to identify the number of rows here that we're dealing with and we need to identify the number of columns that we're dealing with so obviously here we have three rows and four columns and so I'm just going to identify them and I'm sorry I'm kind of writing with my mouse today it doesn't look great but here's our number of columns and our number of rows using zero based indexing okay so really we know that if we're thinking of it in terms of M and N up here as we are given in the question our m is equal to the number of rows which of course is 3 and our n is equal to the number of columns which is four and we're going to need to know that information in order to write our code so when we're thinking about it we could brute force it and we're starting we'll say okay in order to solve this we're going to look at our very first number in our uh row and our very first number in our first column and we're just going to say okay is 0 0 the same as 1 1 and we'd say yeah of course we're just adding one to each one of these um each one of these indices and we'd say okay that's the same We'll add it again we'll add one to this and we'll add one to this and we'll say okay is 2 2 the same well yeah it is and we could go through all the iterations and that would be perfectly fine it'd be a little bit more complicated but for purposes of today we are going to start at this lovely number we're starting at one one and instead of comparing down and right we're going to compare up and left okay and the reason is is that we're going to get down here eventually and I'll make a little bit more clear we're going to end up down here and because we know the number of rows as soon as our I guess you could call it a pointer as soon as we leave our area it's just going to stop and we're going to move on so I'll give you an example we'll work through it so we'll say okay is our number at 1 1 the same as our number up and left at 0 0. yes of course it is fantastic we're going to move on but we're not going to move on to the next number here we're going to move this direction right because we have to finish all of the rows so then we're going to ask ourselves okay is the number here at 2 or I should say 1 2 is it going to be the same as 0 1 which is this number yes it is great we're moving on to the next column and we're going to ask ourselves okay is this number the same and this number is 1 3 is it the same as 0 2 and of course it is yeah yes and we can't move right anymore so instead we're going to move down and go back to our one column and we're going to do the same thing comparing these two numbers and then we're going to compare these two numbers and then we're going to compare these two numbers one and two and by the time we're finished doing that we'll have compared these these these and these and the only things that we have left to compare are this 4 and this 9 which interestingly we don't have to compare it because they have no diagonals so if we can get through this entire Loop of comparisons then we can return true if we complete the loop however if at any time the number to the top left does not match the number or the element that we're dealing with we're just going to return false okay so I know that sounds maybe a little bit complicated but when we write some code it'll become more clear so again if we're looking over here on the right side of our matrices we're going to compare one number to the number above and left two of it then we're going to continue on in the column and our next step will be to compare that number to the number above and left of it and then we're going to move on again and we're going to compare the number on the right side to the number above and left and as soon as we run out of and room in our column we're going to move back to index one and compare the next row until we get to the end of that column and when we reach the end of the column at the end of the rows we are done and we can return our answer okay let's see for our edge cases let's just take a for our edge cases let's just take a look and see what our constraints say look and see what our constraints say okay so we know that m is going to equal okay so we know that m is going to equal The Matrix dot length or the length of The Matrix dot length or the length of our Matrix which means that's going to our Matrix which means that's going to be our number of rows we know that our n be our number of rows we know that our n is going to be the number of columns is going to be the number of columns because of Matrix I dot length in this because of Matrix I dot length in this case I guess they're using Java is case I guess they're using Java is basically saying this is Matrix one here basically saying this is Matrix one here or I'll even highlight it here this is or I'll even highlight it here this is Matrix I the length of it is 4 so that Matrix I the length of it is 4 so that tells us the number of columns so that tells us the number of columns so that is going to exist because M so our rows is going to exist because M so our rows we're going to have at least one row and we're going to have at least one row and our n is going to have at least oh it's our n is going to have at least oh it's going to be less than 20. so it's going going to be less than 20. so it's going to be fairly small equal to or less than to be fairly small equal to or less than 20. uh okay so I guess theoretically we 20. uh okay so I guess theoretically we could have no columns we can't really could have no columns we can't really have negative columns it doesn't say it have negative columns it doesn't say it can't be zero so we could theoretically can't be zero so we could theoretically have I guess one column because we would have I guess one column because we would do a single index at any rate and that do a single index at any rate and that our Matrix i j is going to exist our Matrix i j is going to exist entirely so there's not really any edge entirely so there's not really any edge cases to consider let's move on to some cases to consider let's move on to some pseudocode for our pseudo code you can see I'm just going to be typing it into the python section of the elite code website again it doesn't matter where you type it so the very first thing that we need to do that we talked about was identify identify okay so I'm just going to do identify the number of rows in Matrix okay so that's the very first thing we need to deal with and of course we need to identify the number of columns in our number of rows right so we have our rows which go left to right in our columns which go up and down if we don't know the numbers of each we won't be able to move forward so that's the first two things then we're going to have to create a loop so Loop through each row and then within that we're going to have to do a nested Loop that also that Loops through each column right because when we talked about it we knew that we're starting on second row but we're going to go through the column first and then move on to the next row so that's why we're looping through each row that also Loops through each column okay so then if the element that is above and left of the current element um is not the same so it's not if it's not the same then return false okay otherwise uh we are going to continue the loop right because it's just going to Loop through each one of the columns going left to right and then it's going to Loop down through each one of our rows uh if the loop finishes then return sorry then return true because if it completely finishes the loop that means that we are in a topics Matrix and you just return true now it does not look like a whole lot of code to write and hopefully this will become more clear when we get to actually foreign okay as you can see I just foreign okay as you can see I just copied our pseudocode into the Java work copied our pseudocode into the Java work area of elite code website and we're area of elite code website and we're going to follow line by line so first we going to follow line by line so first we need to identify the number of rows in need to identify the number of rows in Matrix so we know it's going to be an Matrix so we know it's going to be an integer so integer rows we'll call it integer so integer rows we'll call it rows for the number of rows is just rows for the number of rows is just Matrix dot length right Matrix dot length right simple straightforward next integer simple straightforward next integer columns right we need to find out the columns right we need to find out the number of columns in each one of our number of columns in each one of our rows and that is going to be the length rows and that is going to be the length of the very first row in our Matrix so of the very first row in our Matrix so integer rows equals Matrix length and integer rows equals Matrix length and integer columns equals Matrix of our integer columns equals Matrix of our first row length l e n g t h am I just first row length l e n g t h am I just misspelling that entirely links and misspelling that entirely links and again length there we go again length there we go now that we have identified our number now that we have identified our number of rows and identified a number of of rows and identified a number of columns we can get rid of that we need columns we can get rid of that we need to Loop through each row that also Loops to Loop through each row that also Loops through each column okay and so we're through each column okay and so we're going to use a for Loop so 4 and we'll going to use a for Loop so 4 and we'll use integer I equals zero so this is use integer I equals zero so this is going to be you know what let's change going to be you know what let's change it to row right so integer row so it's it to row right so integer row so it's going to be one row and it's not even going to be one row and it's not even going to equal zero it's going to equal going to equal zero it's going to equal one right so we typically start at zero one right so we typically start at zero because we think we're going to start at because we think we're going to start at the beginning of any of our rows or the beginning of any of our rows or matrices but remember we're not starting matrices but remember we're not starting looking at the first element in our looking at the first element in our Matrix we're looking at the one on the Matrix we're looking at the one on the second row in the second column and when second row in the second column and when we're using zero indexing we're going to we're using zero indexing we're going to have to start on row index one instead have to start on row index one instead of zero so for integer Row one as long of zero so for integer Row one as long as the row is less than rows right as the row is less than rows right because as soon as we run out of the because as soon as we run out of the number of rows we've got to stop our number of rows we've got to stop our Loop and we are going to iterate row Loop and we are going to iterate row plus plus it goes by one okay so that's plus plus it goes by one okay so that's what's going to iterate us through each what's going to iterate us through each row but we also need to iterate through row but we also need to iterate through each column so we're going to do the each column so we're going to do the same thing so for integer column same thing so for integer column oh column that's going to equal 1 and as oh column that's going to equal 1 and as long as column is less than columns less long as column is less than columns less than the number of columns we're going than the number of columns we're going to iterate also by one to iterate also by one all right so that's what's going to take all right so that's what's going to take us through column M ends s there we go us through column M ends s there we go make sure I spell it all right so this make sure I spell it all right so this line is going to take us from left to line is going to take us from left to right and then as soon as we finish the right and then as soon as we finish the first or as soon as we finish that row first or as soon as we finish that row this line is going to take us to the this line is going to take us to the next row below it and all we're doing is next row below it and all we're doing is comparing the number that we're comparing the number that we're iterating from or iterating through with iterating from or iterating through with a number that is above and left of it so a number that is above and left of it so how do we do that so if how do we do that so if Matrix Matrix and in this case row right because this and in this case row right because this is going to start at one row column and is going to start at one row column and this is also going to start at 1 does this is also going to start at 1 does not equal Matrix not equal Matrix rho minus 1. rho minus 1. and column and column minus 1 right so our row and column minus 1 right so our row and column we're starting at 1 1 and we want to we're starting at 1 1 and we want to know if it's the same as up left which know if it's the same as up left which means it'd be one minus 1 is 0 and 1 means it'd be one minus 1 is 0 and 1 minus one is zero so zero zero so if it minus one is zero so zero zero so if it is not the same as the diagonal up left is not the same as the diagonal up left then we need to return false then we need to return false false otherwise it's just going to false otherwise it's just going to continue through our for Loops until we continue through our for Loops until we reach the very very end and when we reach the very very end and when we reach the end of our loop we're going to reach the end of our loop we're going to return true so if we get to the end of return true so if we get to the end of our for Loops without returning false our for Loops without returning false that means it is a topolitz uh Matrix that means it is a topolitz uh Matrix and we're done so that should be all of and we're done so that should be all of the code that is necessary for solving the code that is necessary for solving this problem let's hit run code and see this problem let's hit run code and see how we did and accepted let's hit submit to see if it fits all of our test cases we'll have a look over here and yes it's done now this shows that it's two milliseconds but faster only than 38.07 uh I don't know why it says that it's usually a pretty darn good way to solve this type of question but that's it that is all the code you need in order to solve The topolitz Matrix question using Java | 2024-03-21 16:07:59 | 766 | 766. Toeplitz Matrix - Java LeetCode Solution |
|
PiJ8WVv-mP8 | Hello Welcome Back Friends Today We Are Going to Welcome Back Friends Today We Are Going to Solid Code Problem 498 A Lips in Awards Solid Code Problem 498 A Lips in Awards Show's One Environment Report and Beach Sail Show's One Environment Report and Beach Sail Kiss Battleship Another Anti-Return Number of Kiss Battleship Another Anti-Return Number of Battleships Folded Inside Battleships Folded Inside Battleships Can Only Play List Battleships Can Only Play List Horizontally and Vertically On Board in Horizontally and Vertically On Board in Words Words Member in and the Member in and the chapter we battleships time just us chapter we battleships time just us example clear for the explanation to edit can see his example clear for the explanation to edit can see his own this is one battleship and own this is one battleship and sister mother battleship so others can give vertical or horizontal only sister mother battleship so others can give vertical or horizontal only possible to possible to battleships has come net how many battleships has come net how many battleships and there battleships and there battleships and there is Ashu for this Problem Hui Can Easily Solve Organizing Like a Difficult Hui Travels Matrix from the Beginning Cell to the End Cell and Wherever Hui Find Character One Day Will Be Counted as One Battleship Goddess The The The show will try to go for directions for show will try to go for directions for example after and hydrating like this metric example after and hydrating like this metric from beginning software and from beginning software and because it means the Twitter account Battleship S because it means the Twitter account Battleship S 1251 Battleship and will try to interest in 1251 Battleship and will try to interest in evil Try to deficit in all four evil Try to deficit in all four directions like this is one direction and directions like this is one direction and Right side inside don't side and in the left Right side inside don't side and in the left side of this will take you were going out of side of this will take you were going out of the world din will just returned at you inside the the world din will just returned at you inside the board and what do you will board and what do you will open the app quit Rahul Kumar all details with open the app quit Rahul Kumar all details with tejaswita star you know what to tejaswita star you know what to tejaswita star you know what to different character so I do n't and on accounting battleship you know of Agni and lag more times for example hui seedhi 600 bill account battleship is vansh and will change the verses star character is clear aaj to vrat ki vriddhi hui a clear name Here In The Matrix And Will Andar Here In The Matrix And Will Andar Here In The Matrix And Will Andar Plus Form For Stroke Player Plus Form For Stroke Player Song Again Hui Servi It Means The Two Front Song Again Hui Servi It Means The Two Front 's Second Battle Of Years Will Prevent 's Second Battle Of Years Will Prevent Account Battleship And Will Apply To Account Battleship And Will Apply To Divorce In All Four Directions Care Divorce In All Four Directions Care That Sui Will Make This Character A Star That Sui Will Make This Character A Star So I Will Not Count Login And Solve Veer So I Will Not Count Login And Solve Veer Is Silver Gain C 10 Gram Doodh Defes So Is Silver Gain C 10 Gram Doodh Defes So Will Do Like Ka Up And Down World And Will Do Like Ka Up And Down World And Left Side And Don't Like Share And Will Left Side And Don't Like Share And Will Change This Character A Celestial Against Will Change This Character A Celestial Against Will Not Count Begins Again You Witch Year Song Not Count Begins Again You Witch Year Song Again selections will try Tubelight ka Again selections will try Tubelight ka Dandruff World types of download and in the Dandruff World types of download and in the left side and will changes character left side and will changes character apps apps and pain wherever and pain wherever setting on this second universe the setting on this second universe the control of matrix like you will go near and control of matrix like you will go near and dear su will see you will not see a dear su will see you will not see a senior ministers senior ministers senior ministers Another Battleship Already Process Of Development This Battle Scene Already Discounted Dushwar Them Z1 Battleship 100 Deaths Your Solution Will Work For Battleships In Board So Let's Go Through The Solution Superstar Creative Everyone Contest Battleships And Here That They Are Going To Read through the two back to board will have been given Read through the two back to board will have been given Read through the two back to board will have been given substances recently at you bittu substances recently at you bittu matrix from matrix from 028 board link earlier 028 board link earlier and interested to find the character and interested to find the character experience that is where the battleship is going to start starting experience that is where the battleship is going to start starting with SVC at with SVC at character on the board will increase in the character on the board will increase in the Number Battleship Battleship Servi And Will You Number Battleship Battleship Servi And Will You Life Strengthen This Community Sill Subtle Subtle Edifice Life Strengthen This Community Sill Subtle Subtle Edifice Civil Works No Merger Civil Works No Merger Notifications So 0 And Greater Than Body Notifications So 0 And Greater Than Body Language Se Zor A Greater Than Gold For Language Se Zor A Greater Than Gold For Gift Character Data And Details That One Gift Character Data And Details That One Day Were Rich Nothing Doob A Farce Day Were Rich Nothing Doob A Farce Day Were Rich Nothing Doob A Farce otherwise we will mark the celebs who want to change the character to another character and share with the people with a difference in all directions for directions meaning of this leaflet from this day a sale you you you minus one tasty come minus one row end column SIM columns a few of the world with me to go and right side ki daroga this time end column will visit plus one because they are going into the column Was going download here oo will Was going download here oo will Was going download here oo will increase by one convenience plus one oo increase by one convenience plus one oo a clear and calling specific a clear and calling specific objectives naseem column and issue gond left objectives naseem column and issue gond left side clear daaru will just as in a side clear daaru will just as in a problem will decrease by one development problem will decrease by one development versus previous column on versus previous column on 220 initial chairman md face where 220 initial chairman md face where playing playing playing Minus One J A IG Plus One Five Plus One G And Oil J Minus One So Let's Chest Like Toubro The Test Cases Give Arrangement Sure Weekly Castor Stitch K Send Mixture Tree Working Correctly So In Forest Swayam Receiver Discussing Som Hui Receiver Discussing Som Hui Receiver Discussing Som Hui Powder To Battle Tips And Other Ise Intimate Powder To Battle Tips And Other Ise Intimate Rickshaw 150 Battleships Solid Submit This Code A Song For Disseminating Accepted One Hundred Percent Of The Runtime Error Zero MS Evidence Year And Fifty Seven Percent Better In Memory Usage Of All Sorts Of That Solve The Problem Of Number Of Solve The Problem Of Number Of Solve The Problem Of Number Of Battleships On Mode Battleships On Mode On The Question Certificate For The Interview On The Question Certificate For The Interview Young Developers So Insisted Of Young Developers So Insisted Of Waiting Number Of Battleships Another Question Zoom Waiting Number Of Battleships Another Question Zoom Encounter Is Like You Know After Accounting Encounter Is Like You Know After Accounting The Maximum Size The Maximum Size Subscribe To Track Of Union President's Setting Battle for Example Subscribe of the Volume and of the Sheep and Wool 220 Front of Questions Respect Like Uniform Finding Number of Things on Board Basically and Finding Minimum Battles Minimum and Size Battleship and Maximum Five Battleships So Life is Solution Helps in Understanding This is the So Accurate Awesome Solution So Accurate Awesome Solution So Accurate Awesome Solution Subscribe My Channel And Like Button And The Subscribe My Channel And Like Button And The Bell Icon So You Will Also Get Notification Bell Icon So You Will Also Get Notification Open Poster In Solution For Lips Open Poster In Solution For Lips Problem Solve Thank You For Watching My Problem Solve Thank You For Watching My Video | 2024-03-22 11:03:05 | 419 | LeetCode 419 Battleships in a Board - Lintcode 986 Battleships in a Board - DFS Java Solution |
|
n_kL8BkURVA | Hello everyone welcome to my channel Quote Sorry with Mike So today we are going to do with Mike So today we are going to do video number 72 of our dynamic programming playlist. video number 72 of our dynamic programming playlist. Lead code number is five. It is a Lead code number is five. It is a medium question but actually it medium question but actually it is quite easy. If you look at it then the constraints have also been kept small. is quite easy. If you look at it then the constraints have also been kept small. Okay and Okay and Okay and name of this question is Longest Palindrome Substring. It is ok and many companies have asked for making it. I have mentioned only these three. You will get the list of the entire company in the description. Ok, so you will get one by You will get the list of the entire company in the description. Ok, so you will get one by one for Longest Palindrome Substring. one for Longest Palindrome Substring. String S is given. Okay, you have to String S is given. Okay, you have to return the longest palindrome substring. return the longest palindrome substring. Now you know what is a palindrome Now you know what is a palindrome and what is a substring. Okay, let's and what is a substring. Okay, let's understand by looking at the example. Like understand by looking at the example. Like look at this example, which is the longest palindrome in it? look at this example, which is the longest palindrome in it? You You should have a palindrome substring, but I am seeing that should have a palindrome substring, but I am seeing that one is A, ABA one is A, ABA and one is B, OK, so and one is B, OK, so any of the two can write the answer, the any of the two can write the answer, the length of both of you is three. length of both of you is three. length of both of you is three. is only of length three, okay, so you have to return the substring. Look here, the biggest palindrome I can see is B B B, right, this one would be ok, let's assume, let's take another example, A C, Yes, this is a palindrome, Yes, this is a palindrome, Yes, this is a palindrome, otherwise the maximum length will be either A because a otherwise the maximum length will be either A because a single character string is a palindrome. single character string is a palindrome. Right, it will be either C or E. Your Right, it will be either C or E. Your answer can be any of these. Ok, you are answer can be any of these. Ok, you are looking at the looking at the length. The maximum length is one. There is a maximum in this. length. The maximum length is one. There is a maximum in this. length. The maximum length is one. There is a maximum in this. was given in it, okay, it is a simple question, we will approach it in a very basic way, we will make it with the latest approach, okay, let's see, look into part A, let's understand it. Okay, look, tell me the thing How do you check whether a How do you check whether a How do you check whether a string is a palindrome or not? Well, there is a string is a palindrome or not? Well, there is a very simple way, people very simple way, people reverse it, like let's assume it is ABA, reverse it, like let's assume it is ABA, reverse it and ABA will come out reverse it and ABA will come out if both are equal. if both are equal. if both are equal. ways, one look here, first, what will we do, look here, first, what will we do, take a pointer here, take a pointer here, are take a pointer here, take a pointer here, are both equal, yes if equal, then the rest. both equal, yes if equal, then the rest. both equal, yes if equal, then the rest. not have to check whether i is sent here or i is sent here, are these two equal? Yes, then i is sent here, h is sent here, both of these are obviously equal, that is, how simple is the method, Can you? I mean, I Can you? I mean, I Can you? I mean, I think this is the simplest way to think this is the simplest way to check palindrome. Well, if you look at it, check palindrome. Well, if you look at it, its code is also very simple. Now I am its code is also very simple. Now I am just telling you how to just telling you how to check palindrome, so if I check palindrome, so if I make it through iterative approach, then write this. make it through iterative approach, then write this. make it through iterative approach, then write this. start from i = 0, I will start from j = n - 1, right, and how long will I simply run till i is less than or equal to j, only then i was i came here j i came here j i came here j came here and so on run till i le = j only came here and so on run till i le = j only then it will run ok if my given then it will run ok if my given string is s of i i to it string is s of i i to it a of j a of j ok then it is good na mean ok then it is good na mean ok then it is good na mean two characters are the same then what will I do, I will move ahead L plus plus sorry I plus plus j minus minus and if it is not so then break it or return false return false is fine meaning if two characters are not Time should return false Time should return false Time should return false because this is not a plum, let's assume that because this is not a plum, let's assume that it is ABC, okay this A is here, J is it is ABC, okay this A is here, J is here, if these two are equal then there is no here, if these two are equal then there is no need to check the rest, need to check the rest, isn't it? isn't it? isn't it? This is B If this and this are not equal then why would you check the rest For now if this whole string is palm a bit okay then we will return false at the same time If the characters are equal then we will If the characters are equal then we will If the characters are equal then we will move Aa forward and J backward. move Aa forward and J backward. Okay, this is an iterative method. There is also a recursive method. Just convert it into recursive. convert it into recursive. What will we do in a simple way? We will write a solve function. There are What will we do in a simple way? We will write a solve function. There are two pointers and AaJ is okay. two pointers and AaJ is okay. two pointers and AaJ is okay. which is this is my greater than equal to h then it is right meaning I have compared all the characters and aa which is h has reached or aa has crossed h means all the characters have been found equal right then I return true. true. true. that's why I reached here further, okay and if it is not so, then what will we check that if S of I is equal to Il to A of J, then what I said is that further. Check it means check i psv and j mive and if it is not so then return false else then return false. This is a very simple ratio code. Pay attention to it. Okay, what did I say that if both the characters are equal i and j then Okay, you check p and j. Okay, check from there and if it is not so, both are unequal then return false. Okay, and how will we call this, i, mine will be starting from zero, j will be Look similarly, it was the same here too, Look similarly, it was the same here too, Look similarly, it was the same here too, so look similarly, I so look similarly, I converted the iteration into recursion, so there are two ways to converted the iteration into recursion, so there are two ways to check whether any check whether any string is a palindrome or not, okay, string is a palindrome or not, okay, this is the normal thing, I have told you. this is the normal thing, I have told you. this is the normal thing, I have told you. taught you, now let's come to this question, okay, you pay attention to this question, I will take the first example, the first example is mine, what is B A B A D B A B A D, okay now let's come to this, pay attention to one thing, he said that Find the biggest substring and show it which is palindrome. If the substring is said to be palindrome then it is okay. First find the substring and then keep checking whether that substring is palindrome or not. Okay, so there are many substrings. One is itself, one is B and which one is What What else is AD itself? B was also here. Here also A is itself. Okay, here this one itself is the only substring of A. Then AD, this one is okay. Then last one is D. So look, there are many substrings, all of them. We will check the substring whether it is a palindrome or not, okay, and now look at what I actually did, pay attention to this, let's assume this index is zero here T 3 4 So first I started from here, So from Aa to Aa, I So from Aa to Aa, I So from Aa to Aa, I took only the string which means B. Then from I till took only the string which means B. Then from I till A, here I mean A, here I mean B. From Aa till I, I took it like B. A B is B. From Aa till I, I took it like B. A B is taken like this. Okay, so see, R has been taken like this. Okay, so see, R has been fixed now, I and J here. fixed now, I and J here. Another pointer starting from I so that I can Another pointer starting from I so that I can create a substring, I'm okay, look from I to J, then there create a substring, I'm okay, look from I to J, then there is B, then J, go ahead, then look from I to J, then is B, then J, go ahead, then look from I to J, then B, then look from I to J, B, A, B, A, and so B, then look from I to J, B, A, B, A, and so on, okay, then J, when on, okay, then J, when on, okay, then J, when then the entire string will be checked. Okay, after that, what will we do? I will come here, assuming that the plum is not found, then it has come, then J will start from here, A to A, meaning this B B B is this one or this one subbing and so on, so I will generate it in all the substrings like this and what I will check for each substring is whether it I will generate it in all the substrings like this and what I will check for each substring is whether it is a palindrome or not. Okay, so let's say is a palindrome or not. Okay, so let's say here I reached and here J here I reached and here J reached. reached. reached. this one, so as soon as I send it to check, I will call solve, what will I send in solve Aa and J, what will it tell me whether this string is a palindrome or not, whether this It is a It is a It is a palindrome, so I need a string. So, palindrome, so I need a string. So, how do I get the substring of this string? how do I get the substring of this string? S Y B S T R S Y B S T R I N G Where is the substring starting from Aa, I N G Where is the substring starting from Aa, what is its length? Look, j - Aa what is its length? Look, j - Aa + 1, this is the length. + 1, this is the length. + 1, this is the length. out the starting index and what is its length. Okay, so as I came to know that this is a palindrome, so I stored its substring, I also know its length, so I Length, now I have Length, now I have Length, now I have got three, okay and which string is that, got three, okay and which string is that, B A B, B A B, okay, either you want to store no string, okay, either you want to store no string, just store the starting point, just store the starting point, starting point means where did it starting point means where did it start, this substring start, this substring started from zero. started from zero. started from zero. now look pay attention, let's do full dry run with this understanding. Okay, look, now let's start the complete dry run. Its okay, so I have not yet got the maximum length, what is the maximum length of the Right now, Right now, Right now, I will either keep it as int min or zero, okay, I will either keep it as int min or zero, okay, and the maximum length of the substring, if its and the maximum length of the substring, if its length is zero, then what is its starting length is zero, then what is its starting point, I will also keep that so that point, I will also keep that so that I can extract the substring. Remember I can extract the substring. Remember how we used to extract the substring. how we used to extract the substring. What is its starting point and what is its length, so What is its starting point and what is its length, so I will just store these two, the I will just store these two, the starting point, I don't know yet, is -1, starting point, I don't know yet, is -1, let's start, what I said, i will start let's start, what I said, i will start from here, we will start from the first row from here, we will start from the first row and j then from here. and j then from here. and j then from here. so I have extracted the substring from i to j. What is it brother, there is b in i to j? So what will I simply say or will I call recursion? I will say that brother, check this string from a to j to see if it No, and I taught you here a little while No, and I taught you here a little while No, and I taught you here a little while ago that you will ago that you will call the solved ones, or you can do it iteratively, call the solved ones, or you can do it iteratively, I will call the recurs, okay, I will call the recurs, okay, notice, till now I have not said even once notice, till now I have not said even once that this is a DP question. that this is a DP question. that this is a DP question. you hear the topic, don't be afraid, that's why I do n't even talk about the topic. Okay, first you look at Intu. Right now we are building Intu only. DP has not been mentioned yet, so do n't be afraid after seeing the topic. From this we got the truth that yes From this we got the truth that yes From this we got the truth that yes brother B, this is obvious, substring, this is a brother B, this is obvious, substring, this is a palindrome, okay, if it is a palindrome, palindrome, okay, if it is a palindrome, then it is okay, what did I do, what is its then it is okay, what did I do, what is its starting point, what is its starting starting point, what is its starting point, zero, what is its length? point, zero, what is its length? Is its one is ok ok Is its one is ok ok now let's move j from a to j now let's move j from a to j I checked again solved call from i to j is I checked again solved call from i to j is this palindrome no it is not this palindrome no it is not a palindrome so nothing will be updated ok a palindrome so nothing will be updated ok j went here j went here j went here sent it in solve that from row to i i.e. i to j i is my sent it in solve that from row to i i.e. i to j i is my row j is my to row j is my to check if it is a palindrome and it will say check if it is a palindrome and it will say yes it is a palindrome then as soon as it came to know that yes it is a palindrome then as soon as it came to know that it is a palindrome it is a palindrome it is a palindrome look at the max length so what is j - i + 1 three is its length and what is its starting point starting point is zero okay now let's move on b b is it a palindrome AD AD AD This is not a palindrome, okay J, now it is over, I will start from another place, just after this, okay J, now it will start from here, I start from another place, just after this, okay J, now it will start from here, I from J, look, A, from J, look, A, is this a palindrome, yes, but look at its length, it is is this a palindrome, yes, but look at its length, it is more than my maximum length. more than my maximum length. more than my maximum length. will not update then go ahead this is a palindrome no this is a palindrome yes look ABA is a palindrome but the length of this is also more than the max length otherwise there is no need to update its ok After J moved ahead A B AD Is Y a palindrome No Now J is over Okay after this I moved ahead J Started from here B is a palindrome but its length is not more than the max length B AD is not a B AD is not a B AD is not a palindrome Okay then here I go ahead J Will palindrome Okay then here I go ahead J Will start from here What A P start from here What A P Yes but its length which is Yes but its length which is not more than the maximum length AD is a palindrome No not more than the maximum length AD is a palindrome No okay After that I is here J is here okay After that I is here J is here D is a palindrome yes but its length which is not D is a palindrome yes but its length which is not more than three is not more than three is not more than the max length so will not update Gone is the story of A and J, Gone is the story of A and J, what will we do? Find the substring, what is the starting point, what is zero and the maximum length? Look, its three is three. Take out the string of length from zero to three. B. A is from zero to three in Big Palindrome Big Palindrome Big Palindrome is substring. Got it. Okay, now is substring. Got it. Okay, now focus on one very important thing, then we will be focus on one very important thing, then we will be ready for the code. Now look, ready for the code. Now look, focus on one very important thing here. Focus on this example. It's all focus on one very important thing here. Focus on this example. It's all right, so look at this example. right, so look at this example. If the same If the same If the same mentioned above, then we will do the same, it was simple, I started here, J started here, then grew, checked the name, updated it, then J here, checked the palindrome, Okay, Okay, Okay, so let's go by the value, let's take one such state, let's go by the so let's go by the value, let's take one such state, let's go by the value J value J was here, so you called solve of was here, so you called solve of 05. Okay, so of 05, when I checked whether it 05. Okay, so of 05, when I checked whether it is a palindrome or not, remember is a palindrome or not, remember how to check. how to check. how to check. equal, is zero character five character equal, 0 f, which character is A, yes, it is equal, both are equal, okay, so I used to say, okay, check further, And check the index number four, And check the index number four, And check the index number four, okay, check this, okay, check this, after that he said, are these two equal, yes, after that he said, are these two equal, yes, equal, then I said okay, and check the next one, equal, then I said okay, and check the next one, check th, these two check th, these two are also equal, okay this. are also equal, okay this. are also equal, okay this. it becomes like this, then it will return true, we are not ours, there is a condition of base case i >= j, then it means everything is fine, everything is fine, so even If I look, 05 14 23, then If I look, 05 14 23, then If I look, 05 14 23, then I know that yes, this is my palindrome, I know that yes, this is my palindrome, so it is okay, all this must have been checked, now let's so it is okay, all this must have been checked, now let's go by the value, go ahead, your loop will be go by the value, go ahead, your loop will be bigger, come forward, it must have come here, j bigger, come forward, it must have come here, j here. here. here. called solve, for this you must have called for 0, okay, for this, how would I have checked the pum, zero character, sorry, no, one character, f is equal, What I What I What I did is go ahead th is equal yes is equal did is go ahead th is equal yes is equal ok now one thing you notice here is ok now one thing you notice here is that this n f I checked here also for that this n f I checked here also for g f and y f I checked for this g f and y f I checked for this also solved. also solved. also solved. seeing that all the problems are repeating, so from here I got the idea that why not when I am calling recurse or in solve, then I should memoize the If I say somewhere If I say somewhere If I say somewhere that the substring from 1 to 4 is a that the substring from 1 to 4 is a palindrome, then I have written true and palindrome, then I have written true and stored it here. The substring from 0 to 3 stored it here. The substring from 0 to 3 is a substring and that is a substring and that too is a palindrome. Here, store it for all. too is a palindrome. Here, store it for all. too is a palindrome. Here, store it for all. taken so that when I would come here, there would be no need to check further, I would say, ok, this is true for 4, this is true, then I would directly return it from here to 2, saying that brother, this Okay, it is clear till now, that is Okay, it is clear till now, that is Okay, it is clear till now, that is why I said that when I solve the problem of why I said that when I solve the problem of recurs here, recurs here, I I will apply memoization here, okay, then I understood will apply memoization here, okay, then I understood that okay, this is actually it that okay, this is actually it can be made with recurs plus memoization, otherwise I am can be made with recurs plus memoization, otherwise I am normal. normal. normal. I will not use this method. To solve this, you can also do it in an iterative way. Unfortunately, there It It It should have been that way because it seemed to me to be the most should have been that way because it seemed to me to be the most basic and new approach. Okay, so if we quickly basic and new approach. Okay, so if we quickly look at the story that we have understood, look at the story that we have understood, then how will it be? I had said that I will then how will it be? I had said that I will start from zero and will go to I plus start from zero and will go to I plus plus, okay? plus, okay? plus, okay? lesson will be A. No, if it was a palindrome, No, if it was a palindrome, that is, if true came from there, that is, if true came from there, then what I used to do was to then what I used to do was to check that whatever is the check that whatever is the length of the maximum length that I have already stored length of the maximum length that I have already stored and the current length that I have got, that is. and the current length that I have got, that is. j - aa pv If it is greater than the j - aa pv If it is greater than the maximum length which is already mine then I will maximum length which is already mine then I will have to update then I will update the maximum length have to update then I will update the maximum length j - aa pv and yes the j - aa pv and yes the starting point will also be stored I starting point will also be stored I remember the starting point what is aa remember the starting point what is aa remember the starting point what is aa what because right now we are seeing everything from Aa itself, starting point is my Aa, so like this for loop, the entire for loop will end, what I have to do in the last is to remove all from the starting point and whatever is the maximum length of That's fine, so let's That's fine, so let's That's fine, so let's code quickly and the code quickly and the function of solving the checking palindrome, function of solving the checking palindrome, I have already told you about it above and what will we do in it, we will I have already told you about it above and what will we do in it, we will put memoization in it, put memoization in it, so let's code quickly, so let's code quickly, just like just like just like said, brother Rick, is a string a palindrome, what kind of string is it or not, how did they check, first of all they wrote the same function, they used to pass a string to it, an i pointer and a j pointer went into it. It is ok and if i which is >= j is reached then it means all characters were equal return true then ok and what will you check after this if s off i == s off j then check further also s i + 1 and j -1 is ok and s i + 1 and j -1 is ok and s i + 1 and j -1 is ok and if it is not so then nothing will be returned false if it is not so then nothing will be returned false ok that means that character was not equal so there should be ok that means that character was not equal so there should be no return from here but it no return from here but it is being returned here so I have is being returned here so I have returned false ok now returned false ok now returned false ok now function with our longest length. I told you, first of all, let's find out the length. After that, I said that we will keep a variable named max length. Let's keep it as int. Okay, and starting point A is okay. Equal to what to keep now, let's keep only zero for now, either -1, you can keep anything, okay so it was a very simple for look i = 0 aa < n i+ It used to start with It used to start with It used to start with j < n j+ प ok and after this it is j < n j+ प ok and after this it is very simple that if the solve of i s aa j is very simple that if the solve of i s aa j is this string s which is the sub string from this string s which is the sub string from aa to j is it a palindrome, if aa is true then it aa to j is it a palindrome, if aa is true then it is a palindrome. is a palindrome. is a palindrome. what will I do, if the new length I have got is greater than the max length then I will update the max length as it is okay and what is the starting point, this time it is SII, I am looking at the starting point. Point is, we are checking from here only. Okay and lastly what will we do return adot substring what is the starting point a and what is the length th this will get my long palindrome substring okay now let's do one thing without memoization submit it and Here sub string is C+ Here sub string is C+ Here sub string is C+ P, I had written sub string by mistake. Let's P, I had written sub string by mistake. Let's run it and see. Let's see ruble run it and see. Let's see ruble to pass example test to pass example test cases. It is passed. After submitting, let's see whether it is cases. It is passed. After submitting, let's see whether it is submitted without memo. Ok, See why it got submitted because See why it got submitted because See why it got submitted because its constraint is very small right its constraint is very small right see so const is very small so see so const is very small so without mem is also accepted but I without mem is also accepted but I also make it with memoization also make it with memoization in 100 is ok and here memset I will check I will check I will check that that if it of i is not equal to my then if it of i is not equal to my then return t of i is ok and since ama j return t of i is ok and since ama j is an integer then what I do here is is an integer then what I do here is send one more or send one more or send true, same thing. send true, same thing. send true, same thing. send zero instead of false or send false, it is the same thing. Okay, so here I store t off aj is solved and here t off aj = 0. Okay, so let's see an example of how to test. passed. After submitting it, we will see that indeed yes, this has also passed and you pay attention to what I have just done. See how many minutes are taking without Okay so Okay so Okay so I hope it was helpful any doubt I hope it was helpful any doubt raise it in the comment section I will try raise it in the comment section I will try to help you out and pay to help you out and pay attention to its time so off n score so here it is done two attention to its time so off n score so here it is done two for loops and here look at all the strings for loops and here look at all the strings We are visiting all the characters once, so here it seems to be off, here too it is fine, so here it seems to be off, here too it is fine, so off n is cube, actually this is the solution, off n is cube, actually this is the solution, so see you guy in the next video, thank so see you guy in the next video, thank you. | 2024-03-18 11:17:06 | 5 | Longest Palindromic Substring | Recursion | Memoization | Microsoft | Leetcode - 5 |
|
gicMdhjVbw4 | hello friends uh welcome to my channel let's have a look at problem 143 let's have a look at problem 143 reorder list reorder list so here the list is actually a singly so here the list is actually a singly linked list linked list so in this video we're going to share a so in this video we're going to share a solution based on linear traversal and solution based on linear traversal and reversal reversal so first i'll read through the problem so first i'll read through the problem statement to digest the requirement statement to digest the requirement and then we go over the analysis and and then we go over the analysis and finally we share the code finally we share the code first let's look at the statement first let's look at the statement so we are given the head of a singly so we are given the head of a singly linked list so the list can be linked list so the list can be represented as represented as error notes connect to l1 then connect error notes connect to l1 then connect to arrow n minus 1 then to lm to arrow n minus 1 then to lm so reorder the list to be on the so reorder the list to be on the following form so we connect the following form so we connect the head with two head with two then head then head with 2 and so on so we get l not connect with 2 and so on so we get l not connect with l m with l m then l n connects with l 1 then l n connects with l 1 then connect with l n minus 1. then connect with l n minus 1. so so that's the requirement that's the requirement so we may not modify the values in the so we may not modify the values in the lists nodes so only nodes themselves may lists nodes so only nodes themselves may be changed be changed so here are two examples so in the first so here are two examples so in the first examples examples in the first example the linked list has in the first example the linked list has lens 4 so the return is then connect lens 4 so the return is then connect with 4 then connect with 2 and then with 4 then connect with 2 and then connect with connect with 3. so this is the result 3. so this is the result and in the second example the linkedin and in the second example the linkedin list has length five which is an odd list has length five which is an odd number number so so we first connect one with five then five we first connect one with five then five connect with two two is four and four is connect with two two is four and four is three three is now so this is the return three three is now so this is the return so with that said let's also look at the so with that said let's also look at the constraints or additional assumptions constraints or additional assumptions for this problem for this problem first the number of nodes in the list is first the number of nodes in the list is in the range in the range between 1 and 5 times times per four between 1 and 5 times times per four so this constraint actually defines the so this constraint actually defines the problem size problem size and the second constraint is on the node and the second constraint is on the node value range which is in between van and value range which is in between van and maslodend maslodend so with that said so we are ready to so with that said so we are ready to look at the analysis look at the analysis so this problem actually is very so this problem actually is very interesting so the solution is based on interesting so the solution is based on linear traversal with reversal and the linear traversal with reversal and the merge merge so here in this solution we're going to so here in this solution we're going to practice several things practice several things first so we're going to practice slow first so we're going to practice slow fast pointers technique fast pointers technique and then we and then we practice how to reverse a linked list practice how to reverse a linked list so also we practice how to merge linked so also we practice how to merge linked lists so here we merge two linked lists lists so here we merge two linked lists actually there is a problem in this code actually there is a problem in this code which requires to merge which requires to merge a number of a number of linked lists linked lists so it might be useful so it might be useful to check the corresponding list in our to check the corresponding list in our channel if you have time channel if you have time so for this problem the procedure is the so for this problem the procedure is the following so first following so first we'll find the middle node using slow we'll find the middle node using slow fast pointers method so if we are using fast pointers method so if we are using zero indexing then the index of the node zero indexing then the index of the node the so-called middle is the so-called middle is n over two so here over means integer n over two so here over means integer division and the n is the length of the division and the n is the length of the linked list linked list so for example if the links list has so for example if the links list has length um length um which is uh which is uh even or even number so for example 0 1 2 even or even number so for example 0 1 2 3 so the mid 3 so the mid is in this node true is in this node true and if the linked list has length um and if the linked list has length um which is an odd number so for example which is an odd number so for example five so zero connect with one with two five so zero connect with one with two with three is four then the middle is with three is four then the middle is again this node with value 2. again this node with value 2. so this is the first step so this is the first step the second step is that after we the second step is that after we locate the middle then we're going to locate the middle then we're going to reverse the linked list reverse the linked list represented by the middle node so if we represented by the middle node so if we use example one so we can fix the idea use example one so we can fix the idea as below so this is the original linked as below so this is the original linked list so the middle is three so then we list so the middle is three so then we break the link between two and three break the link between two and three and then we reverse the second half so and then we reverse the second half so we will get two links list one is we will get two links list one is represented by the original height so represented by the original height so that that is when connected with two that that is when connected with two then now then now the reverse one is nothing but four the reverse one is nothing but four connect with three then now connect with three then now so this is the second step the first so this is the second step the first step actually is routine so we're going step actually is routine so we're going to merge the two linked lists obtained to merge the two linked lists obtained with alternate nodes from the two linked with alternate nodes from the two linked lists so we from we connect event with lists so we from we connect event with four and then we update the height four and then we update the height correspondingly so then we connect four correspondingly so then we connect four is two and two is three so we are done is two and two is three so we are done so this is the third step so this is the third step so here actually there's a remark so here actually there's a remark so it's possible that the second half of so it's possible that the second half of the linked list is the linked list is longer than the first half so when the longer than the first half so when the original linked list is of odd length original linked list is of odd length for example if we use example 2 so the for example if we use example 2 so the first half will be 1 2 and the second first half will be 1 2 and the second half after reverse will be five half after reverse will be five four and three so which has length four and three so which has length three so we just need to connect the three so we just need to connect the last node after we exhaust the first last node after we exhaust the first linked list and all other nodes except linked list and all other nodes except the last one in the second linked list the last one in the second linked list so this is actually so this is actually a thing that is very easy to do a thing that is very easy to do so with the above so with the above procedure specified so now we are ready procedure specified so now we are ready to write the code to write the code so so as required by the problem we are good as required by the problem we are good we're going to do the things in place we're going to do the things in place so so we're going to write with some detail we're going to write with some detail and explain the code 11.99 so in the and explain the code 11.99 so in the process we're going to process we're going to write some annotations write some annotations so first so we're going to so first so we're going to send send the middle the so-called middle node the middle the so-called middle node using using a slow a slow first pointers first pointers so this is actually a very routine so this is actually a very routine technique so if you practice quite a lot technique so if you practice quite a lot so you can write it with uh so you can write it with uh with ease with ease so here in order to do this i'm going to so here in order to do this i'm going to initialize a variable called previous initialize a variable called previous so because i need to break the link let so because i need to break the link let me do the reverse in the second step so me do the reverse in the second step so previous originally is none previous originally is none then then we're going to initialize a slow and we're going to initialize a slow and fast pointer initially both pointing to fast pointer initially both pointing to the head the head so notice that the head is not null at so notice that the head is not null at the very beginning due to the problem the very beginning due to the problem requirement requirement assumption assumption the number of nodes is at least what the number of nodes is at least what so the links list is not on now list so the links list is not on now list and then we can do the standard slow and then we can do the standard slow faster technique well fast faster technique well fast and and fast next fast next so so you notice you notice or understand this condition or understand this condition after the next two lines so we're going after the next two lines so we're going to to update the pre to be slow and slow move update the pre to be slow and slow move to to less step further so slow next less step further so slow next and then we opted first to be first and then we opted first to be first next next next so that's why we have this next so that's why we have this condition first and the first next condition first and the first next because of this condition first next is because of this condition first next is not now so we can consider not now so we can consider fast next and its next rate because this fast next and its next rate because this part part here is not now otherwise we cannot do here is not now otherwise we cannot do this this so after this after this while loop so so after this after this while loop so actually the slope corresponds to the actually the slope corresponds to the middle node and middle node and if we use this one as example this will if we use this one as example this will be the slope and this will be the be the slope and this will be the previous previous so before we do anything let's first so before we do anything let's first treat a special case if treat a special case if pre is null pre is null so in this case it means that the so in this case it means that the linked list is too short so just to have linked list is too short so just to have one node so we just need to return the one node so we just need to return the head in this case so this is actually head in this case so this is actually very easy so now very easy so now up to now so we have this up to now so we have this uh what um uh what um what we want to do next is to break the what we want to do next is to break the link first so link first so we this is the pre you can imagine and we this is the pre you can imagine and this is the middle so we want to break this is the middle so we want to break this link so previous next we'll set it this link so previous next we'll set it to now to now so then so then we can actually get the corresponding we can actually get the corresponding information for information for the first half of the node let's print the first half of the node let's print out that just for out that just for a examination so if we print height so a examination so if we print height so this head will represent by one two so this head will represent by one two so let's do a check let's do a check yeah this is one and point to two yeah this is one and point to two that's everything the right so that's everything the right so with that said let's do another thing to with that said let's do another thing to the second step the second step so now the second step is to so now the second step is to reverse reverse the linked list the linked list are headed by are headed by and by the middle and by the middle by the middle by the middle by the middle the slope right the slope right so so we're going to do reverse so for this we're going to do reverse so for this actually uh let's first introduce a actually uh let's first introduce a dummy variable let's call it uh now then dummy variable let's call it uh now then we're going to we're going to do the reverse so this is actually very do the reverse so this is actually very routine well slow so slow is the routine well slow so slow is the linked list height right so well slow so linked list height right so well slow so what we are going to do is that first what we are going to do is that first let's save slow next let's save slow next for later use and then they connect slow for later use and then they connect slow with with dummy dummy so this line actually did two things so this line actually did two things first it breaks the link of slow with first it breaks the link of slow with slow next and then we pawn slow next to slow next and then we pawn slow next to be done dummy so be done dummy so after that we can up this dummy to be after that we can up this dummy to be slow and slow to be temp so the temp is slow and slow to be temp so the temp is the original slow next right the original slow next right so this is the standard way of reverse a so this is the standard way of reverse a linked list so after that because if we linked list so after that because if we exit this loop slow will be now however exit this loop slow will be now however the dummy is not now right so the dummy the dummy is not now right so the dummy will be the head of the reversed linked will be the head of the reversed linked list so let's print this out just for a list so let's print this out just for a check check dummy dummy for example when the dummy will for example when the dummy will represent four pointing to three let's represent four pointing to three let's do this check do this check so you can see this there's a four point so you can see this there's a four point two three everything is right two three everything is right so now with this done so we can do the so now with this done so we can do the next step next step so the next step is merge the two a linked list by hiding by the original head as a dummy so for this merge actually it's very very simple we just need to use alternating nodes from the two nodes and for this purpose i'm going to use a auxiliary node so and also make it a start so to be this node so i'm going to use the default initial initialization data then we're going to check the head so height is the first half and stop me either have a lens that is equal to the length by the height or the longer so anyway so we just need to use a head as the check condition so well ahead so what we're going to do first i'm going to save the temp with the head next and the dummy next so it's a head next and dummy next so this is the still four liter used and then what we are going to do is we connect next to be head and then we connect the head next to the dummy so after we do this what we are going to do is that so um we set the ox to be the dummy and then we are going to update the head and dummy head and dummy to be temp one and ten two step temp two so from this line we can interpret the purpose of the first line after the well um vowel condition so that's about it so we have um um so here what we are doing is that save template temp 2 for use later and set aux next we had and connect next with dummy and then we upped its aux to be the current dummy and then we update head and dummy by temp 1 time 2 saved earlier so that's the case so after we access this while loop so the first linked list is exhausted but the second might be not so if the second is exhausted so we're going to have dummy is empty so if not so if dummy so the dummy will be the last node in the second list so we're going to connect aux to dummy so this way actually we merged the two linked list so we're going to use this the aux as a moving variable so when we do the return we're going to return start next right so the return is simple so we're going to return start next so this up to now we finished the overall logic for this problem so now before we make some comments yeah it passes the first example now yeah it passes the first example now let's look at the generic case yeah it passes all the cases it should be reasonably fast because it's a linear method so anyway so before we end this video let's overview the structure of this solution so we split the logic into three parts so the first part actually is a standard practice of the slow fast pointers technique to locate the middle node and after the first step we're going to reverse the second part of the linked list to prepare the merge the third step is to do the merge of the two links list by alternating nodes from the two linked lists now afterwards we return the desired result so in the process actually we used dominoed twice at least forgive for example when we do the reverse and then we do the merge so this technique or trick is very useful sometimes when we do linked list problem so with that said i guess that's about | 2024-03-21 12:42:04 | 143 | Leetcode 143. Reorder List - basic practice: linear traversal, reversal, merging of linked lists |
|
EdR3V5DBgyo | hello guys welcome to algorithms made easy so today we are going to see the easy so today we are going to see the question trapping rainwater question trapping rainwater let's quickly go through the problem let's quickly go through the problem statement given n non-negative integers statement given n non-negative integers representing representing an elevation map where the width of each an elevation map where the width of each bar is 1 bar is 1 compute how much water it can trap after compute how much water it can trap after raining raining so let's just understand this question so let's just understand this question if we draw the bars if we draw the bars according to the given array this is according to the given array this is what we get what we get and if we are said to fill the water in and if we are said to fill the water in this this shape the water will accumulate in the shape the water will accumulate in the valleys valleys so this is where the water gets so this is where the water gets accumulated so how do we find accumulated so how do we find how much water is there on each how much water is there on each bar at each index suppose we take this bar at each index suppose we take this index five index five so the water accumulated at index five so the water accumulated at index five would be the valley formed by the would be the valley formed by the maximum and left maximum and left and the maximum and right so what is the and the maximum and right so what is the actual level because here we can see actual level because here we can see that max's are different that max's are different so it would be the minimum of these two so it would be the minimum of these two max max and since here the height of this bar is and since here the height of this bar is 0 0 it would not affect our answer if we do it would not affect our answer if we do not consider not consider it but if we see the case of index it but if we see the case of index nine the maximum water just the water nine the maximum water just the water that can be accumulated that can be accumulated would need us to subtract the height of would need us to subtract the height of this bar this bar so this is the actual gist of the so this is the actual gist of the question that we need to find the question that we need to find the maximum and left maximum and left and the maximum and right and then take and the maximum and right and then take the minimum of both the minimum of both and then according to the height of the and then according to the height of the building at the index building at the index we can find the amount of water that can we can find the amount of water that can accumulate accumulate on that building or the bar so that's on that building or the bar so that's all that is written all that is written in this algorithm so calculate the max in this algorithm so calculate the max on left calculate the max one right and on left calculate the max one right and then the water on the building would be then the water on the building would be minimum of minimum of max from left and right minus the height max from left and right minus the height of building of building so the question is how do we calculate so the question is how do we calculate this this maximum simply we can say that there are maximum simply we can say that there are two approaches two approaches for now that is a brute force and using for now that is a brute force and using an arrays an arrays the brute force approach for each the brute force approach for each bar you would need to find the maximum bar you would need to find the maximum on the left by looping till the start on the left by looping till the start maximum on the right by looping till the maximum on the right by looping till the end end and then apply the formula that we had and then apply the formula that we had got got this approach would end up having a this approach would end up having a complexity the time complexity of complexity the time complexity of o of n square while the space complexity o of n square while the space complexity here would be o of 1 as we are not here would be o of 1 as we are not taking any additional space taking any additional space how do we reduce the time complexity how do we reduce the time complexity that could be done that could be done by using an extra space so we know that by using an extra space so we know that we we are doing an additional step of going to are doing an additional step of going to the left and right the left and right all the time so we can save the maximum all the time so we can save the maximum in the left and maximum in the right in in the left and maximum in the right in separate arrays and then calculate the separate arrays and then calculate the water on this building water on this building so we will have these loops to calculate so we will have these loops to calculate the max the max left max right max and then once we have left max right max and then once we have these two we'll have to loop these two we'll have to loop to find the water but we do not need to find the water but we do not need these many loops we can just combine these many loops we can just combine these into one loop these into one loop but just for the understanding purpose i but just for the understanding purpose i have shown you have shown you two different loops okay so let's just two different loops okay so let's just start coding this one so first we'll start coding this one so first we'll take an take an integer n that will store the length of integer n that will store the length of the height the height then we'll take two arrays now we need to return water so we take now we need to return water so we take water and at the end we'll return water and at the end we'll return this water in between this water in between we'll have loops so for we'll do a combined looping thing instead of doing the two separate loops so here at the same time we'll keep on adding right max and left max if i 0 then left max of 0 or you can say i is equal to height of 0 or height of i right max of n minus 1 or the last index right max of n minus 1 or the last index we are first filling up the last index we are first filling up the last index in the first index in the first index height of n minus 1 height of n minus 1 now comes the else part so now comes the else part so left max of i would become left max of i would become something at the same time we'll find something at the same time we'll find right max of right max of n minus i minus 1 n minus 1 minus i n minus i minus 1 n minus 1 minus i okay so which would be equal to okay so which would be equal to something something what would the left max be it would be what would the left max be it would be simply simply max of height of i max of height of i and the previous lift max and the previous lift max while the right max would be while the right max would be the max of height of the max of height of n minus i minus 1 n minus i minus 1 and right max of n minus i now that we have the values we can again loop and right max and left max minus right max and left max minus height of i so this is all about height of i so this is all about the array method okay the array method okay let's initialize this sinustate and if you submit this code that's accepted so this was one of the method now let's go on and see the next method which is using stacks here we'll take the same example and we'll take a stack and add the index of these bars into the stack till when we'll keep pushing the index till we get an index for which the height is higher than the height of the top element so here we can see that the height for index 2 which is 0 is lesser than the height at index three so we are getting a increasing height and we stop over there okay so after this what we do is we need to start our calculations on what do we calculate we'll calculate on 2 so we'll calculate the water between its left and right so water between its left and right here what becomes the left the left becomes the one that is there in the top of the stack and the right becomes the one that so what's the formula the formula here so what's the formula the formula here is different it is is different it is distance multiplied with the level that distance multiplied with the level that should be there should be there we'll understand the importance of we'll understand the importance of distance in a while for now distance in a while for now let's just see how this is getting let's just see how this is getting calculated here we are taking the calculated here we are taking the minimum of minimum of top of the stack which is the left top of the stack which is the left element and the minimum of height of i element and the minimum of height of i which is the right element which is the right element so this would be the water level and the so this would be the water level and the height of the pop height of the pop element which is this element itself element which is this element itself so this is the same formula that we used so this is the same formula that we used earlier also earlier also right now that you have understood the right now that you have understood the formula formula let's see how we calculate the distance let's see how we calculate the distance the distance the distance is the one between the left and the is the one between the left and the right right which would be 3 minus 1 and which would be 3 minus 1 and we'll subtract one more to get just the we'll subtract one more to get just the one in the between one in the between so if we use this formula we get the so if we use this formula we get the water here as water here as one unit that we can see now let's take one unit that we can see now let's take another example another example if you are at index six what you'll do if you are at index six what you'll do is you'll calculate for index is you'll calculate for index five because you'll get that the height five because you'll get that the height of index six is greater than height of of index six is greater than height of index five index five so here according to the formula again so here according to the formula again we get we get the water between these two points as the water between these two points as one unit one unit now is the fascinating part as we move now is the fascinating part as we move on to this index seven on to this index seven here we find out that the distance plays here we find out that the distance plays an important role an important role here the distance becomes 7 minus 3 here the distance becomes 7 minus 3 minus 1 minus 1 which gives us 3 and the water level which gives us 3 and the water level that should be there is that should be there is minimum of height of left and right minimum of height of left and right which gives us 2 and from that which gives us 2 and from that we subtract the height of pop element we subtract the height of pop element which is which is 1. so this tells us that this part is 1. so this tells us that this part is filled filled and we need to fill above it which gives and we need to fill above it which gives us us 3 into 1 which is 3. now that we have 3 into 1 which is 3. now that we have understood the concept understood the concept let's start coding for this so since we let's start coding for this so since we are using a stack we are using a stack we first need to initialize the stack next will have two variables first is the current variable both will be initialized to zero both will be initialized to zero and then we will start looping so and then we will start looping so while current is less than height length which is we'll go from 0 to n and in that we'll be checking the condition for stack so stack is not empty and the current height is greater than the so we'll perform some operations or so we'll perform some operations or otherwise we'll just push otherwise we'll just push we'll push current and we'll push current and do a plus so what operations do we do a plus so what operations do we perform here perform here first pop which we are going to take in a variable and then we'll check if stack is becoming empty or not if it becomes empty then there is no need of performing the further operations we can just otherwise what we do is find the otherwise what we do is find the distance distance which would be current minus which would be current minus stack dot peak minus 1 and we will find stack dot peak minus 1 and we will find the water that is going to be filled so the water that is going to be filled so taking a variable fill which would be taking a variable fill which would be distance multiplied by minimum of two heights we were taking that is current and stack dot peak subtract height of subtract height of top now that we have got fill we need to top now that we have got fill we need to update update water that's it return water so so now that we have got a expected output we can just submit this code and see whether it gets submitted or not and it gets submitted this was the stack method let's try to improve it further let's move to the more optimized version of the solution which is using the two pointers approach so what we do is we'll use two pointers i and j which are positioned at 0 and n minus 1 and we'll have some variables which would store the max left and right for our bars and lastly the result variable water in this approach what we would be doing new is that we will only consider the positions we are currently on and we have seen not the ones we have not encountered so here we'll consider 0 and 11 and we can see that there is a slope on the left side which means that the water will accumulate on the left so we would be processing the ith pointer now to calculate the ith pointer the water at it index we would be taking the maximum left minus the height of i and we will add it in the water that was already accumulated previously so for that now we see that we would need max left so we will need to update max left which is going to be the maximum of the previous max left and the current height in this case it would be zero and the height of i is also zero water is also zero so everything becomes zero now since we have crosses the ith position we will move the ayath pointer one step ahead and this becomes our new ing since both are equal we will again calculate for i and here we can see that the maximum left would now get updated because we have not seen a height so tall so this becomes one and the water becomes still zero as max left is one and the water is still zero now we will again move the ith pointer ahead again there is a slope and so we calculate ith pointer here we can see that there is a building or there is a bar which would prevent the water from flowing so it would get accumulated here and as we can see that the water here becomes one the max left could still be one because there is no height that we have encountered which is greater than one so we will just update the water so we move towards right so i moves one step ahead and here we can see that the slope is towards right so we process this right the max right over here gets updated to one and the water still remains 1 because there will not be any water on this building or this bar since we have updated this we will decrement the jth pointer and move inside so here we can see that both the bars are equal and so we process left and now increase the height of the left and so update max left which becomes two the water still remains one as there is no water that is going to be filled on top of this bar we move i and again keep doing the same here the slope is towards left so we fill the water and we will keep on doing the same thing till i and j are not crossing over at the end we will get the result in a variable water so now that we have understood this approach let's go and write some code for that okay so firstly we'll take four variables then we loop while then we loop while i is less than j and now we check if i is less than j and now we check if height of i height of i is less than or equal to height of j so this loop is dedicated for updating max left and this is for max wright and processing the right mat dot max of height of i water becomes water plus max left minus height of i and i becomes i plus plus similarly max right max of max right and height of j max of max right and height of j water becomes max right minus height of j and j becomes j minus minus at the end return water and there it got submitted here's the and there it got submitted here's the time complexity for all the methods that time complexity for all the methods that we have seen we have seen for the brute force the time complexity for the brute force the time complexity is of n square is of n square and the space complexity is of one while and the space complexity is of one while when we were using arrays the time when we were using arrays the time complexity was o of 2n complexity was o of 2n because we were having two for loops because we were having two for loops which which gives us o of n and the space complexity gives us o of n and the space complexity was also of 2n was also of 2n which is equivalent to often while using which is equivalent to often while using the stacks the time complexity is o of n the stacks the time complexity is o of n and the space complexity is also o of n and the space complexity is also o of n while in the two pointers approach while in the two pointers approach time complexity is o of n and the space time complexity is o of n and the space complexity is o of one complexity is o of one so that's it for today guys hope you so that's it for today guys hope you enjoyed the video hope you learned enjoyed the video hope you learned something new something new thanks for watching see you in the next thanks for watching see you in the next one | 2024-03-20 09:19:54 | 42 | Trapping Rain Water (4 Approaches) | Live Coding with Explanation | Leetcode - 42 |
|
Nm2K1oMNg4w | uh so we have an array for which the ith so we have an array for which the ith element is the price of a given stock element is the price of a given stock on day i so we have to design an on day i so we have to design an algorithm algorithm to find a maximum profit you may to find a maximum profit you may complete as many transactions complete as many transactions as you like and that is buy one as you like and that is buy one and sell one share of the stock multiple and sell one share of the stock multiple times with the following restrictions times with the following restrictions you may not engage in multiple you may not engage in multiple transactions at the same time transactions at the same time that is you must sell stock before that is you must sell stock before you buy again after you sell your stock you buy again after you sell your stock you cannot buy stock on the next day you cannot buy stock on the next day that is cooldown of one thing yes so this is uh so we it is a variation of the uh sales talk problem so the symbol will one will be you can only buy ones and sell ones and you have to find the uh the maximum profit that you can make and the second variation is like uh you can buy and sell multiple time but without the last uh like uh this restriction that you have to uh cool down by one and uh and now we have this third variation that you you cannot do multiple transaction and after you buy sell your stock you cannot buy the stock the next day so we have this thing and how would you solve this sort of so is the cooldown one day fixed yes so uh to make the maximum profit uh we first need to buy one item at its minimum cost and we need to sell it at its maximum cost right yeah i can wait as long as i want before i can wait as long as i want before selling a stop selling a stop yeah the cooldown has to be like one or yeah the cooldown has to be like one or more than one like you can also wait more than one like you can also wait like three four days to buy a new stock like three four days to buy a new stock but you have to wait at least one day one like i would solve it nicely using um like a backtracking like uh what i mean is like i suppose this this is the thing and so like i can try with buying in day one okay or not buying in day one and if i buy then i have to sell the next next like so next time so like then i have to sell or not sell but i have to sell in some day and then i can do it again and get see the maximum profit that i can make like i just try all the possible combination like i can like buy in day one and then i pass this function again like two three four two three zero two but i have to sell it the first like the next time or i i choose not to buy in day one and i just do two three zero two and i have to buy the next time i have to sell right so i can like i have to sell right so i can like choose to sell choose to sell in day two so if i sell it in day two so if i sell it then i will get three zero then i will get three zero two but i because i sold it i cannot use two but i because i sold it i cannot use the three again the three again so i have to buy and i have to buy the so i have to buy and i have to buy the new next time new next time and and because i have bought the and and because i have bought the i didn't buy the next uh in the day one i didn't buy the next uh in the day one i can buy the next day like i can buy i can buy the next day like i can buy uh at i can buy two and i can get uh at i can buy two and i can get three zero two as sell and and i can choose not to sell it in the in the second day or i can choose to sell it so if i sell it then i will get zero to as buy but because i can i i cannot buy in the next day i have to pass two to buy or i can choose like not to sell in that case i can do 0 2 and sell again you know so this is my this will be my back tracking and i will consider all possible uh situation and get the maximum okay but here you see there is one like we are solving the same sub problem again and again like 0 to b can be also present in other case you know so we can think of dp yes dp like we can have a dp like array of like uh i to j and we can have like we have to buy do it by yourself you know and if we can store by yourself you know and if we can store this this and use it again and again like uh if we use two like uh if we use two uh arrays like uh one for selling and uh arrays like uh one for selling and one for buying yeah that can also work one for buying yeah that can also work yes that and i think that i think that yes that and i think that i think that will be easier to implement will be easier to implement yes so let's go with that uh yes so let's go with that uh do you want to go implement it do you want to go implement it you can try okay you can try okay let's yeah so yeah you can let's yeah so yeah you can implement it using that and let me stop implement it using that and let me stop the screen share and you can start the screen share and you can start this is our array one two three zero and this is our array one two three zero and two two and uh for the and uh for the i i suppose i had the index of i i suppose i had the index of i uh so we have to give one uh one day of cool down after the selling right yeah yeah i cannot think after relation actually i cannot think after relation actually okay okay i can tell you the relation uh i can tell you the relation uh so let me write it in the google doc so let me write it in the google doc so we have like dp ah so we have like dp ah so we have two dp dp of cell cell and cell and and dpf by ah so dpf by i'm just thinking so dp i'm just thinking so dp so suppose we have arrow right so we can so suppose we have arrow right so we can do do like uh suppose we have the first day we like uh suppose we have the first day we buy in the first day buy in the first day so we cannot uh sell so we cannot uh sell uh in the uh uh in the uh yeah we can sell in the second day we yeah we can sell in the second day we cannot buy it right so cannot buy it right so if like if we buy if like if we buy in the i in the i then our answer will be then our answer will be like uh dp like uh dp of cell and uh and uh if you buy in day one the answer will be if you buy in day one the answer will be dp of cell dp of cell i plus one uh and if you sell in a i then we have to do dp of by i plus 2 so dp of sale and if you buy will be the so dp of sale and if you buy will be the max the best max the best uh uh like the best possible uh uh like the best possible uh case we can get if we sell at day i uh case we can get if we sell at day i and if you buy a day i like uh like dp of is the is the best profit we can make if we buy at day i and dp of cell is and dp of cell is is the best profit that we can make if is the best profit that we can make if we we sell at day i okay so if we buy a day i the the answer will be uh dp of cell like we can sell actually in any day right so we can say we like it will be maximum of dp of cell i like i plus 1 and dp of cell uh i plus 2 like continue something like that okay and if you sell it day one the it will be also maximum of dp of i by i plus 2 dp of by i plus something like that uh something like that uh what do you think this makes sense what do you think this makes sense uh yes so we have this [Music] uh there's like one more way that we can try to solve it using backtracking and then we can use some kind of memory numeration uh like we can store it in custom cache after we solve it using backtracking i think that will be easier to implement yes okay so how would you implement using backtracking yeah we can solve it using backtracking then we'll understand and then we can use the dp to solve it in a better way so how to solve it using backtracking okay let me write the functions how to solve using backtracking so are you writing the solution yeah i'm just trying to like figure out so should i stop my screen share it's okay uh you don't so if i have definition of backtracking how to solve it using backtracking so we how to solve it using backtracking so we can start from so we have an array and we have like okay let's pass index and prices we like stopped prices we like stopped return okay and let's try to find the and let's try to find the other cases so and we also have to pass other cases so and we also have to pass like we need to buy or sell like we need to buy or sell so let's pass two boolean values yes like just buy something like that is buy so we have to buy it sorry is buy so we have to buy it sorry so if this buy we have to buy it so if this buy we have to buy it so if we have to buy it so either i can so if we have to buy it so either i can buy buy by now or i can buy by now or i can buy the next time next day the next time next day so if i have to buy now then i will buy it so i will buy it so i will buy it today so the so i will buy it today so the price will be prices index okay or i can do a backtracking of next day i can do a backtracking of next day which will be which will be index plus one and is buy will be still index plus one and is buy will be still be true be true and if i buy today then i have to sell the next day sell the next time time so we have to pass we have to do backtracking and index plus one is by will be like this by will be false we have to sell it right and it will be this by true if you have to buy it and and we also we also have to keep track of the profit that we are making so we have to also pass like yeah profit and when you this this so we will have a self dot maximum profit which will be zero and when you reach the end we have to uh do like self max profit will be maximum of sales max profit and profit that makes sense make sense so and now when you sell then we have to get the uh price like profit so here we have to pass one more variable like like the last price like if i have to sell like uh i'm like else so we have to sell right we took a return we don't have to go more so because we should avoid the else conditions as much as possible so now what will be the profit so now what will be the profit profit will be so i can sell now profit will be so i can sell now or i can also sell the next day two or i can also sell the next day two options options to options sell today or sell next day although like we can like sell next time so for the cell next time uh it's like index plus 1 index plus 1 and pi is false and pi is false and profit will be profit is not and profit will be profit is not changing so i'll just pass profit changing so i'll just pass profit everywhere everywhere profit profit and profit profit profit and profit but if i sell today i make some profit but if i sell today i make some profit so profit will be so profit will be plus equal to or the price of today like plus equal to or the price of today like sale price sale price like sale price will be like sale price will be prices and index today's like price because we are selling today so the profit will be self sell price minus like we have to pass one more variable like when i bought it by price so i have a buy price so sell price will be sell price minus by price and i have to backtrack and because i have selled it today i cannot sell it plus two yes and i have to pass it as true true because next time i have to uh buy it and i have to pass profit and uh by price by price will be zero like because i i'll buy the next time right so i don't have to consider my price so i prices will be zero but set but in the cell next time uh which line in the line 35 uh which line in the line 35 in line 35 the sale next time will be uh in line 35 the sale next time will be uh yeah it will be yourself will buy price yeah it will be yourself will buy price right right yes because we are we have not been yes because we are we have not been bought it yet bought it yet so i have to do it the next time so we so i have to do it the next time so we have to buy price and profit have to buy price and profit so also let's put by price in so also let's put by price in here also by price in here like okay if we buy now then the price by price will be priced right because you're buying two dates so yeah we have bought it so sell price will be this and also you sell price will be this and also you have to make one more case if have to make one more case if index is greater than index is greater than uh length okay put it in this actually uh length okay put it in this actually oh no yeah like return so that we don't oh no yeah like return so that we don't have an array out of bound have an array out of bound induction because here we can you know induction because here we can you know whenever we're being plus two whenever we're being plus two then we can reach the end like when you then we can reach the end like when you reach the end reach the end when you sell it uh like the last day when you sell it uh like the last day we can again might try to buy you know we can again might try to buy you know like some area like some area out of bounds so we can prevent it using out of bounds so we can prevent it using index this okay index this okay uh do you think this looks okay uh do you think this looks okay backtracking index plus one false so backtracking index plus one false so let's check the let's check the flags one more time all the plugs flags one more time all the plugs so we have this and let's also write the driver function here and index will be zero and i have to buy and index will be zero and i have to buy first time first time so it will be true yes by price will be and so by price one second return self one second return self dot max pocket right dot max pocket right yeah once again yeah once again line number line number 34 like the line number line number 34 like the third argument shouldn't it be price of third argument shouldn't it be price of zero zero yeah by price no actually when we yeah by price no actually when we buy then it doesn't matter right like buy then it doesn't matter right like because because suppose we are buying here is buy oh yes suppose we are buying here is buy oh yes yes because yes because it doesn't matter because we are buying it doesn't matter because we are buying that time so the previous that time so the previous price of buying doesn't matter but when price of buying doesn't matter but when you sell you sell it matters the buy price so because you it matters the buy price so because you have to buy the first time so we can have to buy the first time so we can just pass zero right okay so let's try so let's go through the code one second and try to like see so if index is greater than length prices then return we don't have to do anything and if you reach the last one so just update actually we can also do it like combine this two as right now okay so so like don't we have to check the is by variable like uh if we just bought one item and haven't sell it yeah yeah right right in this case the profit will be but profit will be profit right so that doesn't matter like i understand your point is like yes yes what if we sell or buy like does but if we do not sell one item like yeah that's okay like thus uh is by flag matter here that's a question right i think it doesn't matter because like suppose uh we have two cases right one is we have to buy it at the end or sell it but whatever the thing is the profit is already made okay and and at the end we are not doing anything so we don't need to consider this flag okay so now if okay so now if is buy we have to buy it now so we have is buy we have to buy it now so we have can do can do two thing we can buy today or we can buy two thing we can buy today or we can buy the next day the next day like the next time so if we buy today then the price will be the price of index and we have we are buying so we have to update the price by this price and profit will be profit and backtrack the next one because next day we have cancelled and we are making this flag as false because we can sell and or we can do the next time we can buy the next time so just do index plus one and true by price and profit that's it or we can sell it or if this flag is false then we need to sell it so the sale price will be prices of index so at this price we have to sell it okay we have like two options like sell today or sell next time so next time is like very simple so we just do index plus one and false and by price and profit we don't do any update here but if we sell today the profit we make will be on today's price minus buy price at which price we bought that share and we upgrade this profit and we and we backtrack so all and we backtrack so all so that is my solution do you think it so that is my solution do you think it should work should work it should work okay let's run in the it should work okay let's run in the code okay we got this three so i think this will work but we might get time out because it's not be optimized okay so we got something wrong here so okay so we got something wrong here so we have one two and four we have one two and four uh output is okay so we are cutting output as four okay so we are cutting output as four but we should get three but we should get three what is going on here so we haven't checked a buy price yeah so by price is like not set maybe somewhere so price is the prices that index and backtracks index plus one by today or by okay let's uh print something here and okay let's uh print something here and see what happens so see what happens so we are selling here right so print so this will be else right effects print sell price so in case of okay let's do a dry run so in case of okay let's do a dry run and see where the coat might get wrong and see where the coat might get wrong so we have one two four can you do a dry run one two four so what will happen so i first improve true three zero so yeah we will buy it so we have zero true zero zero so we have uh is buy is true so we can buy today back by taking one okay and uh okay so let's uh keep going so now we or we have this one it will be backtracking off one one two two one and zero by price yeah by pressing one which was zero right by price should be zero and profit is zero because you'll not have buildings yes yes okay now we have this so let's consider this case we have one so now so now we have it goes here again we have it goes here again and we have index no and we have index no we now we have sell right we have false we now we have sell right we have false we have sell here we have sell here so we can try to sell it today okay so we can try to sell it today okay so sell price will be uh so sell price will be uh so index is okay sorry index so index is okay sorry index equal to now 2 and equal to now 2 and we have this condition we have this condition backtrack one false one zero so now backtrack one false one zero so now index will be index will be uh one index only one uh one index only one yeah it will be yeah this will be one so now we have to sell sell price will be two two and profit will be sell price one two minus y minus one so one what will be one will be one so now if we backtrack uh to true and true and profit zero properties indexes one right then we do uh back in x plus two right so one index plus two so it will be change three so when we have three then it will stop so when we have three then it will stop right uh and we update the max profit right uh and we update the max profit to uh max profit will be to uh max profit will be two one yeah so that's probably one two one yeah so that's probably one right because we right because we have one yes now we have the have one yes now we have the case of buy so we have bought it case of buy so we have bought it at so yeah so now we again have this at so yeah so now we again have this case that we don't sell today case that we don't sell today we sell the next day so it will be backtracking of we have two right index will be two and this will be false false by price will be one one one profit will be zero so now now we come here again and now we try to solve it for two like we are selling at day two so sale price will be prices of index which will be four four yes right and profit will be that's right three three and backtrack and backtrack will be five true zero and three so why are we getting four the question okay let's open one thing we can print okay let's open one thing we can print print print index uh index uh you can just print the four variable we you can just print the four variable we are setting it why profit is becoming sorry let's do one to four so in this case profit is favoring four and three true and three true why profit is becoming 4 4 is the profit okay can you think of when it is written for profit profits always sell price minus profit profits always sell price minus by price by price oh we are doing plus plus one oh we are doing plus plus one so one time we have maybe we are getting one somewhere and one plus three so we have three true so three is the index and zero is the is the buy price this one and one is the profit yes so [Music] and now we have four is the index zero and now we have four is the index zero is the buy price profit is four so how is the buy price profit is four so how we are getting profit as four we are getting profit as four answers so let's just print oh i think we are setting the what oh i think we are setting the what profit here right yes so that's what i'm profit here right yes so that's what i'm making mistake making mistake i got it so you know here we're setting i got it so you know here we're setting this property here this property here yes so like let's make it yes so like let's make it original profit original profit okay like okay uh let's make a new okay like okay uh let's make a new profit profit the profit will be profit plus the profit will be profit plus uh this silly mistake silly mistake and we passed a new profit here and we passed a new profit here and you pass the profit here ah yeah cool one silly mistake okay uh let's give this one to so yeah so our solution is correct we so yeah so our solution is correct we just need to optimize it so now we need to optimize it our back so now we need to optimize it our back tracking is working fine tracking is working fine so let's just take out the code okay so do you think we can do uh a caching here imagination memoration here is possible i think we can do it so backtracking because this one we are so backtracking because this one we are doing it doing it repeatedly so this profit repeatedly so this profit we can save it in some we can save it in some we can have in dictionary of this we can have in dictionary of this element and like uh like if i have to element and like uh like if i have to do it like self dot cash will be this and when we get the return sell cash index is by by price and profit you can index is by by price and profit you can put in cash right who can how would we cash it so how would we cash it so because you're doing a backtracking so i because you're doing a backtracking so i don't think we can do caching because don't think we can do caching because we're doing backtracking so we're doing backtracking so because we don't have any any track we because we don't have any any track we are not are not getting the value from uh like there uh but maybe what we can and we have this profit which will keep changing so i think caching is not a good solution is there any way any like sub problem that we are doing i think we are solving this one i think we are solving this one repeatedly right this back tracking repeatedly right this back tracking index true false plus one index true false plus one yes and this yes and this so i think what we can do is if we so i think what we can do is if we pass the profit you know as pass the profit you know as a result a result then we can solve it i'm not sure then we can solve it i'm not sure like like we we are doing it from you know like recursively can we make it iteratively and then how to cash it like what you can do is maybe not pass the price but when we buy it past the index you know when we bought it like and then that can help us to solve this thing okay so uh the answer is like we have to do something so we change it a little bit and uh instead of this buy price and profit we have to pass the sell sell index or like buy indifferential index find extension index okay then we can solve it so how can we do by index and cell index and solve it what we can do is we'll discuss one method that we have solved seen in the which is similar to our solution java yes java yes so let's try to understand it first get maximum price so we got a working solution java that so we got a working solution java that is almost same as what we solved but uh is almost same as what we solved but uh they used they used the almost the same way but they have the almost the same way but they have managed to make the cache managed to make the cache like a memo to solve this problem so [Music] let's go through the solution and because this is similar to what we make so forget this dputil we i think we don't have this one yes we only need so as you can see this code is running and this if you submit it it will yeah it success so we have so instead of uh so we have so instead of uh the keeping track of the profit we keep the keeping track of the profit we keep track of two track of two indexes like buy index and sell index indexes like buy index and sell index and we have the prices which is the and we have the prices which is the average that we passed average that we passed and we keep it keep track of the profit and we keep it keep track of the profit between this buy index and sell index between this buy index and sell index in a memo 2d array in a memo 2d array so let's see what they have done it so now we have the base case that if by index is greater than prices dot length or cell index is greater than price of dot length then we cannot do it anymore we reach the end so we return zero okay and if we already have the solution of buy and sell index then we return the buy and sell index it's memorized yeah yeah or we compute the memo so if the price of cell index is less than the price at by index they cannot do anything we just return the uh the we that we just go to the next index because buying buying is not possible possible so we just try to buy from the next index and sell from the next net index this is the like or we can buy it we can we can sell it so if we can sell it we have two option either sell now or sell the next time they like that we did before so this so that we can understand so we this so that we can understand so we have to option have to option that we can price like profit price like profit and profit yeah profit and profit yeah profit now profit now will be now profit now will be the price of so we just sell it the price of so we just sell it right today and we also now uh and from because we sell we sold at uh sold index so we can again start we have to give one day of cool down so we can do it from plus two like yes after uh one day and and the cell index will be plus three because we have to buy after this index okay so profit and it will be maximum of and it will be maximum of math this or math this or we can sell it the we can sell it the next day which will be plus one next day which will be plus one so this is the uh way to solve it so this is the uh way to solve it it is the same of what we did but little it is the same of what we did but little bit better because bit better because uh because of keeping track uh like uh because of keeping track uh like track of the profit track of the profit we just keep track of buy and sell index we just keep track of buy and sell index so that we can so that we can ah build this uh matrix ah build this uh matrix in a right way but in the interview even if you can solve using this uh this backtracking you you will get some points and maybe you will get the offer because no one expect you to come up with this solution by yourself and the interview will guide you to how to reach this solution but it's great that we had a good thinking process and you can solve it in this way | 2024-03-24 10:10:38 | 309 | LeetCode 309-Best time to buy and sell stock with cooldown |
|
iX1N52oRJ8M | QUESTION KEY YOU SO LET'S START IT IS SO WHAT DES EN MARRIAGE MINS FIRST OF WHO IF WE SEE THIS NOT IF WE SO WHAT DES EN MARRIAGE MINS FIRST OF WHO IF WE SEE THIS NOT IF WE CONSIDER CONSIDER NUMBER DATE IS ONE YOU TU ONE SO IF WE NUMBER DATE IS ONE YOU TU ONE SO IF WE START IT FROM D STARTING START IT FROM D STARTING START IT FROM D STARTING and they bill come de number it note so what they need you do they have you start reading from meaning they have you be read it from starting and you can see every it is coming out you be from it Mins aur number ok so what is it simple ki hum log itse kya kar sakte ki isko ki hum log itse kya kar sakte ki isko na hum log matla le jaayenge aur hum log kya kari compare kar yahan par aaye equal tu zero lagayenge [Music] Because if this condition of ours is not fulfilled, that is, if this condition is not fulfilled then we will be taken out of the loop and what will we do, we will get 4 sitters done, okay so this is a simple method, you can think but it is Note applicable every d region behind dead it is you can see dr what jump it you tu it in zero and time and zero of one space so so this method will not reduce ours okay then it will not reduce so I have to think, I have to think, I have to think, okay, because this has become stupid and space, okay, because this has become stupid and space, okay, now what can we think that okay, now what can we think that suppose if I divide my number in two equal suppose if I divide my number in two equal parts, this is equal parts and then parts, this is equal parts and then suppose you check it from starting what Do per de second number means Do per de second number means Do per de second number means divided portion de second record both de tu number [ condition you can think of this is on and condition you can think of this is on and seeds but today you can think of of number seeds but today you can think of of number which is of meaning size so what you can think of one tu which is of meaning size so what you can think of one tu three three three Number This One Too Three You One So What You Can Think About It's Simply Date You Have Too Be Divided Into Equal Parts I Bill Tell You With One More Example of No Date Suppose one two four three one Suppose one two four three one Suppose one two four three one it is n number ok so it is n number ok so what will we do first of all just divide it from what will we do first of all just divide it from middle you can divide from middle you can divide from each and every it total depends on you ok each and every it total depends on you ok we we can do any fashion ok we can do any fashion ok we What did people do from here and check this, this is how much it is, What did people do from here and check this, this is how much it is, one, two and four, and what did the numbers behind them do, one, two and four, and what did the numbers behind them do, reverse the date, this is how much will reverse the date, this is how much will come, come, then we will check a question, this then we will check a question, this is from 11, okay, you and three are from. is from 11, okay, you and three are from. is from 11, okay, you and three are from. not there, it means that this number is not the first one, after that we will divide it, okay, how much will come from here, 123, what will we do with the last number, we have to reverse it, how much will come, one People were like, let's People were like, let's People were like, let's count from the front, let's count from the back, count from the front, let's count from the back, he will come from the same place, he is coming from the same position, that's why he will come from the same place, he is coming from the same position, that's why we consider only the people, if we consider only the people, if both of them are okay, then how much has he come from, this one both of them are okay, then how much has he come from, this one is from this, he is from this one too, you are the same. is from this, he is from this one too, you are the same. is from this, he is from this one too, you are the same. count from the front for both, when count from the back, the function can be done at both places, so it means A is for both, so what is our number, so this is the simple condition that What we have to do simply What we have to do simply [Music] [Music] What is the first [ Music] D Second we have to compare it, how to find out the middle Okay, so here you saw that our first We will find out the middle We will find out the middle We will find out the middle here, so first of all, here, so first of all, now we have this, let us make two points, now we have this, let us make two points, I will tell you what is the need to make two points I will tell you what is the need to make two points because we have to find out the number, because we have to find out the number, okay, so we are making 2m, okay, so we are making 2m, okay, so first of all. Okay Hum log kya loco bhi hai so find out and do fast Hum log kya loco bhi hai so find out and do fast Okay, Okay, fast and next should not be null and close next's next fast and next should not be null and close next's next means fast's means fast's next What is this one this one next What is this one this one next What is this one this one and fast key next connect, this one is top with mixer, these two are not taps, it means what will be slow, one less will flood next, now where will this one come, On On On next pay, it means next pay, it means here on here, we will check again, again, there is a here on here, we will check again, again, there is a connection, means that the value of our slow key has come, means that the value of our slow key has come, we have to return it, we have to return it, what does it mean this is the number, no, this is the number, no, this is the number. this is the number. this is the number. okay, we have made the head, after that whether the next of okay, we have made the head, after that whether the next of five is next or not, five is next or not, then first of all five's next means this one, this one, then first of all five's next means this one, this one, you and his next's you and his next's next. next. next. not, what does it mean, the one who is a slow painter, will flood the slow bill, the other one will be of fast one, okay here, what will happen now is that he will check again for fast and the Look, five's Look, five's Look, five's next and its next's next, next and its next's next, what doesn't it mean that the one who what doesn't it mean that the one who is slow will go one less further, he will go to 3 and the one who is fast will go to where three, so you can see our three, so you can see our How much is the output? Three and we will see that it How much is the output? Three and we will see that it is digital and how much comes in it. What is our is digital and how much comes in it. What is our mid number? What did we do? Divide it by MED. After that, what did we do? The term which is the number below, we have to reverse it. Okay, we have to reverse it. Okay, so we go to our reverse one. We have given We have given We have given three points to me, I have started first, three points to me, I have started first, how much was created, how much was created, created a point named Previous, created a painter named Current, created a point named Previous, created a painter named Current, okay, so what is the previous first and okay, so what is the previous first and who has done the current on the current? By help on help, I who has done the current on the current? By help on help, I mean this one which mean this one which mean this one which not only this is our reverse string, that is, these are the notes, we will look only at this one, so what is the current, we are on the head, that is, you are on and next, On On On what is the current and next, our current what is the current and next, our current is on the next one, okay but what does it mean, is on the next one, okay but what does it mean, vile current is not equal to null, vile current is not equal to null, what does it mean, we have to do the whole link what does it mean, we have to do the whole link till it is not null, it is caste, okay, till it is not null, it is caste, okay, then more. then more. then more. Next and Next These both are different and you can write different names if you want. Okay, where is the dot, see here, you Operator Operator Operator A is the dot operator when it has to be there, A is the dot operator when it has to be there, what is the meaning of next after that, it is to what is the meaning of next after that, it is to tell that after this note, we have to jump to this note, tell that after this note, we have to jump to this note, okay and JB is also okay and JB is also written simply next, what is the meaning of this name. written simply next, what is the meaning of this name. Okay, I have understood now, Okay, I have understood now, what have you done after that, how much has this one become? These what have you done after that, how much has this one become? These three conditions of ours will three conditions of ours will come under our first. Okay, what is written after that, come under our first. Okay, what is written after that, current.net, equal, you, previous, Note, what will it Note, what will it Note, what will it indicate? Okay, the net of the current has to be indicate? Okay, the net of the current has to be indicated. Here, indicated. Here, what is the previous to the previous? We have a null, so what is the previous to the previous? We have a null, so what does it mean, now how much will our current become, then how what does it mean, now how much will our current become, then how much is the current? much is the current? After that, what is the previous equal to current? After that, what is the previous equal to current? What will be the previous bill's hole position of the current What will be the previous bill's hole position of the current current, how much was the current, current, how much was the current, what will be the hole in the previous, what will be your position, date is what will be the hole in the previous, what will be your position, date is here, this will be our current, our tap is done, here, this will be our current, our tap is done, what is the meaning of this which is closed of ours, what is the meaning of this which is closed of ours, it will break here. it will break here. it will break here. pointing out the tap, as you can see the current is pointing out the tap and the previous one is no holding empty, poor guy, now this empty, poor guy, now this empty, poor guy, now this this previous bill hall disposing of? If the previous bill hall disposition is ok, then what is the current in it? What is the what is the current in it? What is the current in it? What is the current here? Who is the current halling now? Next is the next one, current in it? What is the current here? Who is the current halling now? Next is the next one, what was our one, what was our one, what will happen in it now? what will happen in it now? what will happen in it now? D Next date this one current is halling whom one is ok so inside the current inside the previous you went to A and inside the connect one A went when as soon as this happened then it Because of these means Because of these means Because of these means this one, in the first starting, this blink dr was this one, in the first starting, this blink dr was closed, what will happen after that is closed, what will happen after that is that our as soon as this is current equal you next, this one that our as soon as this is current equal you next, this one is this point, whatever happened, it is this point, whatever happened, it started indicating this and this is our node. started indicating this and this is our node. started indicating this and this is our node. simply one is indicating you are simply what will we get done written previous second previous means they have you be indicating also means this whole note of ours will become a, it is representing, okay, what did we do, we got our note reversed. This one and you are gone, okay now in the last what we have to do is 1 and 2 of the starting and one behind and you, what was our number, this is our number, so what is ours and this one behind, if we reverse it, then 12 These two are equal, what does this mean 12 These two are equal, what does this mean [Music] So I have already simplified all this, name, what should we do in this, we will name, what should we do in this, we will check, check, okay, first of all the condition is fine, If you do If you do If you do n't have any note then will you get return 2 done? n't have any note then will you get return 2 done? If there is zero number then If there is zero number then you will get return done. If there is no number then you will get return done. Middle is equal to first middle head. Now what we have to do is find out which one is in the middle or not. Middle is equal to first middle head. Now what we have to do is find out which one is in the middle or not. Middle is equal to first middle head. Now what we have to do is find out which one is in the middle or not. doing is to do the evening point, which was the first half, so that if we divide the last number, which is the starting point, then what will we do, which is the starting point of the next number, If this is the number, then we will know that you are the next one, what will happen to us, which is the second portion, which will be its starting point, how far will we write, the second half will be the how far will we write, the second half will be the starting point of the second half, that is the starting point of the second half, that is the middle of it, which I told you right now. middle of it, which I told you right now. Found his just next one, this is what Found his just next one, this is what I told you that his just next one will be, I told you that his just next one will be, what is there after that, the list what is there after that, the list note that starts the first half is the note that starts the first half is the head, any note starts with what, head, any note starts with what, headset is ok, what do we do now? headset is ok, what do we do now? headset is ok, what do we do now? check which is the first part of the second half. Unless it is being taped, what does it mean that we have not played the entire string, we have played our entire note, it is People, this People, this People, this portion is to be completed from start portion is to be completed from start to lake entry. to lake entry. Okay, Okay, what to do after that to check that what to do after that to check that if your value is before our start, if the value of the if your value is before our start, if the value of the first start of second half is first start of second half is not there, then we will get our returns burnt. not there, then we will get our returns burnt. Meaning. Meaning. Meaning. and its value, if it is not from both the keys, the value of the start of the first half, second half its value, if it has not come from both, then next step is now you will see the Let us tell you in the big jam, Let us tell you in the big jam, Let us tell you in the big jam, see what is said here, we will move forward here on the first starting basis [Music] If this flower condition is achieved, then what will we get done in the end, it will be written true and our program will be successful, okay People must be understanding it, okay, so see, we are People must be understanding it, okay, so see, we are People must be understanding it, okay, so see, we are running 'Accept' and after running 'Accept' and after submitting it, let's see the complete submitting it, let's see the complete convenience. Okay, so convenience. Okay, so see, you can see here, I told you separately, first of all the tell it in big | 2024-03-22 11:22:04 | 234 | Palindrome Linked List | Leetcode 234 | Linked List |
|
ITvYKB8BjEo | Hello Hi Guys Welcome to Cold Weather Today is Question is Combination No. 3 in this question be up to find all the possible combination of number dep guddu and number and given to 19 number from one to 9 can be And Give The And Give The And Give The Number 2 And Subscribe Combination Number 2 And Subscribe Combination Combination Video give Number Distance From Combination Video give Number Distance From 12951 Combination 1253 For To-Do List From This 12951 Combination 1253 For To-Do List From This That Now Hindi Souls Will Have To Take Only Three Number Three Number Combination To Generate Is Impossible Nahi Soe The Combination Veerya The Commission r12 65 2340 Combination of Three r12 65 2340 Combination of Three r12 65 2340 Combination of Three Does It Is Equal to the Guide subscribe and Does It Is Equal to the Guide subscribe and subscribe the Channel Number One Two Three One Two Three One Two Three subscribe the Channel Number One Two Three One Two Three One Two Three Two Elements Two Elements Combination To-Do List Combination To-Do List A Vision for All This Subset Offers Numbers But A Vision for All This Subset Offers Numbers But on One Two Three End on One Two Three End on One Two Three End find that subject which achieve this and 10 20 condition vacancy in this app has only been subjected to three liquid liner is condition in this is only and such Samadhi element of these types 500 to three is the answer subscribe Video subscribe How to take atul wali committee offer answer birthday idea is to generate submit listen let's look at the driver of this code no left-front taken 9th article 356 simplicity purpose and goals to point two elements high music 125 29 this question is C What is the C What is the C What is the Main Function of World 2151 Study Into Main Function of World 2151 Study Into Consideration Elections 2019 Absolutely Consideration Elections 2019 Absolutely Against Two Elements To 9 9 4 4 2nd T20 World Against Two Elements To 9 9 4 4 2nd T20 World Cup 2012 Elements Of Elements December 19 Cup 2012 Elements Of Elements December 19 2012 2012 That I Absolutely To So In This Case Will That I Absolutely To So In This Case Will Not Make A Call For Forward Not Make A Call For Forward Not Make A Call For Forward A Call Forward Is Finance Minus One Day It Will Consider These Three Elements Good 2012 Elements That Will Not Make A Call Forward Will Just Simply Is Vitamin A Call From Near 90 Coolness Want To Know It Will Call And Elements 30 And And Elements 30 And And Elements 30 And Came One And K In 2009 Came One And K In 2009 That Similarly In This Condition Also Most That Similarly In This Condition Also Most Mega Call Forward In Last Week Ka Call Mega Call Forward In Last Week Ka Call Forward Earth And One Element Will Also Increase Forward Earth And One Element Will Also Increase Not Only Earthquake Will Be Equal Not Only Earthquake Will Be Equal To Minus One Which They Have Taken Into To Minus One Which They Have Taken Into Consideration Consideration Return The Call From Her Only Been Return The Call From Her Only Been Cases And The Answer Is Not Found No One Will Go Cases And The Answer Is Not Found No One Will Go Back To This Will Make A Call To Back To This Will Make A Call To A Friend Spider-Man NDA 350 Elements A Friend Spider-Man NDA 350 Elements And Give Vikas Vyas And Give Vikas Vyas And Give Vikas Vyas Consideration Noble Call Forward 99 Hair And 10 And K Vacancy Means Switch Powder Combination In Which Year And Also Like World Tourism Day Required And A Number Of Elements Of All Should You Record Only Like Five System * Uniform Elements Which Are Combination Will Take This Comes Combination Will Take This Comes Combination Will Take This Comes Into Account And After 10 Years Soft Into Account And After 10 Years Soft Science To Make A Call Forward Because RN Science To Make A Call Forward Because RN Vikram Negative And K Vikram And Sune Vikram Negative And K Vikram And Sune Tips Will Return From Hair Election Tips Will Return From Hair Election Bansi Lal Written Test Will Return This Adhikat Bansi Lal Written Test Will Return This Adhikat 232 232 That Nau And Spine And They Can Do That Nau And Spine And They Can Do That Nau And Spine And They Can Do Quiet's Vikram One Election Absolutely Head But Did Nothing So It Will Return And Nowhere Recorded Decided And Witnesses And DR All The Answer To Return To The Email Serval Combination Vighn 1947 To Three Will Thursday K Dushman Solar Panel Answer Will Return Return This Answer And Nor Will Make Butter That Bismil Saurabh Current Commission And Will See Weather This Current That Bismil Saurabh Current Commission And Will See Weather This Current Commission For Being Given Commission For Being Given Condition For Not Knowing What Will Do What Will Condition For Not Knowing What Will Do What Will Caller Equations Recursive Function In Caller Equations Recursive Function In Caller Equations Recursive Function In That Art Architecture And Enters Size Duration Target That Art Architecture And Enters Size Duration Target Required Its End Share And Required Its End Share And Starting Audition Date Of Birth Jeevan The Starting Audition Date Of Birth Jeevan The Number 212 Not Starting Number One After This Application Has Been Called Number 212 Not Starting Number One After This Application Has Been Called Will Return Will Return Divya Answer Function The Answer Is Gold Channel Combination subscribe Video Combination subscribe Video Combination subscribe Video like and subscribe the Channel and 10 and like and subscribe the Channel and 10 and 1000 combination looking for some will 1000 combination looking for some will and discrimination in no final answer answer and discrimination in no final answer answer is back a are current is back a are current current events which contain the current current events which contain the current combination no will return from her big combination no will return from her big boss big guide will be developed within boss big guide will be developed within boss big guide will be developed within them and will be amazed and the will also be the native and as well as know you certificate condition second day box one hour of 10 limit of elements in two front 98100 something about it and will agree with you ka Want To Know Want To Know Want To Know And Between m0vie Can Not Take Any And Between m0vie Can Not Take Any Element Here Element In Consideration For Rate Element Here Element In Consideration For Rate And Wars Still Have Any Value In And And Wars Still Have Any Value In And So In This Case Better Returns Returns From Here Only So In This Case Better Returns Returns From Here Only Be Kanpur Down Words Be Kanpur Down Words Om Nandishwar Best Condition No Valid Lighter Om Nandishwar Best Condition No Valid Lighter Loop Point High Loop Point High Loop Point High plus the first will happen it into your current vector will consider this element also on a back I know at all Nakul per reaction function only Krishna can only happen in the sporting answer or current that and - Strategic Strategic Strategic 121 Subah At Least One Into Account Swar 121 Subah At Least One Into Account Swar To Sudhar New Answer Which Will You End When To Sudhar New Answer Which Will You End When Required In Further Iterations Will Be For Required In Further Iterations Will Be For Note 500 Notes Printed And Elements Note 500 Notes Printed And Elements Class Voucher Decree By One And All Class Voucher Decree By One And All Meditation Will Be Called From I Plus One By Itself Meditation Will Be Called From I Plus One By Itself But But But Not To Find Information For One Beat 12345 Dowry Into Consideration And Take Vansh Again Into Consideration Thee And Suno Vinati Shri Krishna Functions Over BF Got All The Combination Richa Starting From 20th Starting From Chief We Are Not Refrain From Next Number 12192 Subscribe 159 Are Ke Raaste Seervi A Pooch Yovan In From Shri Ke Raaste Seervi A Pooch Yovan In From Shri Krishna Call Back Find All The Congress Meter Krishna Call Back Find All The Congress Meter Cutting From Nowhere Pop Back 118 Mode On 419 Oil Boil Smoke Plus 9 Portions Of Welcome To Back Starting From Evil Bake Its The Day the President Accepted Only Custom Presiding Accepted I Hope You Presiding Accepted I Hope You Liked Video Thank You Too | 2024-03-22 10:41:12 | 216 | Combination Sum III leetcode | Leetcode 216 | Leetcode September Challenge |
|
KGfXrj7G0W0 | hello everyone welcome back here is my name and today we are tackling the name and today we are tackling the infamous text justification problem infamous text justification problem number 68 uh on uh little daily number 68 uh on uh little daily challenge so it's challenge so it's a fantastic challenge especially for a fantastic challenge especially for interview so first thing first interview so first thing first understanding the problem we are understanding the problem we are essentially building a mini justify essentially building a mini justify feature for a word processor and given a feature for a word processor and given a list of words and a Max white we need to list of words and a Max white we need to format this words so that they are format this words so that they are Justified on both left and right so Justified on both left and right so there are some nuances but that's the there are some nuances but that's the gift so let's have a look at example two gift so let's have a look at example two clarify so with the word this is an clarify so with the word this is an example example and Max white of 16 our output should be and Max white of 16 our output should be like this so maybe a visual like this so maybe a visual representation is easier so it's representation is easier so it's Justified text so notice the varying Justified text so notice the varying spaces and between the words so that's spaces and between the words so that's the magic we are about to implement so the magic we are about to implement so let's start coding and we will employ a let's start coding and we will employ a greedy strategy trying to fit as many greedy strategy trying to fit as many words on a line as possible then we will words on a line as possible then we will distribute spaces using modular arithmet distribute spaces using modular arithmet so it's simpler than in sounds so I so it's simpler than in sounds so I promise the core idea is to pack as many promise the core idea is to pack as many words in a line as we can and without words in a line as we can and without exceeding the max white and once we have exceeding the max white and once we have got our line we will distribute spaces got our line we will distribute spaces between the words and if spaces between the words and if spaces I don't divide evenly among the words we I don't divide evenly among the words we use modulo to add more spaces to the use modulo to add more spaces to the leftmost gaps and for the final line we leftmost gaps and for the final line we simply left align text simply left align text so I have so I have let's implement it and then I will dive let's implement it and then I will dive deep into the code deep into the code so so resolved blind white will be all right resolved blind white will be all right all right and zero and four W in words all right and zero and four W in words if white plus Len W landline greater if white plus Len W landline greater than Max White than Max White for I in range Max y minus White for I in range Max y minus White line I modulo Len of line minus one or line I modulo Len of line minus one or just one just one and plus space and plus space and and result line white will be result Plus result line white will be result Plus join the line also all right join the line also all right and zero and zero and line will be plus W and line will be plus W and Y will be plus length of w and Y will be plus length of w and finally return and finally return result result Plus Plus join join line L dust L dust the max white so okay let's run it to the max white so okay let's run it to verify uh verify uh it's it's working working so yeah o is working so as we can see so yeah o is working so as we can see and what we did so now diving deeper the and what we did so now diving deeper the logic so we start by initializing three logic so we start by initializing three main variables so rest so this will main variables so rest so this will store the final result containing store the final result containing justification line justification line and line is a temporary list to hold the and line is a temporary list to hold the words for the current words for the current line and white this gives track of the line and white this gives track of the total character length of the words total character length of the words added to line and then the main logic of added to line and then the main logic of our solution begin as we look through our solution begin as we look through each word through its word in in our worth list so for each word uh w we check if adding it to the current line along with spaces I would exit the max wide so the expression white plus Len plus land line so this one gives the total white of the line if we were to add the current word and here land line provides the minimum number of spaces required since there is at least one space between each word and if adding the words would exceed this white it's time to justify the current line so the inner loop distribute spaces among the words in line so the modulo arithmetic ensure Extra Spaces are added to the leftmost gaps between Wars so it's a clever trick to guarantee even a distribution and the expression I modulo landline minus 1 over 1 so this one helps decide where to place the extra space and after justifying the line we append it to our results so simple and rest line and white to the next set of words so then we add words to the line so if there is still a room on the current line for the word we add it to line and update the white and once we have processed all words there is likely a partial line left so this represents the final line of the text which gets left justifies so we use a python L just method to ensure it takes up the full Maxwell right padding it with spaces on the right if necessary so and there we have it this solution is quite efficient for packing the works into a line and justifies the text using the bondulo operation so the modular helps us decide where to place the extra space ensuring a balanced look so now let's submit it for unsynthesis cases to verify it's working so yes it's working and as you see it's bit 83 with respect to random so I have run it previously so it was even 94 percent but yeah maybe it's a different test cases or something so basically it's quite efficient and also uh code is short and elegant and the beauty of this approach lies in its simplicity so we are using python list and string module operation uh and that's a heavy lifting of the space distribution uh so all right that's a wrap up of our live coding session I hope you found it enlightening and if you like uh seeing implementation in other programming languages check the description below and as always hit the like button share and subscribe for more coding Adventure tutorials and much more always practicing happy coding and see you next | 2024-03-20 11:13:47 | 68 | How Text Justification Works: LeetCode 68. Text Justification Diving Deep with Python |
|
i7brwcn2v7o | so so for today's question that is power of so for today's question that is power of 4 4 we have been given an integer n we have been given an integer n that should return true that should return true if if it is a power of 4 otherwise it should it is a power of 4 otherwise it should return false return false so basically uh n is so basically uh n is is the power of 4 is the power of 4 that means uh for that means uh for integer x such that n integer x such that n is equals to 4 part x like it should be is equals to 4 part x like it should be a power of 4 so 4 16 a power of 4 so 4 16 16 into 4 something like that it should 16 into 4 something like that it should go like that go like that so so if we are getting uh putting n equals to if we are getting uh putting n equals to 16 then it should return true because 16 then it should return true because that's a power of 4 if it's a 5 it that's a power of 4 if it's a 5 it should written false should written false if it's a 1 it should return true if it's a 1 it should return true because uh 0 because uh 0 if our value of x equals to 0 it should if our value of x equals to 0 it should it would return 1 so that's why it it would return 1 so that's why it should be true should be true okay so this is uh my solution so what i okay so this is uh my solution so what i have done is taken integer r that is have done is taken integer r that is equal to zero that is remainder and equal to zero that is remainder and while n is greater than one and r is while n is greater than one and r is equals to zero equals to zero so uh that time this while loop will uh so uh that time this while loop will uh keep on executing so what we are doing keep on executing so what we are doing is r is remainder so n is r is remainder so n modulo four modulo four so that will return so that will return the remainder the remainder that should return 4 uh sorry 0 if that should return 4 uh sorry 0 if that is divisible by 4 that is divisible by 4 n is divisible by 4 then what we are n is divisible by 4 then what we are doing we are dividing the value of n so doing we are dividing the value of n so let's say for 16 4 divided by 16 divided let's say for 16 4 divided by 16 divided by 4 it should return 4 by 4 it should return 4 okay so okay so this step is just output so uh yeah so after this n goes to four will get four uh so the value of n is greater than uh one and r is equal to zero then we will continue again so here uh four modulo 4 that should return 0 and uh 4 divided by 4 that should return 1 so now the value is not greater than 1 so that's why we will continue so we'll check what is the value of r after this so our value is 0 and n is greater than 0 so we will return true for that condition else we will return false so that is the solution that i used so this was based on just basic mathematics so the other solution we have is using recursion so here what we are doing uh we have taken and we have taken three conditions okay so these three conditions are terminating conditions for uh the recursive recursion so uh if n equals to 0 will return false if n equals to 1 will return true if n modulo 4 that is any like when we divide a remainder for if we end up if n is divided by 4 the remainder should uh if the remainder is not equal to 0 then we'll return false okay else we will uh if i if either of these conditions are not there then we will uh uh written the power of n by four that means we are just dividing the value of n so let's let's say example of here we started with 16 then uh since n is not equal to zero one and modulo uh four is uh equal to zero so not this condition as well so then we will go here and we will again uh like 16 uh divided by 4 that means 4 this is power of 4 is then again called with value of 4 so then it will again come here uh again it is not uh then four divided by four now the value will be one so n equals to one that means it should right until so any other cases it should return false okay so that is one solution as well so that is uh all for today's problem on the lead code that was uh the power of four okay thank you for having have a nice | 2024-03-24 11:00:19 | 342 | 342. Power of Four | Leetcode Daily Problem | 22-08-2022 |
|
mHyqBRGCSy8 | Hello hello guys welcome back today we are going to solve dynamic programming dynamic programming account south wales prince problem account south wales prince problem statement that you have been in India, the statement that you have been in India, the length of the screen and kept you tied is in length of the screen and kept you tied is in English subscribe which is made by us English subscribe which is made by us should be the previous one. should be the previous one. should be the previous one. one two three 500 appointed subscribe now school so you have two positions here so if the table here at this position on the number is from me or can or can come, can he can like that means can become five Here's how much do you want from me because you will take then here quickly so this position then subscribe for that then good if you want if here this then here we can do a way Here you Here you Here you can see that if we subscribe then for this let's can see that if we subscribe then for this let's go to subscribe husband. go to subscribe husband. First of all we will create a function solve in which we will add water and any character just which is not a pill. I have run a software. The back is The back is The back is that our name is last. Okay, our name is last. If then our name is last. If you have got your answer, then we will turn on was written and we will check whether our Is this or the Is this or the Is this or the value of the last, come to our praiseworthy last, if I am subscribing, value of the last, come to our praiseworthy last, if I am subscribing, then I then I subscribe, subscribe, what do I do here - 121 Jai Hanuman, good feelings, good wishes, inch plus, If If If I copy and paste it, I'm I copy and paste it, I'm looking for A+ Okay, it's done, here's what's going to happen here, here's what's going to happen here, so here I can keep you 15 subscribed, if my subscribed, I can say that you you you can take one and here's this and here's the value of my last key. If I don't have it then how will I use the camera that came to me, if it's done then we'll put it Hain Hain Hain Na Tere Ko Na Tere Ko A Transitional Period You To That A Transitional Period You To That Or Let's Check If I Have If I Have Or Let's Check If I Have If I Have CR From Here If I Have CR From Here If I Have Last Ki Value What Is My I Know That I Last Ki Value What Is My I Know That I Have You To Me To Me Come Have You To Me To Me Come This This This I can keep my darling away that baby If it's my last wedding Drink be the phone If this is what I need I only have one more that I So it is new and then what will I do, I will open my number of passengers, here I will keep the answer, you, let's look at it, let's look at the that it is telling where it is, that it is telling where it is, here we forgot to put plus, let's here we forgot to put plus, let's go. then the correct answer is ok, it then the correct answer is ok, it will go at the time of submission but we will return it to us will go at the time of submission but we will return it to us Simar, the time complexity will be reduced once, to Simar, the time complexity will be reduced once, to forgive you, let's go and get an forgive you, let's go and get an astrologer, the affair happened till the minute, okay. astrologer, the affair happened till the minute, okay. astrologer, the affair happened till the minute, okay. here there here there are ints which will tow their values that are ints which will tow their values that how much has been calculated, how much has been calculated, we earn DP and simply we are here 1431, this is we earn DP and simply we are here 1431, this is mine, I have already calculated on this name and what it is saying, mine, I have already calculated on this name and what it is saying, if calculate if calculate if calculate I do then I will simply get it done till now, this is not my only work, I have the last one here, I will get it done, if it is not so then what will I do, I will store it in my index which was last, I will submit Joint Secretary of IS submits this Cost of this organization Thank you Thank you for | 2024-03-19 15:54:33 | 1,641 | 1641.Count Sorted Vowel Strings|leetcode dp series|leetcode |
|
exgPJlF3ZH4 | uh hey everybody this is larry this is me doing uh day six of the september me doing uh day six of the september lego daily challenge on september lego daily challenge on september uh hit the like button the subscribe uh hit the like button the subscribe button i'm gonna do this live so button i'm gonna do this live so join me on discord in image overlap i join me on discord in image overlap i think i think i did this on a contest or something like did this on a contest or something like that i think the big that i think the big thing to notice is that n is equal to thing to notice is that n is equal to dirty so dirty so so that means that is any rotation just so that means that is any rotation just up down that right up down that right okay so you can do okay so you can do uh proof first i think and just slide uh proof first i think and just slide uh yeah uh yeah can i move both left right can i move both left right how do we choose okay but yeah but i how do we choose okay but yeah but i think it's just think it's just doing that and then uh returning it doing that and then uh returning it uh just put force calculate uh just put force calculate going left end times going right end going left end times going right end times going up and times going times going up and times going down end times and depending on the down end times and depending on the definition of whether we can go up or definition of whether we can go up or left left or sorry uh like combine two directions or sorry uh like combine two directions going diagonal going diagonal um then we might have to do some checks um then we might have to do some checks but um and so key thing to note is that but um and so key thing to note is that moving a moving a uh you know down is equal to moving b up uh you know down is equal to moving b up so you only have to check so you only have to check moving one of these uh yeah so let's moving one of these uh yeah so let's get started uh with our ordered links get started uh with our ordered links the same the same so n is gonna let's just do this then and then now we just have to do four uh zero negative one zero one so that we uh zero negative one zero one so that we get all the get all the com uh possibilities of all the com uh possibilities of all the directions up down left right directions up down left right uh we have to do more than what to do uh we have to do more than what to do more but more but yeah and then for n oops for shift say in range sub n because if you move more than n then your not you know two things will be completely overlapped so or not overlap at all so then you don't need to do that x in range and for y and range n okay so overlap is the both ones so if a okay so overlap is the both ones so if a sub x sub y sub x sub y is equal to one and b sub x i guess we have to do some down checking x plus d x times shift is equal to less than n then oh i guess we should do it and then now we just have to check whether that's p of n x and y is equal to p of n x and y is equal to one then we just increment count and one then we just increment count and then now then now we take the best of you know we take the best of you know pass and then the max of count pass and then the max of count i think that should be it if we have to i think that should be it if we have to go only in one direction go only in one direction uh but let's kind of give it a look uh but let's kind of give it a look okay i wonder yep oh no oh i guess we should have just read the explanation for the first one that's okay so now we have to add in another direction then so let's just call this shift x and then this is shift x this is shift x and this is shift y but of course now we and this is shift y but of course now we need this is a little bit awkward the way this is a little bit awkward the way that i did it but um that i did it but um because now because now [Music] oh yeah actually then this is just um oh yeah actually then this is just um shivered shift y we don't need the dxty shivered shift y we don't need the dxty anymore okay anymore okay i think i changed some stuff and then i i think i changed some stuff and then i forgot forgot um the only thing that we have to um the only thing that we have to actually maybe we do do we yeah because we want to make sure that um let's try again i was going to put into let's try again i was going to put into a test case to just a test case to just test the diagonals for clear i don't test the diagonals for clear i don't need this uh okay need this uh okay so we're running into some technical so we're running into some technical difficulties but okay we messed that up no that looks okay so basically first we go right yeah unless i'm off by one somewhere which is unless i'm off by one somewhere which is possible possible oh uh this should be here oh uh this should be here okay i guess i shifted the things but okay i guess i shifted the things but then then in dentist okay cool uh yeah let's in dentist okay cool uh yeah let's submit it because i'm submit it because i'm relatively okay with this one it may relatively okay with this one it may time out i think that's the only case time out i think that's the only case but but okay so if it doesn't time out but but okay so if it doesn't time out then that's fine then that's fine um so how fast is this right well um so how fast is this right well n to the fourth times some of one so n to the fourth times some of one so and and yeah end to the fourth uh time and and yeah end to the fourth uh time uh over one space so that was pretty uh over one space so that was pretty good but given that n is equal to dirty good but given that n is equal to dirty i wouldn't i wouldn't think that much about it um think that much about it um yeah uh that's all i have for this farm yeah uh that's all i have for this farm uh seems like a straightforward problem i'm gonna take a quick look at the solution maybe there's a better solution but given that n is dirty i don't think i just expected to but let me see if i missed something obvious and then we're gonna we could go over it together uh in that case um now okay shifting count linear transformation i mean okay yeah that's just still into the fourth okay yes we can do convolution but that's ridiculous okay so a lot of these are still into the fourth i don't know if there's a easier solution so yeah um or not easier just quicker solution cool uh yeah let me know what you think about this farm hit the like hit one hit the subscriber and join me on discord and i will see | 2024-03-22 15:09:38 | 835 | 835. Image Overlap - Day 6/30 Leetcode September Challenge |
|
87wxqhwildk | Hello hello one to baat hai gopal number 84 ki replace all widgets end with 84 ki replace all widgets end with characters to pun interesting like this loud characters to pun interesting like this loud english letter this end subscribe and english letter this end subscribe and subscribe - 40000 example2 example2 subscribe - 40000 example2 example2 example2 example2 and this so this so like this is example2 example2 and this so this so like this is my second this that this is It is an English letter and I It is an English letter and I It is an English letter and I got the rotation here from Digit as if I talk to the media otherwise got the rotation here from Digit as if I talk to the media otherwise now as if I will have to subscribe to the first and second now as if I will have to subscribe to the first and second aspect, I aspect, I will shift it to one space, if I do my ghagra then will shift it to one space, if I do my ghagra then subscribe to this and after that I will If I shift in two utensils, then If I shift in two utensils, then If I shift in two utensils, then here I will give this, in the same way, after here I will give this, in the same way, after which scene, what is mine, after C, it is which scene, what is mine, after C, it is mine, okay, then as soon as possible, I will mine, okay, then as soon as possible, I will shift someone in three times, okay, if I shift someone in three times, okay, if I do three children, then this goes do three children, then this goes do three children, then this goes tell you this place of support, similarly, when should I talk about a date at home, then it is a matter of discussion, look at my photo, I will start Asif, then if it is okay, I will do four shifts, then if my mother wants this, then this ghee, then I will now get this wet According to the digits in Ghr Ghr Ghr, I am According to the digits in Ghr Ghr Ghr, I am According to the digits in Ghr Ghr Ghr, I am like a young man running away, like a young man running away, start the setting, first of all, I run the start the setting, first of all, I run the types, last lo, then come Lansdowne s.no, I Plus serial, the I Plus serial, the extra given in it, this is our string, extra given in it, this is our string, its hearty. its hearty. its hearty. people go into this then I will pick each character. Okay, so after picking each actor, what will I do? So to pick each character, I select It will suit every actor, It will suit every actor, It will suit every actor, okay then what do I do? okay then what do I do? Then I check whether that character is our letter i.e. it is our English alphabet or it is our digit and there is one more thing in it that it will be All that is not in our list All that is not in our list that and she is the direct request to the person Udayveer that anything can happen in the same way that StringBuilder Facebook object New that StringBuilder Facebook object New Stress Builder Right now what I do is that Stress Builder Right now what I do is that this is what I have taken this is what I have taken this is what I have taken ghee in English-Vinglish is like if I set the ghee in Maa Ghee with character and digit pin. If it does not work, set the ghee in Maa Ghee with character and digit pin. If it does not work, how did I take quantum herbal and then I will how did I take quantum herbal and then I will make it in 1 minute. You will have to feel the convert salt make it in 1 minute. You will have to feel the convert salt now. now. now. our digit is, we will take that digit, now we have subscribed and subscribed, so now here I subscribed that war subscribe button more this which this alarm set this raised and after that this one which What will Ego do to these two? If he What will Ego do to these two? If he sacrifices one of the subscribe subscribe, then he wants, so now that convert string, so what we do is like subscribe to the subscribe, then set that twice, subscribe, then set that twice, Quantico 297 plus two. Quantico 297 plus two. Quantico 297 plus two. 98 99 Raghava Digital Then we do this our this so we print this song again Which ko Tyag I have printed CO And finally what will I do So finally here which is mine That At night, I At night, I At night, I will get the pattern done here by converting it into a peer vestige and will get the pattern done here by converting it into a peer vestige and said, son, that's why there are two said, son, that's why there are two strings, now what do I do, this is strings, now what do I do, this is our function, now I will our function, now I will have to create a function, I created have to create a function, I created this convert function on the public, convert then I this convert function on the public, convert then I Appointed here and should convert into the house Appointed here and should convert into the house this is our I this I this I am this is our I this I this I am pregnant he subscribe here which does the hair character and then there is an interior which does the hair character and then there is an interior flavor his body this is mine its flavor his body this is mine its flame take it is okay flame take it is okay now what am I now what am I now what am I got a character and I liked it, then what should I do, like I got this, okay, I also added the character which is my character, Monday Digit, this is the question, the Youth Youth Youth i.e. this one which is the first one which is the i.e. this one which is the first one which is the character and once we character and once we do the interior of it, how many liters of 1978 do the interior of it, how many liters of 1978 Edison will be filling the return that our one can Edison will be filling the return that our one can edit and our one gas key will come first, edit and our one gas key will come first, then what will we do that the gardener will change. then what will we do that the gardener will change. then what will we do that the gardener will change. our exciting herbal edifice, now we are this young man 181, so first of all we convert our character - what will happen from 202, which is our forest, this is the If it If it If it happens, what will you do, then 1968, which was converted into war, then you can subscribe here for that number 9828, like, comment, if it happens, subscribe, subscribe Home text is Home text is Home text is given here in this place then we also given here in this place then we also appointed final what do we do which will appointed final what do we do which will become ours then we convert it into strong building is getting damaged strong building is getting damaged access submit Done Runtime Roots Done Runtime Roots Done Runtime Roots Second Step Dahej Central Go Online Second Step Dahej Central Go Online Submission for This Question on | 2024-03-25 10:20:28 | 1,844 | 1844 Replace All Digits with Characters (Leetcode) | Easy Solution |
|
013SWeW2aqM | hey what's up guys this is chung here so this time uh today's daily challenge so this time uh today's daily challenge problem right number problem right number 600 non-negative integers without 600 non-negative integers without consecutive ones consecutive ones uh so this one is pretty tricky one and uh so this one is pretty tricky one and okay so the description is very short so okay so the description is very short so you're given like you're given like positive integers right and return the positive integers right and return the number of integers in the range number of integers in the range from zero to n whose binary from zero to n whose binary representations representations do not contain consecutive ones do not contain consecutive ones right so for example we have n is equal right so for example we have n is equal to five which means we need to five which means we need we are we're searching from n to five we are we're searching from n to five right right and then we have six numbers in total and then we have six numbers in total right the binary right the binary representation is as far a as follows representation is as far a as follows as this and the three is not as this and the three is not a valid one because we have two we have a valid one because we have two we have two consecutive two consecutive we have some consecutive ones right we have some consecutive ones right that's why the answer is 5. and then example 2 this one is pretty basic right 0 and 1 right so we have 2. so here we have 0 1 and one zero right that's from zero to two that's why we have three here okay so the constraint is ten to the power of nine right so it's pretty big you know the first brutal force way is simply we simply just loop through everything from zero to n right and for each of the number we uh we check the bits one by one right and we see if there's any consecutive ones if there is then we just simply skip that all right obviously the time complexity is going to be at n times what times 32 right because i think 10 to the power of 9 is a range of 2 to the power of 32 right that's why and a better one a little bit better one and a better one a little bit better one which which but we'll still tl is that you know we but we'll still tl is that you know we have a bunch of like have a bunch of like bits value right so we check the current bits value right so we check the current value value if it's zero or one if it is zero it if it's zero or one if it is zero it means that you know means that you know the next one can be either zero or one the next one can be either zero or one right or the current one is one then the right or the current one is one then the next one has to be zero next one has to be zero right so that's the the second solution right so that's the the second solution but this one as you but this one as you as you guys can see even though we have as you guys can see even though we have we could have either zero uh one branch we could have either zero uh one branch or two branch but or two branch but the time complexity is still going to be the time complexity is still going to be the 2 to the power of the 2 to the power of length of the the beat string which is length of the the beat string which is 32 32 right so this will still tle basically right so this will still tle basically this one this one so this one what what it improved was so this one what what it improved was that you know we're not that you know we're not basically we're not searching for all basically we're not searching for all the numbers the numbers we're only searching for the numbers we're only searching for the numbers that's doesn't have a consecutive ones that's doesn't have a consecutive ones right but still this one will right but still this one will will also also tle will also also tle um so which means we need a better um so which means we need a better solution right even solution right even even better even faster one even better even faster one um so to do that you know we have to make some observations here you know let's say we have one zero zero one zero zero one right okay so we have a one zero zero okay so we have a one zero zero one zero zero one right then one zero zero one right then right so remember we're searching for right so remember we're searching for anything that's smaller anything that's smaller than than n right the so the first one is one right so the so the first one is one right so which means that which means that any number that's within the range uh any number that's within the range uh from zero from zero if we fix the first number to be zero if we fix the first number to be zero right anything after this right anything after this right so anything right so anything starts with zero but ending could be starts with zero but ending could be anything right anything right basically this is uh something that basically this is uh something that would definitely fall in falls into the would definitely fall in falls into the range range of this end right if we have if we of this end right if we have if we know like in this range in the six know like in this range in the six bit range how many uh bit range how many uh how many like numbers doesn't have a how many like numbers doesn't have a consecutive ones that can greatly consecutive ones that can greatly that can greatly improve our performance that can greatly improve our performance right so right so let's try to solve the sub problem first let's try to solve the sub problem first and then we'll come back here and then we'll come back here okay so now the sub problem is that you okay so now the sub problem is that you know know given like a bit right length of beat right how many length of beat right how many right how many numbers does not have one once right i'll just use the one once for for short so in order to solve this sub problems so in order to solve this sub problems you know you know we need to look at this one here okay we need to look at this one here okay again right so let's say again right so let's say now with sub problems that are given now with sub problems that are given like 6 6 bit like 6 6 bit value right we want we want to know how value right we want we want to know how many many right how many numbers right right how many numbers right with the with the size with the length with the with the size with the length of six digits of six digits six bits right who doesn't have the six bits right who doesn't have the the consecutive ones right so now we can the consecutive ones right so now we can i think we can we can go back to the i think we can we can go back to the second approach you know second approach you know because this one okay obviously you know because this one okay obviously you know the first one can be either zero or one the first one can be either zero or one right so let's say if if the first one right so let's say if if the first one is zero is zero okay so the first scenario is that you okay so the first scenario is that you know the first one know the first one oh sorry the first one we we put is zero oh sorry the first one we we put is zero the second scenario is that we put the the second scenario is that we put the second one second one we put the first one to one right so we put the first one to one right so this is the two scenarios we can use to this is the two scenarios we can use to solve this one recursively okay solve this one recursively okay so if we oh we have a dp right so let's so if we oh we have a dp right so let's define define dpi here right i is the dpi here right i is the basically this is the dpi right of beta basically this is the dpi right of beta the length is i here right so that's the the length is i here right so that's the definition of the dp here definition of the dp here um so we have we have two branches right um so we have we have two branches right basically we can either put this one basically we can either put this one current one to zero or one so if current one to zero or one so if if we put the left most significant if we put the left most significant the the most significant okay so the the the most significant okay so the most significant most significant most most significant bit to zero most most significant bit to zero then it means that you know the next one the next one can either be zero or one right because you know zero zero it doesn't have any consecutive one is fine so what does this mean this so what's this this is like it means that you know the next this one can be anything right so this is what this is dp i minus 1 right because you know if we fix zero then the next one can be either zero or one basically anything after this one which means it's basically it's a sub which means it's basically it's a sub sub problem of dpi minus one sub problem of dpi minus one but if if if this one is one but if if if this one is one it means that the next one has to be it means that the next one has to be zero right and after zero right then the sub problem is what so this one can be anything so now we have now we have two so now we have now we have two fixed bits the remaining is what fixed bits the remaining is what i minus two right so that's how we uh can calculate the uh the dpi here right basically this one is going to be what dp of i minus 1 plus dp of i minor i minus 2 right so that's going to be the the state transition function and this one is what actually is a fibonacci number but the difference is that you know the but the difference is that you know the value of dp0 is is value of dp0 is is instead of instead of zero it's it's instead of instead of zero it's it's gonna be gonna be it's gonna be one and dp of one is gonna it's gonna be one and dp of one is gonna be instead of one is gonna be two right so the base case is what so the base case is like this uh we already talked about we already saw the example dp1 is what dp1 is equals to two right because dp1 is with one digit we have what we have either zero or one that's that's why the answer is the answer is two right and we need for the fibonacci since we have i minus two we need another like we need another uh base case which is dp0 0 is going to be 1. and because for dp3 right because for dp3 right dp3 goes to dp uh dp3 goes to dp uh two plus sorry not not not for dp3 so dp2 here db2 equals to dp uh 1 minus dp0 plus dp0 okay so dp2 we already saw the example dp2 the answer should be three because for dp2 we have zero one and one because for dp2 we have zero one and one zero right that's why we have dp3 zero right that's why we have dp3 and for dp dp one is two and then the and for dp dp one is two and then the leaf dp is zero to one so we have to set leaf dp is zero to one so we have to set cp0 to one cp0 to one actually dp zero to one this doesn't actually dp zero to one this doesn't make any sense make any sense right we simply use this one to make right we simply use this one to make sure we can get a 3 sure we can get a 3 for dp2 right or you can just simply set for dp2 right or you can just simply set dp to e equals to 3. you don't have to dp to e equals to 3. you don't have to worry about this dp0 right i think that's that's the first sub i think that's that's the first sub problem i think this dp0 might problem i think this dp0 might might also be useful uh might also be useful uh let me think yeah i think this one also let me think yeah i think this one also make also also going to be useful but make also also going to be useful but i will i will we'll take a look at it i will i will we'll take a look at it later later but anyway so that's how we but anyway so that's how we calculate the the dp basically given calculate the the dp basically given like a length like a length of a of a bit string of a of a bit string we can use this one to calculate the uh we can use this one to calculate the uh the total number within the total number within who has the same who has this bit value who has the same who has this bit value who has this bit length that who doesn't who has this bit length that who doesn't have have a consecutive ones right okay cool so with that you know let's let's go back to the original problems one zero zero uh so first we see this number uh so first we see this number one here right and then we have this one here right and then we have this what we fix zero what we fix zero so which means that anything that's so which means that anything that's after zero can be can be after zero can be can be calculated right so which means that you calculated right so which means that you know so now know so now if we fix zero so what range we're if we fix zero so what range we're currently recovering this ring zero zero currently recovering this ring zero zero zero zero zero zero zero two zero one one zero zero zero two zero one one one one one one right so what's this one one one one right so what's this value value this is a dp of six this is a dp of six right because we have this six that's right because we have this six that's that's the range we're covering right that's the range we're covering right um okay so that's that but if it's zero right oh sorry so we we covered that right so we covered the uh we covered the dp6 uh with this one but how about one case right so for one zero zero zero zero zero zero two one one one one one one right so this is something we cannot cover basically we cannot use dp dp7 to cover to do to cover this one case right because you know this will also include some values numbers who is greater than this than the original n right that's why we can only uh use this dp when the current one is when the current bit value is one then how about okay so how about the uh did how about this range the range of what the range of of this one which is going to be the one to to this uh zero one zero zero one right so we already covered this scenario at this uh range then how about this range right how how can we calculate this range so what we can do is we simply just keep moving the the bit value to the right side until we see another one okay so let's see this is one right so now let's let's keep going uh go let's go to the next bit the next bit is zero zero means we cannot do anything okay and then the next one is also zero we simply skip that we don't we don't accumulate right because we we we shouldn't uh because this dp will include both zero and one right because that's for everything now the next one is is one right then we can just use dp again why is that because now with one we can use the similar logic here right now we have this one so the range we have is one zero zero zero zero zero zero right to what to one zero zero zero one one one so this is the zero we we fixed right and this is zero bit value we fixed okay so this is the second range this is what dp of what i'm sorry dpl dp of three right i'm sorry dpl dp of three right second one because now we see another second one because now we see another one here that's why we can one here that's why we can uh use a similar strategy uh use a similar strategy as as for the first one right basically as as for the first one right basically we're going to fix this one two we're going to fix this one two to zero and then once we fix this one to to zero and then once we fix this one to zero then the rest zero then the rest can be anything right that's why we have can be anything right that's why we have dp3 here dp3 here okay and then the last one is the last okay and then the last one is the last one is and then we just keep going one is and then we just keep going to zero zero and then until we reach to zero zero and then until we reach here here it's going to be a zero zero so now gonna be a one zero zero zero right to this one zero zero one zero zero one so this is gonna be the right uh yeah i think that's it right so now as you guys can see if we just uh follow this strategy we can cover uh all the out of the ranges right because here you know we're covering the range from the zero zero to this one and also curving from this one to to here right now we're splitting the this big problem into a few sub problems which is dbf6 so that's that's the first scenario and so that's that's the first scenario and how about second one we have a second how about second one we have a second scenario which is the scenario which is the you know currently this one doesn't the you know currently this one doesn't the the original number itself doesn't the original number itself doesn't include any any of the uh include any any of the uh the consecutive one that's why we can the consecutive one that's why we can just keep going until we reach the end just keep going until we reach the end right what if this one has an has right what if this one has an has let's say for example if this one has a let's say for example if this one has a one one then what will what what would be a then what will what what would be a different this one different this one right so now i think the only difference right so now i think the only difference is that you know is that you know so here stays the same this one stays so here stays the same this one stays the same the same and now for the first for the third for and now for the first for the third for the third one now instead of this one the third one now instead of this one we're gonna we're gonna so the one we are covering the range so the one we are covering the range we're covering is going to be we're covering is going to be this right 0 to the 0 this right 0 to the 0 1 1 right so this is going to be the 1 1 right so this is going to be the thing we're covering here thing we're covering here because this is going to be the ones because this is going to be the ones where we're fixing where we're fixing right that's why we have we have two right that's why we have we have two here here right so that's that and now you know can we continue no and why is that because you know so this is the the last number we're covering here right and as you guys can see any number that that is a greater than this current number will result in will result to a consecutive one because you know this one is have one one you know any number if we add one doesn't really matter how many numbers we added here if we add one we'll have like what we'll have like one zero zero one one zero zero right which we have consecutive two uh consecutive ones if we add two we have like this one it's also basically this is the last number that will not have a consecutive ones any number that greater than this then the last number here will result to a consecutive one that's why you know if the current number if the limit this range here has a consecutive one and this is where we should stop we should not continue right cool uh i think that's the basic idea here let's go back to the original problem i think we can try to implement i think we can try to implement implement this problem right implement this problem right so actually the implementation is pretty so actually the implementation is pretty short but the idea behind it is short but the idea behind it is pretty mind-boggling right so like i pretty mind-boggling right so like i said we need said we need like this kind of fibonacci like dp like this kind of fibonacci like dp structure first to help us to structure first to help us to pre-calculate the the number of the number of the values to count often the valid numbers within the who has the same certain like length of the bits right now let's do a dp of um times 20 32 because that's the biggest number we're dealing with right so like i said the dp equals to 1 right and dp 1 equals to 1 right and dp 1 equals to 2. i think db0 equals to 1 equals to 2. i think db0 equals to 1 this also has a meaning of this also has a meaning of it but it's not that obvious right so it but it's not that obvious right so for i for i in range of 2.32 in range of 2.32 here we have dp of what i plus here we have dp of what i plus equals to dp of i minus 1 equals to dp of i minus 1 plus dp of i minus 2. right we have plus dp of i minus 2. right we have already talked about this how already talked about this how why this one is one or two right and why this one is one or two right and then the next one is that we have to then the next one is that we have to check right we have to check the the check right we have to check the the the most significant bit first right the most significant bit first right uh let's do a defined k equals 30 31 uh let's do a defined k equals 30 31 right and then we need a pre right and then we need a pre equals zero because the answer is equal equals zero because the answer is equal to zero and the answer is equal to zero okay so this pre so the pres use to check if we have if we need to stop right in case we in case the original n has a like two consecutive numbers right something like this right so basically we need to maintain like a pre but pre-like digits right in case we have two consecutive one that's when we need to stop right so basically we have y of k is greater equal to than zero okay i'll explain why we need that equal to zero here if so basically we check if the current digits is like it's one right of this k and then it does not equal to zero right it means it is one then we do answer dot uh plot dp of k right so why we have k and dpk here right again right so let's say we have 1 0 0 1 0 1 right so we're checking this this bit right so what is the bit here so we have k is what is five right so if we do a one left most five we have what we have one zero zero zero zero zero right that's how we set d set this one and the five is what the five is actually exactly the the count of the the remaining digits right the remaining bits except for the current one which is exactly five that's why we use dpk and then right like i said right okay and then right like i said right okay and then else right else and then else right else uh we simply just do nothing right and uh we simply just do nothing right and then we do a k minus one then we do a k minus one and then we return the answer something and then we return the answer something we return the x right but here like i we return the x right but here like i said we also need to take care of this said we also need to take care of this consecutive one case which means that consecutive one case which means that you know you know if the pre is oh it's equal also equal if the pre is oh it's equal also equal to one that's when we'll simply return to one that's when we'll simply return the answer the answer okay and then we set the pre equals to okay and then we set the pre equals to one here one here and then the pre will be zero right and then the pre will be zero right because that's the simple that's the s because that's the simple that's the s to update the previous value okay to update the previous value okay and then so the first thing is that why and then so the first thing is that why we do a we do a k equals to zero here how about if we do k equals to zero here how about if we do a k a k greater than zero if we don't consider greater than zero if we don't consider that so what's going to happen that so what's going to happen right so what will happen is that you right so what will happen is that you know know for the for the very basic case let's for the for the very basic case let's see if the see if the n is equal to 5 which is one zero one n is equal to 5 which is one zero one right uh if it's one zero one so it will be what it will be first it's going to be a zero uh zero zero to zero one one right which is a dp of three right dp of three if we stop at k is equal to one if we stop at k is equal to one instead of zero that means that we would instead of zero that means that we would there's no way we can check the last bit right basically the k equals to zero is to check the last bit if the last bit is is one we also need to cover that we also need to consider that because you know if the last bit is one it means that we have we have one zero zero needs to cover right that's why we need to do a equal okay and then the last one is that okay and then the last one is that when we return we need to return the when we return we need to return the answer plus one answer plus one so this one is to so this one is to include include include include and itself right and itself right because everything we have been doing because everything we have been doing this while loop here this while loop here is we're only considering the the what is we're only considering the the what we only we only can we're only uh including we're only considering the anything that's smaller than n right we're not we're not uh checking the the number and itself right because you know for again for one zero one right so the first range we're covering is what we're covering is this from zero zero one zero zero zero two zero one one right and what under the second the last the last uh range where curving is what is from zero to one zero zero it's not to one zero to one zero zero it's not to one zero one so i know this part is a little bit tricky i think it's tricky here it's not it's not one uh one zero one because we're fixing this one to be zero because we're fixing this one to be zero and then there's nothing there's nothing and then there's nothing there's nothing else else here right because you know if we have a here right because you know if we have a uh you have one one one zero uh you have one one one zero right and this is then when we right and this is then when we covered when we try to fix this one to covered when we try to fix this one to be zero and then that's when we be zero and then that's when we we have we will have one zero zero we have we will have one zero zero to one zero one right this is the one we to one zero one right this is the one we will cover will cover the the one the one zero one case but the the one the one zero one case but for this one for this one actually since we're fixing this zero in actually since we're fixing this zero in this case this case so similarly since this is one we're so similarly since this is one we're fixing zero here fixing zero here which means that you know the range which means that you know the range we're covering is one zero zero to one we're covering is one zero zero to one zero zero for zero zero for the last one not one zero one right so the last one not one zero one right so this is this is a the difference this is this is a the difference okay so which means that you know this okay so which means that you know this while loop will never cover while loop will never cover the n itself and that's why you know we we need to we need to do a answer class one because you know when we when there's a concept when there's a consecutive uh ones uh in this and itself obviously we should not include this n number into the final answer that's why you know whenever this if check is true we simply return the answer but if nothing if there's never a consecutive once in this end we will we need to include um yeah i think that's everything you know i'm not sure for the for this last part if you guys uh clear about that because you know i the the way we are doing this thing is uh oh and that's why when i uh oh and that's why when i it says that you know dp0 do does have it says that you know dp0 do does have other meaning it's it's other meaning it's it's it's this case which is for the one for it's this case which is for the one for this case for the zero this case for the zero for the zero zero case one zero zero to for the zero zero case one zero zero to one zero zero this is also another one zero zero this is also another another uh valid number right that's why another uh valid number right that's why you know dp0 is 1 you know dp0 is 1 because we are covering 1 number in this because we are covering 1 number in this case case which is the 1 0 0 itself which is the 1 0 0 itself right because it means that you know the right because it means that you know the dv 0 means that basically dv 0 means that basically by fixing the current uh after fixing by fixing the current uh after fixing the current one to be zero there's not the current one to be zero there's not nothing there's nothing on the on the nothing there's nothing on the on the right on the right side for example this right on the right side for example this one right so basically one right so basically if you fix the current one to be zero if you fix the current one to be zero there will be five digits on the there will be five digits on the on on the right side that's why we have on on the right side that's why we have this dp5 so db0 means that you know this dp5 so db0 means that you know after fixing the current one to be zero after fixing the current one to be zero there's zero there's zero digits on the right side which means digits on the right side which means that you know this dp0 will that you know this dp0 will we will be representing this this uh one we will be representing this this uh one zero zero zero zero itself right that's the meaning of db itself right that's the meaning of db zero i think and yeah so that's it i know it's a pretty long explanation but i hope you guys uh can understand what i'm trying to explain here and as you guys can see so now the time complexity is what simply o of 32 to the max right because the k is like this and this this is also like a constant right oh we haven't even run it no so let let's run it so what's the point if it didn't work right um yeah um yeah i think that's it right i mean just to i think that's it right i mean just to recap so basically this to solve this recap so basically this to solve this problem you know we have problem you know we have we need to make we need to solve two sub we need to make we need to solve two sub sub problems sub problems the first one is that given like the first one is that given like given like a a length of the digits given like a a length of the digits how many values numbers how many numbers how many values numbers how many numbers within uh who has that size within uh who has that size who has this eighth length of digits who has this eighth length of digits are valid numbers and we use this one are valid numbers and we use this one this this fibonacci like uh kind of dp transition fibonacci like uh kind of dp transition function to calculate it right function to calculate it right and so that's it and the second one is and so that's it and the second one is that you know that you know this given this dp here right how can we this given this dp here right how can we utilize this gpu to help us to find utilize this gpu to help us to find all the valid numbers within the using all the valid numbers within the using the given numbers the given numbers right so the way we're doing is that you right so the way we're doing is that you know know we only use that this fibonacci dp array we only use that this fibonacci dp array whenever we see a one whenever we see a one because otherwise you know we don't know because otherwise you know we don't know because with a one that's because with a one that's that's when we can fix this one to zero that's when we can fix this one to zero and we can just and we can just safely check all the remaining digits on safely check all the remaining digits on the on the right side the on the right side right and then under further for divided right and then under further for divided range range which is which is greater than this which is which is greater than this counter range right we simply just keep counter range right we simply just keep go moving forward until we see a next go moving forward until we see a next one right one right and then we just keep doing it and then we just keep doing it accumulating that and the last thing is accumulating that and the last thing is that that how can we deal with the this how can we deal with the this consecutive ones in the original and consecutive ones in the original and right we simply stop there right we simply stop there cool i think that's it for this problem cool i think that's it for this problem and and thank you for watching this video guys thank you for watching this video guys and stay tuned see you guys soon and stay tuned see you guys soon bye | 2024-03-20 12:14:27 | 600 | LeetCode 600. Non-negative Integers without Consecutive Ones |
|
wciOFao3IFU | hello everyone in this video we're going to be looking at the solution to delete to be looking at the solution to delete code problem possible by partition so in code problem possible by partition so in this problem were given a set of n this problem were given a set of n people so we have n people and we want people so we have n people and we want to split everyone into two groups of any to split everyone into two groups of any size so there's any size now size so there's any size now each person may dislike some other each person may dislike some other person so they should not go in the same person so they should not go in the same group so it is like if I were given a 2d group so it is like if I were given a 2d array or very two people if they're in array or very two people if they're in the same array meaning that they dislike the same array meaning that they dislike each other so if a or B are in the same each other so if a or B are in the same array then a or b cannot be in the same array then a or b cannot be in the same group they dislike each other and so we group they dislike each other and so we only have to partition everyone into two only have to partition everyone into two groups we can look at this example here groups we can look at this example here so we have 1 2 1 3 2 4 so 1 doesn't like so we have 1 2 1 3 2 4 so 1 doesn't like to so 1 & 2 are separate one doesn't to so 1 & 2 are separate one doesn't like 3 so 1 & 3 are separate two doesn't like 3 so 1 & 3 are separate two doesn't like both 2 & 4 are separate so cook 1 like both 2 & 4 are separate so cook 1 can't be this group 2 can be this so can't be this group 2 can be this so very simple problem as they only have to very simple problem as they only have to separate them into two groups so we'll separate them into two groups so we'll just look at this example and see some just look at this example and see some approaches so this is the dislike array approaches so this is the dislike array meaning that the people who dislike each meaning that the people who dislike each other this it should be Java yeah so other this it should be Java yeah so these are the people who dislike each these are the people who dislike each other no my what I thought earlier was other no my what I thought earlier was what we can do is 1 & 2 dislike each what we can do is 1 & 2 dislike each other so first of all we can have two other so first of all we can have two groups so we can have took 1 and we can groups so we can have took 1 and we can have group two so when I do dislike each have group two so when I do dislike each other so obviously they have to be in other so obviously they have to be in the they don't get to be in the same the they don't get to be in the same group they have to be in different cook group they have to be in different cook so one can be here two can be helped now so one can be here two can be helped now I come to one and three and so one is I come to one and three and so one is already in a group and she doesn't want already in a group and she doesn't want to be in the same group as one so three to be in the same group as one so three terms here no 4 and 2 2 is already in terms here no 4 and 2 2 is already in the group and who doesn't want to be the the group and who doesn't want to be the same with h2so4 culture so what I same with h2so4 culture so what I thought for it is you can just manually thought for it is you can just manually run a loop and if two person are not in run a loop and if two person are not in any group and then we can just put them any group and then we can just put them in two different groups and if one of in two different groups and if one of them means it is in a group then we can them means it is in a group then we can put the other into a different group but put the other into a different group but this approach won't work and I'll tell this approach won't work and I'll tell you why you why so suppose I have 1 comma 2 and I have 3 so suppose I have 1 comma 2 and I have 3 comma 4 and I have 1 comma 3 so what I comma 4 and I have 1 comma 3 so what I do have to be in a different group so 1 do have to be in a different group so 1 is here 2 is here is here 2 is here no three and four have to interdiction no three and four have to interdiction group so I put three here because no group so I put three here because no condition and four I can put here for I condition and four I can put here for I can put here but two and four cannot be can put here but two and four cannot be in the same group so our answer will be in the same group so our answer will be false but it's the answer false no the false but it's the answer false no the answer is true how is that so what we answer is true how is that so what we can do is one into don't want to be in can do is one into don't want to be in the same to fine I can do one I to one the same to fine I can do one I to one and three don't want to be in the same and three don't want to be in the same group so I came to two and three and two group so I came to two and three and two infer don't want to be in the same group infer don't want to be in the same group so I can do one at four so this is you so I can do one at four so this is you can see a possible answer for this given can see a possible answer for this given test case point to one thing to put one test case point to one thing to put one forward together and to 3i together and forward together and to 3i together and nobody who doesn't want to be in the nobody who doesn't want to be in the other group in with someone else is not other group in with someone else is not so this is a sandy condition satisfied so this is a sandy condition satisfied this is a condition satisfied example so this is a condition satisfied example so what I mean is that we have to look at what I mean is that we have to look at all of the cases at once for example one all of the cases at once for example one may have one comma two and then we have may have one comma two and then we have three called two comma three and then we three called two comma three and then we have five comma six and then later on have five comma six and then later on one can also have later on one can also one can also have later on one can also have one comma 5 later on one can also have one comma 5 later on one can also have one over seven so my point is when have one over seven so my point is when we are searching for one then all the we are searching for one then all the person point doesn't like have we have person point doesn't like have we have to take care of them at work two two to take care of them at work two two five and seven and then one all of the five and seven and then one all of the person who do doesn't like we have to person who do doesn't like we have to take care of the met one so one three take care of the met one so one three and like that so this is nothing but an and like that so this is nothing but an adjacency list representation of a graph adjacency list representation of a graph we will be solving this by considering we will be solving this by considering people or people as nodes on the graph people or people as nodes on the graph so idea is we'll come across a node or a so idea is we'll come across a node or a person so we'll have two groups again person so we'll have two groups again good one and two that will be the same good one and two that will be the same in our approach so we have Group one and in our approach so we have Group one and group two now if you're going to do is group two now if you're going to do is we come across a node we're going to use we come across a node we're going to use BFS so we take that node and we put it BFS so we take that node and we put it in a queue and after putting it in I in a queue and after putting it in I putting it in the queue so I have one putting it in the queue so I have one two three four five so I take one and I two three four five so I take one and I put it in my queue now all the person put it in my queue now all the person one doesn't like I I now I take one out one doesn't like I I now I take one out of the queue and put in and take in all of the queue and put in and take in all the person whom one doesn't like and the person whom one doesn't like and afterwards I just whatever those persons afterwards I just whatever those persons are their group will be are their group will be potato cut so I'll just make all of potato cut so I'll just make all of their groups the opposite of one then their groups the opposite of one then afterwards if one or the person he afterwards if one or the person he doesn't like are in the same book then doesn't like are in the same book then the answer is false otherwise answer the answer is false otherwise answer will be true so to make motions as I will be true so to make motions as I code it so like I said we'll be doing code it so like I said we'll be doing this with cloth using PFS and the idea this with cloth using PFS and the idea for that was that we had to find all of for that was that we had to find all of the person that one person doesn't like the person that one person doesn't like and that can be used as adjacency list and that can be used as adjacency list representation so for the list representation so for the list representation we'll just use a list of representation we'll just use a list of list popping teacher and I will just list popping teacher and I will just call it drop because they're having a call it drop because they're having a graph so it would be a new ArrayList you graph so it would be a new ArrayList you are a list of for size and plus one are a list of for size and plus one because people are from 1 to n naught 0 because people are from 1 to n naught 0 to n minus 1 so the size will be n plus to n minus 1 so the size will be n plus 1 and then we'll have in or we'll have a 1 and then we'll have in or we'll have a group so any so group of I will tell the group so any so group of I will tell the group that the person is in so coop will group that the person is in so coop will be new in and it'll also have the place be new in and it'll also have the place what and initially all the people will what and initially all the people will be in group 0 which is meaning that we be in group 0 which is meaning that we haven't put them in any code so cook 1 haven't put them in any code so cook 1 and go now we just need to add the bus and go now we just need to add the bus we just have to make that a since a list we just have to make that a since a list so first we'll just create so it doesn't so first we'll just create so it doesn't go it doesn't give null point exception go it doesn't give null point exception so I less than equal to and I plus plus so I less than equal to and I plus plus and then grow it add new ArrayList Oh in and then grow it add new ArrayList Oh in teacher so this is just filling up with teacher so this is just filling up with empty array list so it doesn't give the empty array list so it doesn't give the important exception when we actually add important exception when we actually add something in our list no simple thing something in our list no simple thing less than equal to N or dislikes dot less than equal to N or dislikes dot length less than equal to just like so I pressed us so the disk what we are doing is so dislikes of zero doesn't like dislikes dislikes of I of zero doesn't like dislikes of by your phone so in the edges in the adjacency list of dislikes of I of zero will put in this lecture for your one and with one will put in zero simple so meaning that in curve dot get his lights of I of zero thought dislikes of your phone so zero doesn't dislike zero doesn't like one one doesn't like zero so both of them be will be in there adjacent silat will be in each other 30 sensible so just copy it and in one we have zero so when doesn't like zero zero doesn't like one and we have a will have a queue like we usually have for or do you p2p we usually have for to India fest and we'll just name it queue so it'll be a new linked list oh he just between we need to write that so now we can just to work on the people so Oh let's then n I so we're going to look at each people then we're going to look at all the people they taste like and we'll put everyone in some group so first of all if the person is not in any group only then we need to worry otherwise we don't need to bother so a group of I meaning is equal to zero meaning that person is not in any way so I'll just write it down group of group is equal to zero groups are I'll just write down good are one and to cook if group is zero then meaning turn out in any group so if group of I is zero then what we need to do is we need to add that person to our Q so Q third over I so now we've oh like edit this guy to our Q and then we'll look at all the people he dislikes so first we need to make his group as one so we need to group group him so I'll just give him one randomly then I read it and to avoid it to make you know while not you thought empty so we'll keep on doing it while queue is not empty meaning all the purses are not so white thought queue is empty what I'm going to do is I'm going to say in U is equal to Q dot foo so whatever person is on the front of the queue I'll take him out and I'll deal with his dislikes so his dislikes are in the list da thought I taught you the graph of that gate of U is the list of all the people it is light so what I'm going to do with the people he dislikes is that I'm going to put them into opposite group as he is if he's in one I'll put them into it is into I'll put them in one and then I'll do if they're already not in any group so group of T is equal to zero they're not in any group then if group of U is equal to one then we'll put the person he ate he hates in two and you're facing two then we'll put the person he hates input then we add this person then we add this person to earth queue and then we'll deal with his dislikes so cute Auto for K so why am i considering this group of PI to PI so am i considering the opposite of group of you when I already put is one here so for the first person group his group will be one for the other people cook may not be one that's why we have to check and put the person he dislikes in the opposite group of U is 1 then we'll put the person he hates and do if there isn't cook dude and we'll put the person he hates finally we'll add the person to work you know here comes the main thing so if group of G is zero and there's one no condition suppose that J the person you hate is already network so if he's already in a group and he isn't that thing repels you then our condition will not be satisfied because they're already in the same row so cooper-cooper U is equal to of U is equal to poop of J so according to every if they're in the same group then we can no longer like have the people in to cooks so it is fine a condition soup then we return for so we take out you we deal with all the person he hates and if the person he hates is already in his book then we turn first because it is not possible to divide the person in that case otherwise all well and good we can divide the person because there is no problem which like counters our condition so otherwise you can simply return true and that's all that should try to the neck compiler I will return statement very dear I returned it okay and so the idea of BFS that we got okay and so the idea of BFS that we got was from the thing that each person will was from the thing that each person will have it dislikes list so that somewhere have it dislikes list so that somewhere reminds us that this person that this reminds us that this person that this can be solved using adjacency list or can be solved using adjacency list or this have has a plane of adjacency lists this have has a plane of adjacency lists in it and using BFS in one node we go to in it and using BFS in one node we go to all or that all the neighbors of one all or that all the neighbors of one node so here using it using BFS from one node so here using it using BFS from one person we go to all the person need it's person we go to all the person need it's light and little bit them so that's why light and little bit them so that's why we use BFS so that's all thank you we use BFS so that's all thank you and one more thing guys do subscribe to and one more thing guys do subscribe to my channel I plan to do a lot more lead my channel I plan to do a lot more lead code problems and hopefully I'll be code problems and hopefully I'll be doing all the mainly foot problems doing all the mainly foot problems interview problems so stay tuned thank interview problems so stay tuned thank you | 2024-03-22 17:38:10 | 886 | LeetCode 886 Possible Bipartition |
|
ADUqvpxwkSM | hey hey everybody this is larry this is me going with q4 of the weekly contest me going with q4 of the weekly contest 257. 257. yikes uh gcd sort of an array so yeah so yikes uh gcd sort of an array so yeah so basically basically this is a tricky problem hit the like this is a tricky problem hit the like button hit the subscribe button join me button hit the subscribe button join me on discord let me know what you think on discord let me know what you think about this problem especially if you'd about this problem especially if you'd like to talk about this and other like to talk about this and other problems come hang out come come make me problems come hang out come come make me feel good feel good in like in like conversation i don't know that sounds conversation i don't know that sounds like i'm trying to brag or something but like i'm trying to brag or something but yeah so this one yeah so this one i actually got it relatively quickly i i actually got it relatively quickly i got in about 13 minutes and if you watch got in about 13 minutes and if you watch me solve it live during the video the me solve it live during the video the live uh coverage i actually talk way too live uh coverage i actually talk way too much i probably could have if i just much i probably could have if i just focus on coding i probably could have focus on coding i probably could have done it much quicker but i don't know done it much quicker but i don't know maybe today i'm just in a talk of maybe today i'm just in a talk of talkative mood and i didn't care about talkative mood and i didn't care about it that much but yeah um it that much but yeah um yeah i didn't get a wrong answer so yeah i didn't get a wrong answer so that's good i wasn't even confident that's good i wasn't even confident anymore because i've been very sloppy anymore because i've been very sloppy but the idea here is this right but the idea here is this right so basically you can sort two numbers if so basically you can sort two numbers if there's a common divisor so i'm going to there's a common divisor so i'm going to break it into two components one is break it into two components one is um um yeah yeah we'll do about the primes part but we'll do about the primes part but basically basically let's say pretend that you you know i let's say pretend that you you know i know that n is 10 is uh know that n is 10 is uh it's 3 times 10 to the fourth it's 3 times 10 to the fourth but but but uh let's yeah because n is 10 3 times 10 to the fourth we cannot do this in n squared time because it takes too long but let's pretend that we can do this in n squared time um that i'm going to explain an n squared algorithm real quick right um and and this is maybe intuitive if you think about it i don't know what the sorted thing is okay i could copy and paste um but yeah and [Music] yeah i'll go over a couple of cases but the idea is that if you have an n square solution um then you can look at every number every pairs of number and kind of see if they have a common divider right if they have a common divisor then you can sort between them and in this case for example um 5 you could start with 10 and in a way because um because of this um what's it called they call flipping uh swapping um in this case swapping is transitive right and what do i mean by that what i mean by that if a is if you can swap a with b that means that and you can swap a uh okay let me say it again let me write it down if if you can swap a with b and swap b with c then you can swap a with c right i don't know my computer is a little bit slow um and the reason why this is the case um even though you cannot do it directly to be correctly to be true right so for example let's say you have a b c and you want to sort it backwards um and and you cannot you know you cannot swap directly a with c you can just kind of use you know uh you could kind of use b as an intermediate variable for example this is one possibility sort a with b and then you sort c with b and then you sort c with a right or sorry b with a so you can definitely do it so so you know it takes a couple of operations but because we have infinite number of operations this transitive probability holds right so that means that now if we have an n squared algorithm is that well um now we just kind of go through the way to kind of do a depth first search on every possible pair right um and what i mean by that by that first search is that you may imagine that we have um you know now instead of a and swapping b then now a is connected to b there's an edge from a to b and there's an edge from b to c and that means that those three numbers are interchangeable of each other right and then now you can do a connected component and what does that mean for you well in this case at the very end um there are a couple of scenarios right which means that if everything if the final sorted numbers um if you look at them one by one if they're in the same connected component then you can get them together right in um yeah in this case actually i think every number is sorted but um okay they don't provide a good example for you but for example you can imagine uh something like 2 4 and then we add some odd numbers 3 and then we add some odd numbers 3 9 9 uh 27 right uh 27 right um okay maybe a little bit not sorted so let's just say i don't know nine again right doesn't matter right um so the idea here is that we're building out these components because okay we know that we can swap this number with this number right so this is one component so one component is 4 2 and then another component is 9 327 right because you can swap them with each other and then now if we given the sorted um uh answer the question is okay so can this 4 get to this 2 well the 4 can get to this 2 if they're in the same component right um and you can do this in n square um of course it's time small but the definite search or breadth first search will be n squared right um yeah the nine can you get to the three the answer is yes okay that's good the 2 can you get to the 4 yes because they're in the same group same for 3 and 27 right so then the answer is true for this one but keep in mind that in this case the 4 and the 2 do not interact in any way oh sorry the 4 and the 2 interact with each other but they're totally independent from the 3 9 and 27 right so that's that's one thing and then the second thing um so that's that's the n square algorithm and that's too slow right so then the question is you know how do you make it faster well the thing that i talked about is um connected components and that should ring a doorbell and the doorbell is use union find and basically the idea behind union fine is that okay for every number this is not a good example but for every number but for every number we try to figure out um yeah uh so for every number you can still do it n square but but the linear time way is to break it down to these components right um because okay for example and this is kind of awkward because these are all powers or whatever so let's actually take this number real quick right so what does this mean this means right so what does this mean this means that 10 is equal to 2 times 5. what does that 10 is equal to 2 times 5. what does this mean that means that that this number is in the same group with every um every multiple and and every multiple every multiple of five of five right so so now right but what does this also means right this means that 10 now is a group between two and five because of what we said earlier with a swap b equals b swap c and so forth um so the translated property holds and that means that you know now given the 10 even if you have a two and a five oops uh let's just say we have two and then uh a multiple of 25 and four say um right or even five times say nine so 45 right um so 45 and 10 they have at least five as a multiple together or so i divide it together so that means that you can swap 45 of the 10 and then because 10 uh is also as a divisor with four that means that four now can swap at 45 due to the transit properly right but so what does this you know now i'm going to say it another way this means that now any number with a divisor of 2 is now swappable with any oops number with a divisor of five i think i missed typo because i can't see what i'm typing because my computer is slow for some reason my chrome is slow okay actually i mostly typed it okay so swappable is one p i think it's a two piece i don't know actually whatever um so yeah so that's basically the union fine way of doing it is that is that now you you know now you in this way you so now you define these what they call your equivalent set um so now you have um multiples of two and as in one set and multiples of five in another set and now you put them together right um so that's basically the union find solution um and now yeah the thing that i thought about though is that this may still not so this is fast um you could do this in linear time the problem is that you have to factor every number in the number list and that may be too slow if you're not slick enough right um so the way that i did it um because you can do some math um so the biggest number is 10 to the fifth so the square root of that times 3 30 000 is equal to some number i forget what it is but it it feels too too big is this fast enough in python um right so i wasn't sure so i did one more optimization um and the optimization is using the sieve um i always forget how to say the sieve of errors aristotle's did i spell that right nope ah close mr t uh maybe i misspelled this right uh i misspelled this incorrectly toast yeah okay ever told denise okay toast yeah okay ever told denise okay well but yeah so i would google this but well but yeah so i would google this but basically that's the way that i did it basically that's the way that i did it um i'll go over my code right now um i'll go over my code right now um pretending that union fine is a um pretending that union fine is a constant i know that there's there's um constant i know that there's there's um there's some inverse anchorman stuff i there's some inverse anchorman stuff i know i know but i'm just going to call know i know but i'm just going to call it constant for now because it's easier it constant for now because it's easier to say so i have these uh to say so i have these uh this union fine code this union fine code and then now i have so i set up the and then now i have so i set up the primes this is the sif basically i just primes this is the sif basically i just go up go up the up to the max and matches the the up to the max and matches the biggest number into the array but biggest number into the array but basically i calculate all the primes basically i calculate all the primes uh factors for this number so for uh factors for this number so for the and this is just to say if i'm not the and this is just to say if i'm not going over the sip that much but this is going over the sip that much but this is actually actually max let's say m is equal to max this max let's say m is equal to max this actually wants him m log m time the actually wants him m log m time the proof is a little bit tricky please do proof is a little bit tricky please do some research uh but yeah but basically some research uh but yeah but basically here now that we have all the primes here now that we have all the primes together reunion them together reunion them uh with the first one because that's uh with the first one because that's just how you group them they're is just how you group them they're is transitive right so now we're transitive right so now we're um um reunion all the primes together given a reunion all the primes together given a number and then at the very end this is number and then at the very end this is just to see if they're in the same just to see if they're in the same component which is that okay if the u component which is that okay if the u find of the find of the the number so s nums is the sorted the number so s nums is the sorted number so we have to sort it so it has number so we have to sort it so it has to be on log n i suppose actually but to be on log n i suppose actually but but uh but yeah but uh but yeah but but but basically we look at if but basically we look at if if the number in unnumbs if the group is if the number in unnumbs if the group is the same as the or if it's not the same the same as the or if it's not the same then that means that it's forced then that means that it's forced otherwise if it's true for every one of otherwise if it's true for every one of them then it's true um so yeah so this them then it's true um so yeah so this algorithm like i said because you have algorithm like i said because you have to sort first it's going to be n log n to sort first it's going to be n log n plus m log m plus m log m where m is the max number um yeah in where m is the max number um yeah in terms of space this is all of terms of space this is all of uh i think m log m as well because of uh i think m log m as well because of this thing because we this thing because we we uh yeah and also we uh yeah and also uh of n plus this for space um because uh of n plus this for space um because this can this can contain a lot of devices i think so i contain a lot of devices i think so i think it's m log m i could be wrong um think it's m log m i could be wrong um on that particular one um yeah and on that particular one um yeah and there's also a lot more space for there's also a lot more space for for you know union fine and stuff like for you know union fine and stuff like that but yeah but that's all i have for that but yeah but that's all i have for this one this one uh let me know what you think i think if uh let me know what you think i think if you get this part um you can actually you get this part um you can actually implement most of this part the civ is implement most of this part the civ is also a little bit tricky as well but also a little bit tricky as well but that's fine i did so i actually did that's fine i did so i actually did everything from scratch i didn't do any everything from scratch i didn't do any copy pasting i know that people like to copy pasting i know that people like to cop to have this template and even this cop to have this template and even this is template so maybe you can save a is template so maybe you can save a couple of minutes but um couple of minutes but um but yeah i did this in about 13 minutes but yeah i did this in about 13 minutes without it so you should be able without it so you should be able to not need it is my point uh even if it to not need it is my point uh even if it takes longer obviously but yeah uh takes longer obviously but yeah uh that's all i have for this one let me that's all i have for this one let me add add let me know what you think and you can let me know what you think and you can watch me solve it live during the watch me solve it live during the contest next and i talked a lot during contest next and i talked a lot during the contest so the contest so so hopefully maybe that's helpful i so hopefully maybe that's helpful i don't know why i talk so much anyway don't know why i talk so much anyway let's actually see how this one's let's actually see how this one's looking looking uh 47 people have gotten it so if i do uh 47 people have gotten it so if i do this now maybe i'll get in a good time this now maybe i'll get in a good time but yikes though that was a rough but yikes though that was a rough problem for me okay but i just need to problem for me okay but i just need to write it down actually if that wrote it write it down actually if that wrote it down was pretty easy but i just kind of down was pretty easy but i just kind of convinced myself i didn't need to okay convinced myself i didn't need to okay let's actually do this one any number of let's actually do this one any number of times swap i and j if they're times swap i and j if they're if they are um much mccoy if they are um much mccoy uh if they're uh if they're mutually something uh i'm pointing out mutually something uh i'm pointing out numbers right now numbers right now um um return true it's possible to start return true it's possible to start numbers in non-decreasing numbers in non-decreasing order okay so basically this is going to order okay so basically this is going to be some sort of union fine perhaps be some sort of union fine perhaps and this kind of thing so yeah so yeah um how do we figure though is i think it's gonna be some sort of union fine but how do we figure it out if if they have a common denominator uh or a common common divisor then that's good so that well that means that we can do them this is 10 to the fifth so common dividers are not that big but um that means that for every we can group okay so we just factorize every number and then we group all of them and if we are able to group i mean but that's not always true i mean but that's not always true because in that you can have if the because in that you can have if the input is already like sorted like this input is already like sorted like this it doesn't matter that they're not it doesn't matter that they're not grouped grouped um so then the question is okay i see so then now it's just union fine and basically for every um we just look at the group of the result and the thing okay fine um so sorted away or sorted answer maybe so that answer is equal to a copy of this it's called s numbers for sorted numbers it's called s numbers for sorted numbers um and then now we factor every number and okay so then union fine okay union union okay union fine of x is equal to okay union fine of x is equal to return return parent of x parent of x and then here and then here if parent of uh is just not equal to x if parent of uh is just not equal to x our current of x is equally fine for our current of x is equally fine for that pound of x okay that pound of x okay and then here we just have pound as you and then here we just have pound as you go to this thing go to this thing it's not even a maybe called group i it's not even a maybe called group i forget what i use for union fine let's forget what i use for union fine let's call it g call it g and that's called parent whatever and that's called parent whatever i know what that means and that's good i know what that means and that's good enough for me enough for me yeah yes you got a u fine of a u b is yeah yes you got a u fine of a u b is equal to minus b equal to minus b uh u uh u count of u a is equal to u b count of u a is equal to u b and then that's pretty much it so then and then that's pretty much it so then now now we group them together all the numbers for x and nums we factorize factorize how many numbers are the 30 three times ten i always forget i three times ten i always forget i read this as sometimes three thousand read this as sometimes three thousand and i get in trouble so okay thirty and i get in trouble so okay thirty thousand square root of thousand square root of ten to the f uh what is square root of ten to the f uh what is square root of ten to the fifth um square root of that i'm just using a calculator don't worry that's 316 so 316 times 30 000 is 9 million yikes uh i'm trying to think how i would do i need to use the sif i'm worried do i need to use the sif i'm worried about uh just doing this straight up but about uh just doing this straight up but then this goes only up to 10 to the then this goes only up to 10 to the fifth so we can use the surf um yeah okay yeah okay uh let's see what uh nums uh let's try to surf okay okay um the good thing is that we can able to um the good thing is that we can able to test this pretty quickly test this pretty quickly so that's good um okay what does that mean i have to remember how to do the presif but uh but i should be able to do this just 45 minutes and i think my idea is right my implementation has just been terrible because i don't practice enough but okay if length of times is equal to zero that means that this is prime so prime sub x well this is a prime so then okay just do this and then we do for y in range of and then we do for y in range of uh let's just do it this way uh let's just do it this way well y is less than or less than or well y is less than or less than or equal to max equal to max we add this by x y dot append x yeah okay so then now let's return yeah okay so then now let's return something let's see if this should be something let's see if this should be fast enough i'm gonna run it for this fast enough i'm gonna run it for this but what i really want is something like but what i really want is something like um 10 to the fifth do i have enough zeros but it's hard to tell oh okay this looks fast enough so i'm happy okay this looks fast enough so i'm happy about that about that um um let's print it out real quick to see let's print it out real quick to see that we do real work that we do real work because otherwise because otherwise okay so we don't do real work so that okay so we don't do real work so that makes it easier for it to be fast makes it easier for it to be fast huh oh okay that's why which is a quick loop uh okay okay so this is fast okay so this is fast enough maybe we could enough maybe we could if it gets nasty we could mess it up two if it gets nasty we could mess it up two three four five six seven eight nine ten three four five six seven eight nine ten 10 11 12. everything looks okay so far 10 11 12. everything looks okay so far and looks and it runs pretty quickly so and looks and it runs pretty quickly so okay so then now we we have to look up okay so then now we we have to look up table for the sieve then now we just table for the sieve then now we just have to go for the x have to go for the x um okay for um okay for x and nums x and nums uh so what does this mean when we see a number let's also get the index when we see a number it means that we want to group all the all the things together so okay for y in primes sub x we want to union union uh y with primes of x of zero um so this should be a union we'll start actually from the first number so then we skip the first number um [Music] yeah maybe this should be good so then let's look at parents oh um how do i want to write this okay if x is not in parent then parents of x is equal to x and then we return uh okay maybe that's good enough actually um okay it doesn't so then now it's what is what what am i printing that means that 2 and five are in the same group which is what we want two five and three are the same group so that's also what we want is that a true answer five cannot be five cannot be i thought we put five in the same uh i thought we put five in the same uh thing okay so maybe that's not quite true let's see let's put out what i'm doing here print out union okay so it's union two and five and then okay so it's union two and five and then three and five why three and five why am i looking at the white case oh i'm am i looking at the white case oh i'm looking at the one case that's why okay looking at the one case that's why okay sorry so okay so i'm doing it right sorry so okay so i'm doing it right um and then here it doesn't because two um and then here it doesn't because two and three unions but then the five and three unions but then the five doesn't okay doesn't okay so then now so then now we we are mostly done are mostly done all we have to do is just all we have to do is just um yeah okay actually we don't even need because this is just to include the because this is just to include the unions and then now we look at unions and then now we look at for for [Music] [Music] for a b and sip of s for a b and sip of s nums and s nums uh if nums and s nums uh if union find of a uh that's not true what am i doing [Music] if the union fine of the prime sub a of zero basically get the group that it is in and we union and everything so everything should be together if this is not equal to that of b doing that um then we return oops we return force otherwise they're in the same group so i think i talked too much to be honest i think i talked too much to be honest but okay so this looks okay i mean i'm a but okay so this looks okay i mean i'm a little bit early but let's give it a little bit early but let's give it a submit and then we get a wrong answer submit and then we get a wrong answer we'll debug it um we'll debug it um cool i mean i was actually pretty happy cool i mean i was actually pretty happy about this one about this one hey uh yeah thanks for watching hey uh yeah thanks for watching everybody hit the like button hit the everybody hit the like button hit the subscribe button join me on discord and subscribe button join me on discord and come hang out with me um yeah stay good come hang out with me um yeah stay good stay healthy to help you have a great stay healthy to help you have a great rest of the week hope you had a great rest of the week hope you had a great contest uh anyway see you later and contest uh anyway see you later and yeah good mental health bye bye | 2024-03-25 12:17:33 | 1,998 | 1998. GCD Sort of an Array (Leetcode Hard) |
|
uD1yXki53KA | hey guys in this video I'm going to talk about a lead code problem the problem's about a lead code problem the problem's name is Max number of K some pairs so in name is Max number of K some pairs so in this question we given an integer ARR this question we given an integer ARR nums and also integer variable K in one nums and also integer variable K in one operation we have to pick two numbers operation we have to pick two numbers from the array whose sum is equal to K from the array whose sum is equal to K and remove them from the array and we and remove them from the array and we have to return the maximum number of have to return the maximum number of operations you can perform on the array operations you can perform on the array so we have to remove all the pairs which so we have to remove all the pairs which are having some equal to five so let's are having some equal to five so let's take this example here you can see the take this example here you can see the sum is five you have to pick two sum is five you have to pick two elements I'm picking one and I'm picking elements I'm picking one and I'm picking four 1 + 4 is equal to 5 it is equal to four 1 + 4 is equal to 5 it is equal to sum so I remove these two elements from sum so I remove these two elements from the array so the array will become 2A 3 the array so the array will become 2A 3 now now again I pick this element and now now again I pick this element and pick this element 2 + 3 is equal to five pick this element 2 + 3 is equal to five so I remove these two elements from the so I remove these two elements from the array and the array will become empty array and the array will become empty since I perform two removal operations I since I perform two removal operations I return two as the output so talking return two as the output so talking about the first approach let's take the about the first approach let's take the input array so I've taken the same input array so I've taken the same example as example one so in this example as example one so in this approach I'm going to use a map to count approach I'm going to use a map to count the elements and their number of occurrences so this approach is similar to the first problem lead code called two sum I leave a link to that video in the description box below where I'm going to use a map find out if the complement of the current number is present inside the map or not so let's declare the map so first let's start with i is equal to 0 we check if that element is present inside the map no it's not so add it and set its frequency to 1 now the complement of this element 1 so 1 + something is equal to 5 right that is our Target 1 + x = 5 so this will become x = 5 - 1 5 is equal to K right so this is equal to Kus 1 if we subtract the current element from K we will get our expected value which is four so we have to search if this x is present inside the map so X is four in this case so we have to check if four is present inside the map check if four is present inside the map no four is not present as of now now go for the next element now I is pointing at two check if complement of 2 5 - 2 equal to 3 check if three is present inside the map no it's not present so add that element and set it frequency to one now go to the next element complement of 3 is 5 - 3 is = 2 check if 2 is present inside the map yes it is present so there is no need to add this element into the map but we have to remove this element which is its complement from the map so I remove this element from the map and increment the count to one because we found a pair remove it now in the next iteration I is equal to 3 complement of 4 is 1 because 5 - 4 is equal to one check if one is present inside the map yes one is present so we increment count and we remove the complement from the map and in the next iteration I is pointing at four which is out of bounds so we come out of the for Loop and return whatever is present inside count count is equal to two denoting the two operations so two is the output now let's take a look at the code for this approach so let's start by creating a map let's take the second example now numis 31 3 43 and K is equal to 6 I created the map where key is going to be the ARR and the value is going to be the frequency of that R element I create a variable count which is initially zero so I is pointing at zero now we start with i pointing at Z now we find the complement of that 6 - 3 is equal to 3 check if 3 is present inside the map No 3 is not present so this statement will be executed I add three and get its current count current count is zero default value 0 will be executed I'm adding + one so it will become one next iteration I is pointing at index 1 we find the complement of that element 6 - 1 is equal to five check if five is present inside the map no it's not present so again this statement will be executed add that element one and set it frequency to 1 in the next iteration I is pointing at index 2 find the complement 6 - 3 is equal to 3 check if 3 is present inside the map as key yes three is present so remove that from the map and increment count to one and then removing that elements next move I further calculate the compliment 6 - 4 = 2 check if 2 is present no it's not present so add it into the map so 4A 1 will be added into the map move I further complement of three is three check if three is present inside the map it was present but it has been removed for this pair so there is no three present so add the current element three into the map and set it frequency to one and in the next iteration I will go out of bounds and will reach the end of the for Loop and we come out of the for Loop so whatever is present inside count count is having the value one so one is returned as the output so the time complexity of this approach is O of N and the space complexity is also o of n because we're using a map where n stands for the length of the Namar now let's take a look at the approach which we use where the time complexity is going to be of n log because we're going to sort the array in ascending order and the space complexity is going to be constant space so this is a better approach where we improve the space and we sacrifice the time complexity but for this specific question o of n login will run faster than o of n because of the small input size let us go to the method two so I've taken the example two to explain the method two so this is the nums array so in this question as I said we are going to sort the array in ascending order so after sorting the array will look like this so the value of K is equal to 6 and now in this approach I'm going to use two pointers so left will be pointing at the starting of the array and right will be pointing at the end of the array we add the elements at left and right left 1 + 4 is equal to 5 since 5 is less than 6 we need to increase the target value to increase the target value we have to increase the sum to increase the sum we have to move the left pointer because if you decrease the right pointer the overall sum will decrease so because the array is sorted in ascending order the larger values are placed at the end where right will have access to so if you remove the larger it will either not change the total sum or for sure decrease the sum that is why we try to move further and increase the sum now left will be moved further and we find the sum again sum is 3 + 4 is equal to 7 compare it with K 7 is greater than 6 so we increase the value now now we have to decrease the sum compared to the Target six so as I said to decrease the sum decrease the right pointer Now find the the sum again 3 + 3 is equal 6 so 6 is equal to K so we increment the count and since both so since both left and right have been used to form the output we move both the pointers so left will move further and right will be decremented so this action will perform until left is less than right so this y Loop will run until left is less than right as both are not same we end our iteration and finally count which is having the value one will be returned as the output outside the while loop so one is the output now let's implement the steps in a Java program so let's take the same example as example one now we having the input array so let's sort the array in ascending order after sorting the array also the array will remain the same because it's already sorted in ascending order that's fine now let's declare the two arrays now let's declare the two pointers left and right left will be pointing at zero index and right will be pointing at array length minus one that is last index and declared a variable count now we use the while loop where left is less than right left is zero and right is three yes it will go inside now let's find the sum nums of left plus nums of right so 1 + 4 is equal to 5 it is equal to K so increment count this part will be executed and since we used both left and right in our forming the sum move both the pointers so left will move further and right will be decremented by one now let's repeat the same steps find the sum 2 + 3 is equal to 5 again both are matching so increment count move both the pointers now this condition will fail because right is equal to one and left is equal to two since this condition is failing 2 is less than one this condition fails so we come out of the Y Loop and return whatever is present inside count count has two so two will be returned as the output which is matching here so the time complexity of this approach is and login because we sorting the are in ascending order and then using a while loop to iterate from left to right the space complexity is of one because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video | 2024-03-20 11:12:19 | 1,679 | Leetcode | 1679. Max Number of K-Sum Pairs | Medium | Java Solution [2 Methods] |
|
jD8M5q0OkUM | hey hey everybody this is larry and this is now me doing the bonus question uh is now me doing the bonus question uh hit the like button hit the subscribe hit the like button hit the subscribe button join me on discord let me know button join me on discord let me know what you think about you know today's what you think about you know today's bonus question i'm gonna do a hard today bonus question i'm gonna do a hard today uh um okay fine let's actually just let uh um okay fine let's actually just let the rng choose because i don't know the rng choose because i don't know if you're doing it at home with me then if you're doing it at home with me then you know i you know i want it to be fair want it to be fair so let let's see okay so let let's see okay subscribe to to do about to find it subscribe to to do about to find it one that does not require subscription one that does not require subscription because i'm cheap and i haven't paid for because i'm cheap and i haven't paid for it maybe one day i'll pay for it anyway it maybe one day i'll pay for it anyway okay so we're getting a yeezy day so 914 okay so we're getting a yeezy day so 914 x of a kind in a deck of cards okay in a x of a kind in a deck of cards okay in a deck of cards each card is a number or deck of cards each card is a number or individual on it we aren't true if you individual on it we aren't true if you can choose x over two or x is greater can choose x over two or x is greater than two such that as possible to split than two such that as possible to split the deck into one or more group of cards the deck into one or more group of cards where each group where each group has exactly x cards and you two cards has exactly x cards and you two cards have the same number okay have the same number okay so basically the idea is so basically the idea is actually it's kind of very similar to actually it's kind of very similar to the problem that we did today because the problem that we did today because it's kind of like okay so we have you it's kind of like okay so we have you know let's say we put them or in a counter right then now what well then now the values um if we set it it's um length of this is equal to one i think that's pretty much it right unless i misunderstood this part because they have all the partition this is actually wrong because x has to be greater than or equal to two so but this is like mostly right but it's not right because of that like i could try it um and if this was a contest i would be very sad if i submit this i think that's why i've been kind of i don't know but yeah as you can see i returned true because there's no uh um the number of counts is always whatever but yeah i mean you can this becomes a little bit awkward now but um do set is equal to all this stuff and then one and max of s is equal is greater than one right so i think that should be good but you know it's not as cool as a one-liner but we'll see if that works maybe i missed oh oh huh i really did miss understand this huh i really did miss understand this one one i guess in this i guess in this okay fine i don't know if i okay fine i don't know if i misunderstood it but i did miss an edge misunderstood it but i did miss an edge case that's kind of uh case that's kind of uh um because the idea here is that do i wow for easy i'm not gonna lie i underestimated this because it was easy i was like usually maybe i'll try to you know do something cute and clever uh even then there's a thing but the idea here is that basically you can split into groups of two by squaring this into two um and then the next idea would be to just you know take the min and then you know put it into multiples but then that's when you get into issues of you know gcd and stuff like that right so and that's pretty much the idea i think is that we now do the gcd of all these things um and then just making sure that uh i've always forget where the gcd and i guess we can do that um i always forget whether gcd and python um um gcd and python allows me to do a list gcd and python allows me to do a list but i guess not but i guess not i feel like to some language where you i feel like to some language where you can take it as a list but can take it as a list but uh uh how do i do it um i think there's a how do i do it um i think there's a reduced function or something like that reduced function or something like that or map function now it's a reduce or map function now it's a reduce function right uh gcd reduce python function right uh gcd reduce python something like that so you could do it something like that so you could do it in one line or something in one line or something but uh okay so you could do something but uh okay so you could do something like like reduce because the idea is that if you just because the idea is that if you just naively tick naively tick uh where is my other uh where is my other yeah we naively do yeah we naively do one one one one two two two two that's fine but then we two two two two that's fine but then we have like have like um let's say four and six right four um let's say four and six right four numbers one three four one two three numbers one three four one two three four five six the answer should be true four five six the answer should be true because then now you have two as a because then now you have two as a number which is the gcd portion but number which is the gcd portion but you know you know ooh what did i get i will force but this ooh what did i get i will force but this should be true should be true huh huh did i miss did i miss this this hmm hmm because the gcd should be between four because the gcd should be between four and six and six and that should be and that should be unless i misunderstood it unless i misunderstood it [Music] [Music] um and that should be two i mean maybe um and that should be two i mean maybe my representation is wrong oh no no my representation is wrong oh no no whoops this one is query not white um whoops this one is query not white um i don't know why i had still have this i don't know why i had still have this i think i i think i i think i just left it in for some i think i just left it in for some reason because reason because i don't know left it in from before and i don't know left it in from before and forgot to take it out because i was forgot to take it out because i was trying to fix the second part but uh trying to fix the second part but uh okay so let's try it again let's give it okay so let's try it again let's give it a submit a submit i mean it's not a hard problem but it's i mean it's not a hard problem but it's definitely definitely a little bit harder than yeezy and i a little bit harder than yeezy and i definitely just underestimated if i definitely just underestimated if i really thought about it maybe it would really thought about it maybe it would be okay um be okay um i wonder if i wonder if yeah i don't know that you can do it in yeah i don't know that you can do it in a better way a better way um um in the sense that i wonder if there's in the sense that i wonder if there's like some brute force way i can do it like some brute force way i can do it like you can't really test for one two like you can't really test for one two three dot dot dot three dot dot dot uh maybe you could take the smallest uh maybe you could take the smallest number and then before like you know put number and then before like you know put force on on the factors or something but force on on the factors or something but that's a little bit awkward uh let's that's a little bit awkward uh let's take a look we could really is this fast take a look we could really is this fast enough enough why is this fast enough why is this fast enough and it's real plugin i guess if you and it's real plugin i guess if you already okay i guess if you have already already okay i guess if you have already have the counter then maybe you could do have the counter then maybe you could do it it i'm not sure though oh i guess it was 10 i'm not sure though oh i guess it was 10 to the fourth for some reason i thought to the fourth for some reason i thought it was 10 to the fifth it was 10 to the fifth um like okay um like okay i guess you can before so okay so i i guess you can before so okay so i guess if you can move first then guess if you can move first then then maybe this is a yeezy but i did the then maybe this is a yeezy but i did the gc doa gc doa um um [Music] [Music] but this is n squared though oh i don't know that's really awkward because i've that's definitely too slow to be on square yeah i don't know i mean this is a little i mean i'm not saying it's hard i'm just saying it's a little bit hard for and easy definitely a lot of it or not a lot of edge cases but definitely at least like you have to really think about your edge cases at least you know or one edge case or one or two edge cases about how you want to think about it but you have to think about it um yeah anyway this is gonna be linear time linear space um then your space to do this thing you don't even really need to set i kind of just kept it in there because i it wouldn't change the answer because that's the way how gcd works but yeah and i kind of left the other thing in there just because i wasn't looking at it and i forgot about it but yeah uh that's pretty much all i have for this one this is easy but um it's marked as easy but clearly uh very easy to get wrong but that's what i have so let me know what you think stay good stay healthy to get mental health i'll see y'all tomorrow see you | 2024-03-25 10:52:54 | 914 | 914. X of a Kind in a Deck of Cards (Leetcode Easy) |
|
MLCq8rN2EWI | hello everyone so in this video let us talk about one more problem from lead talk about one more problem from lead code the problem name is number of one code the problem name is number of one bits so this problem is from the top bits so this problem is from the top interview question series i've been interview question series i've been working on from lead code so if you working on from lead code so if you haven't checked it out i have the link haven't checked it out i have the link of that delays in the description of of that delays in the description of this video so go check it out okay so i this video so go check it out okay so i will making out a lot of top interview will making out a lot of top interview questions from lead code the problem questions from lead code the problem name is number of one fit so the problem name is number of one fit so the problem statement goes like this that you are statement goes like this that you are given a number n given a number n and that number is of that type like it and that number is of that type like it is a bit representation of zeros and is a bit representation of zeros and ones ones okay now you just have to tell that how okay now you just have to tell that how many bits are set okay so bit set up by many bits are set okay so bit set up by if any terms you means that how many if any terms you means that how many bits are set so every number consists of bits are set so every number consists of bits zeros and ones that is its binary bits zeros and ones that is its binary representation now if we want to like representation now if we want to like tell how many number of ones are there tell how many number of ones are there in the binary representation of any in the binary representation of any number that means that you just asking number that means that you just asking how many bits are set in that particular how many bits are set in that particular number in binary representation that's number in binary representation that's what the problem statement asks you to what the problem statement asks you to do now they can multiple ways to do this do now they can multiple ways to do this problem but the very standard way uh to problem but the very standard way uh to do this problem is by using the left shift operator so this operator now how this operator works i'll give you one uh like overview of how it works so this operator is called a left shift because it is like pointing towards left and this is the right shift now left shift operator shifts the number that we are inputting by this particular amount what we are putting on the right side i'll just give you so one left shift let's say two times this this represent means that we are writing down this in by this is not 100 this is in binary binary representation binary representation so this is equivalent to this now you so this is equivalent to this now you might be asking how so this means that might be asking how so this means that you put a one and then you put a one and then so let's say that you put one so let's say that you put one and then left shift it two times so when and then left shift it two times so when you left shear fit obviously there can you left shear fit obviously there can not be any number or like any bit other not be any number or like any bit other than one so because you are not putting than one so because you are not putting any bit so it zero will come eventually any bit so it zero will come eventually because you are like shifting it so you because you are like shifting it so you can just assume that there's some window can just assume that there's some window and there is one on like uh on the left and there is one on like uh on the left corner of like the right corner on the corner of like the right corner on the window and then you shift this person so window and then you shift this person so like there are different seats like there are different seats so use like shift this one two sides and so use like shift this one two sides and this is like a long seat like this this this is like a long seat like this this is a very long uh you can say window but is a very long uh you can say window but you can only see till this point you can only see till this point and everything is zero like everything and everything is zero like everything is empty is empty you can see that everything is empty now you can see that everything is empty now if you tell this person one that okay if you tell this person one that okay left shift two positions so this person left shift two positions so this person will go to this and this so when this will go to this and this so when this person comes to this obviously person comes to this obviously this hole will come to this actually this hole will come to this actually this this will not shift because these this this will not shift because these are zeros only but still you can see are zeros only but still you can see that they're like this shift like this that they're like this shift like this uh zeros will also shift because uh zeros will also shift because everything will shift by two positions everything will shift by two positions so it will be one zero zero and that is so it will be one zero zero and that is this question so one left shift five this question so one left shift five times means that one and then five z one times means that one and then five z one two three four five two three four five zeros so okay so that is one and one zeros so okay so that is one and one left shift zero zero one left zero which left shift zero zero one left zero which means that it is only one nothing is means that it is only one nothing is shifted so that is how you can check shifted so that is how you can check that like what does this left shift that like what does this left shift operator do now let us talk about how we operator do now let us talk about how we can like uh can like uh check how many number of ones are there check how many number of ones are there in any bit representation in any bit representation so let's say that you have a number that so let's say that you have a number that says like this 1 1 0 1 0 0 1 says like this 1 1 0 1 0 0 1 and you want to check how many so this and you want to check how many so this is the binary representation of some is the binary representation of some number binary representation and you just have to check that how many like bits are there that are set that are equal to one so what you can do here is you can take one as a number you have okay and if you know what is and operator so what you can do is that you first do an end of this and everything is zero what is this value turns out to be this turns out to be one because when you do end of two bits and if they both are set like both are one then only it will become one so this is zero this is zero this is zero zero zero zero so this is also and when it turns out to be one which means that this is some number like this is not zero okay let us do one more thing you will understand more now if you do so if you do this now so all i'm doing is end operation then all of them will turns out to be zero because this will be zero this is zero zero zero zero zero zero because the like this bit will only be the only one when both of these are one like so both of them are not one so it will be zero so what i'm doing here is that i am doing an and operator of the number i have with a number with one at a particular position and everything is zero so one is moving from left to right at every like every position so one will be like so this particular bit is set and everything is zero then this bit is set and everything is zero then this bit is set and everything is zero and at any position if when two bits are matched then this particular value will become one and it will be all zero but this number it will be non-zero so because there is a bit so obviously this is the bit this number will not be zero but if you have done an and operation of this number in which this bit is set and everything is not set then obviously it will be zero because this will be zero zero zero everything will be zero so this number will be zero and thus what you can observe here is that you can use the left shift operator to do a for loop in such a way that you have one then you left shift one by one position it will become one zero when you left shift one by two position it will become one zero zero so you will keep on shifting one by left shifting it some number of times so that you got one at every position and whatever number you have you will do and with that number and it and if at any position this one that i'm sending and this one will coincide it will make the number of the end of this number and this number non-zero and whenever they become non-zero which means that this particular bit is set so we are just doing this for loop and because the number of times is 30 like this uh by anything is of 32 so we'll do a 32 times for loop and every time we just do an end update of the particle number we have and the number that we are forming by left shift this one by n times and then like i had time and then whatever the answer will be like by doing an annotation of both of these numbers if it turns out to be non-zero which means that the particular bit i am on is non-zero so if like it is it is set sorry if it it is set we just have to count on how many bits are set that's the overall logic from this problem so that's a very small problem that total we're just doing a volume from 0 to 32 we're doing so 1 is left shifted as you can see i times so it will be 0 times so 1 time 2 time and so on so it will be like one zero then one one zero zero one zero zero zero and so on so we are doing an operation of this and n and if this number turns out to be non zero because if it is non zero then only this if condition will work if it is zero then this if condition would turn should be false this condition will not meet you can also tell that if this value is not zero then also you will increment your total and in the end you just return the total energy so that's the total number of bits that are sent that's all logic and code i have been posting a lot of videos on binary representation and binary problems also so you can check out all of those problems as well but this problem is from the top interview questions from it so thank you for this video till the end i will see you next | 2024-03-21 14:28:21 | 191 | 191. Number of 1 Bits | LEETCODE EASY | BITS MANIPULATION |
|
p4kkT3OqJtI | hey guys welcome back to my channel and i'm back again with another really i'm back again with another really interesting coding interview question interesting coding interview question video this time guys we are going to video this time guys we are going to solve question number 965 univalued solve question number 965 univalued binary tree before i start with the binary tree before i start with the video guys just want to ask you that if video guys just want to ask you that if you have not yet subscribed to my you have not yet subscribed to my channel channel then please do subscribe and hit the then please do subscribe and hit the bell icon for future notifications or bell icon for future notifications or more such programming and coding related more such programming and coding related videos let's get started now so videos let's get started now so basically guys the problem statement is basically guys the problem statement is pretty straightforward we want to find pretty straightforward we want to find out if this binary tree is univalued or out if this binary tree is univalued or not by uni values we mean that if all not by uni values we mean that if all the nodes are having the same value then the nodes are having the same value then it's a univalued tree so in this example it's a univalued tree so in this example you can see that all the values of the you can see that all the values of the tree are one so the output is true tree are one so the output is true because it is unique value because it is unique value in uh in the second example you can see in uh in the second example you can see that that the leaf node is having value five the leaf node is having value five whereas all the other nodes are having whereas all the other nodes are having value two so the output is false value two so the output is false constraints are that the number of nodes constraints are that the number of nodes in the 3 is in the range of 1 to 100 and in the 3 is in the range of 1 to 100 and the value goes from 0 to 100 okay the value goes from 0 to 100 okay so let's jump to the solution guys so let's jump to the solution guys so just looking at this problem guys so just looking at this problem guys there are two ways to solve this problem there are two ways to solve this problem one is the depth first search one is the depth first search and one is the breadth first search and one is the breadth first search so just to explain a bit uh if you're so just to explain a bit uh if you're using depth first search then basically using depth first search then basically you are taking one node you are taking one node and then and then you are checking its value and then you you are checking its value and then you are going to its left node and then you are going to its left node and then you are going to that left nodes left node are going to that left nodes left node so basically you cover the height of the so basically you cover the height of the tree first and in that particular order tree first and in that particular order you just check if all the nodes are you just check if all the nodes are having the same value having the same value and then you go to the next node or to and then you go to the next node or to the next branch right the next branch right but if you are doing breadth first but if you are doing breadth first search then basically you are doing sort search then basically you are doing sort of a level order reversal that means of a level order reversal that means first you check all the nodes on one first you check all the nodes on one level so in this case there is only one level so in this case there is only one node on root level that is root node node on root level that is root node then you check all the nodes on the then you check all the nodes on the second level and then you check all the second level and then you check all the nodes on the third level okay so nodes on the third level okay so basically it's a pretty straightforward basically it's a pretty straightforward implementation of depth first such implementation of depth first such object first search but in this case we object first search but in this case we are going to solve this problem with the are going to solve this problem with the uh recursive depth first search approach uh recursive depth first search approach so let's see how we can do that so so let's see how we can do that so basically guys we are going to take this basically guys we are going to take this is universal tree function and we are is universal tree function and we are going to call this function only going to call this function only recursively to see if this tree is a recursively to see if this tree is a unique value tree unique value tree now let me just remove bfs here we are now let me just remove bfs here we are just going to use dfs just going to use dfs so the first thing in a recursive so the first thing in a recursive function is the base condition right so function is the base condition right so my base condition is that if the root my base condition is that if the root value is not equal to null so if the value is not equal to null so if the root is equally equational then root is equally equational then basically it is a unique value tree basically it is a unique value tree right right so if the root is not equal to null then so if the root is not equal to null then we have to do for the things otherwise we have to do for the things otherwise we simply return true we simply return true now let's go inside this if condition now let's go inside this if condition now we are going to check our other base now we are going to check our other base conditions the first base condition is conditions the first base condition is that if root dot left is not equal to that if root dot left is not equal to null null and and root dot left dot val root dot left dot val is is not equals to root dot val not equals to root dot val so basically if so basically if left node is present and its value is left node is present and its value is not equals to the root value then you not equals to the root value then you can simply return false here because it can simply return false here because it means that it's not a means that it's not a unique value tree and the same thing i unique value tree and the same thing i am going to do with the am going to do with the right node so if the right node is also right node so if the right node is also present and its value is not equals to present and its value is not equals to the root node then also i will return the root node then also i will return false and finally once this check is false and finally once this check is done that means that for the root node done that means that for the root node both left and right child are having the both left and right child are having the same value then we go into their same value then we go into their own sub trees that means we'll go and own sub trees that means we'll go and evaluate the left sub tree and right sub evaluate the left sub tree and right sub subtree subtree so after evaluating those we are going so after evaluating those we are going to return to return and of and of the left subtree result and the left subtree result and right subtree result so if both left right subtree result so if both left subtree and right substrate result is subtree and right substrate result is true that means both of them are unique true that means both of them are unique value trees it means that our value trees it means that our main parent tree is also univalued and main parent tree is also univalued and finally this will return true so let's finally this will return true so let's run this quote guys let's see if this run this quote guys let's see if this works for our problem statement works for our problem statement and there you go guys you can see that and there you go guys you can see that it's accepted it's accepted and uh and uh yes so there you go it's accepted yes so there you go it's accepted not talking about the time complexity not talking about the time complexity guys so the time complexity for this guys so the time complexity for this particular solution is going to be order particular solution is going to be order of n of n because you can see because you can see that we are checking each and every node that we are checking each and every node and assuming there are n nodes in our and assuming there are n nodes in our tree the time complexity is going to be tree the time complexity is going to be order of n order of n the space complexity is going to be the space complexity is going to be order of h order of h where h is the height of the subtree where h is the height of the subtree uh basically guys you can see that this uh basically guys you can see that this particular function is being called for particular function is being called for the left sub tree and for the right the left sub tree and for the right surface at one particular time surface at one particular time if we are going through the entire depth if we are going through the entire depth so let's see if i am going to the entire so let's see if i am going to the entire depth of this this subtree then at one depth of this this subtree then at one point of time i will be holding the point of time i will be holding the entire height of the tree in my entire height of the tree in my recursive stack so that's why the recursive stack so that's why the order of the space complexity of the order of the space complexity of the order of h you can also call it as order order of h you can also call it as order of n if you are using bigger notation of n if you are using bigger notation okay okay uh if you talk about dfs guys so dfs uh if you talk about dfs guys so dfs sorry if you are talking about breadth sorry if you are talking about breadth first search first search if you if you use level order reversal if you if you use level order reversal to solve this problem then also the time to solve this problem then also the time complexity is going to be order of n complexity is going to be order of n um um the time complexity is going to be order the time complexity is going to be order of n of n and the space complexity in that case and the space complexity in that case can be order of n can be order of n because you are using uh because you are using uh a level right so you will be having a q a level right so you will be having a q and in one queue at one point of time and in one queue at one point of time there is a possibility that you are there is a possibility that you are holding n nodes okay holding n nodes okay so uh we won't be implementing bfs so uh we won't be implementing bfs solution in this because i have solution in this because i have implemented bfs in a lot of previous implemented bfs in a lot of previous videos so you can go and check those out videos so you can go and check those out i can uh put those links in the i can uh put those links in the description below the link of the coding description below the link of the coding interview playlist interview playlist so that was the solution guys i hope you so that was the solution guys i hope you guys like the solution and i hope it guys like the solution and i hope it worked for you as well if it did help worked for you as well if it did help you guys then do not forget to like this you guys then do not forget to like this video and share this video with your video and share this video with your friends and do subscribe to my channel friends and do subscribe to my channel guys hit the bell icon for future guys hit the bell icon for future notifications if you have any questions notifications if you have any questions comments suggestions better solutions comments suggestions better solutions please post them in the comment section please post them in the comment section below so that everybody can benefit from below so that everybody can benefit from them and i would be happy to address them and i would be happy to address them as well thank you so much for them as well thank you so much for watching guys i'll see you guys in the watching guys i'll see you guys in the next video until then take care and bye | 2024-03-25 14:03:18 | 965 | Univalued Binary Tree | Leetcode 965 | Amazon Google Facebook interview question |
|
nPsQVD4rthY | guys babybear4812 coming at you one more time today with time today with another oldie but a goodie it's the gas another oldie but a goodie it's the gas station problem problem number one three station problem problem number one three four uh this question is currently as of four uh this question is currently as of uh fall 2020 being asked by amazon uh fall 2020 being asked by amazon google google microsoft facebook uber apple bloomberg microsoft facebook uber apple bloomberg so a lot of the big guns have picked it so a lot of the big guns have picked it up up it's an old one but it's it's clearly it's an old one but it's it's clearly still being asked and i thought it was still being asked and i thought it was it was interesting because like most of it was interesting because like most of the problems that i choose the problems that i choose there's a um there's kind of an there's a um there's kind of an intuitive way maybe you want to dive intuitive way maybe you want to dive into into your first time around but that's not your first time around but that's not always the optimal solution there's one always the optimal solution there's one little neat trick to get you right over little neat trick to get you right over the line the line and so that's why i wanted to cover it and so that's why i wanted to cover it if you haven't tried already pause the if you haven't tried already pause the video give it a shot video give it a shot come on back you all know the drill by come on back you all know the drill by now so now so this question essentially says their n this question essentially says their n gas stations along a circular route gas stations along a circular route where the amount of gas at a station i where the amount of gas at a station i is gas of i is gas of i we also have a car okay so we have a car we also have a car okay so we have a car that's got an unlimited gas tank and it that's got an unlimited gas tank and it costs costs cost of i of gas to travel from station cost of i of gas to travel from station i i to its next station i plus one okay and to its next station i plus one okay and we start a journey with an empty tank we start a journey with an empty tank at one of the stations and so it says we at one of the stations and so it says we start with an empty tank start with an empty tank at one of the gas stations it doesn't at one of the gas stations it doesn't tell us which one the question will tell us which one the question will essentially be essentially be tell me where we can start all right if tell me where we can start all right if we can at all we can at all it says return the starting gas stations it says return the starting gas stations index if you can travel around the index if you can travel around the circuit circuit once in the clockwise direction um once in the clockwise direction um otherwise negative one otherwise negative one they tell us also there's a solution they tell us also there's a solution that's unique uh that's unique uh both inputs are are non-empty they have both inputs are are non-empty they have the same length and each element in the the same length and each element in the input array is a non-negative integer so input array is a non-negative integer so we don't have to do any error checking we don't have to do any error checking we're given legitimate inputs now we're given legitimate inputs now we're told that this is a a circular we're told that this is a a circular road if you will with with certain gas road if you will with with certain gas stations and we need to see if we can do stations and we need to see if we can do one one one full loop around clockwise right i one full loop around clockwise right i think i said clockwise uh yes in the clockwise direction so if you were to start out i'll call it gas station or gas station zero gas station zero you can fill up one unit of gas from you can then drive three three unit three we'll call it miles it's called you know gallons and miles so you can do you know one gallon of gas and then uh drive three miles but rather that's a stupid analogy that's not what it's saying at all you get one unit of gas it costs you three units of gas to leave and get to the next place all right sorry my brain's all fried today um if you can fill up one unit of gas but it would cost you three units of gas to get to the next place well that's not gonna work out also well because you know you're you're gonna lose you're gonna lose all your gas before you get there um basically what their point is is that the the output here in this question would be three and the reason it'll be three is as follows if we started at index three right here we could fill up four units of gas all right and it would cost us one to make it over all right so let me maybe i could i could write these down and walk through the example where we're given one two and we're given three four five one two and we're given three four five one two all right all right three four five one three four five one two okay so this is gas two okay so this is gas this is cost and if we start right here this is cost and if we start right here right we're going to have essentially right we're going to have essentially we're going to gain four units of gas we're going to gain four units of gas so we're going to say plus four and then so we're going to say plus four and then we're gonna lose one getting to the next we're gonna lose one getting to the next town town okay so now we're at we've netted three okay so now we're at we've netted three we get to the next town over we get to the next town over right we're gonna gain five more right we're gonna gain five more units of gas but it'll cost us two to units of gas but it'll cost us two to get to the end get to the end so until it'll be three plus five minus so until it'll be three plus five minus two two will leave us at six all right so i know will leave us at six all right so i know the math doesn't really check out here the math doesn't really check out here leave us at six we're now sitting at leave us at six we're now sitting at this town this town we're gonna gain one unit of gas and we're gonna gain one unit of gas and lose three to go over to the next town lose three to go over to the next town for the next gas station so we're gonna for the next gas station so we're gonna gain one that'll be seven gain one that'll be seven we're gonna lose three that'll give us we're gonna lose three that'll give us four so we're now at four four so we're now at four now we'll start at two we're at this now we'll start at two we're at this town excuse me we're going to gain two town excuse me we're going to gain two and lose four we're gonna gain two we'll and lose four we're gonna gain two we'll be at six we're gonna lose four we'll be at six we're gonna lose four we'll have two have two finally we're at this town so remember finally we're at this town so remember this is where we started okay this is this is where we started okay this is our starting point right here our starting point right here now we want to see if we can make it now we want to see if we can make it just over the edge just over the edge and and make it right back to where we and and make it right back to where we started so if we we started so if we we we have two liters or two gallons we have two liters or two gallons whatever in the uh in the tank right now whatever in the uh in the tank right now two liters uh two liters uh it caught we can fill up three but it'll it caught we can fill up three but it'll cost us five to get over cost us five to get over meaning that we'll go see we'll go from meaning that we'll go see we'll go from two we'll get to five two we'll get to five it'll cost us five to get there after we it'll cost us five to get there after we fill up so we end up at zero fill up so we end up at zero however we did end up at our destination however we did end up at our destination and so that's why we're going to return and so that's why we're going to return this starting index this starting index now and that's pretty much now and that's pretty much you know everything we kind of got to go you know everything we kind of got to go through in this case over here there's through in this case over here there's nowhere you can start that'll actually nowhere you can start that'll actually allow you to do that because wherever allow you to do that because wherever you start you're going to lose more gas you start you're going to lose more gas than you would have filled up than you would have filled up and it's just not going to happen so how and it's just not going to happen so how do we actually solve this problem do we actually solve this problem well there are two trains about all i'll well there are two trains about all i'll walk you through what i think is the walk you through what i think is the more more more intuitive one the one that i tried more intuitive one the one that i tried the first time around and it worked but the first time around and it worked but it was a it was a it was a bit of a longer solution so it it was a bit of a longer solution so it wasn't it wasn't very efficient wasn't it wasn't very efficient what i thought to myself was the what i thought to myself was the following i thought well if i've got the following i thought well if i've got the gas and the cost at every given gas and the cost at every given point surely i can you know create a new point surely i can you know create a new array called net array called net right so what's the net gas that i'm right so what's the net gas that i'm getting getting at any given position getting getting at any given position and so i you know i figured here i'd and so i you know i figured here i'd have uh have uh well i'm gaining one unit of gas one well i'm gaining one unit of gas one liter i'm losing three liter i'm losing three so here i've got a negative two game i so here i've got a negative two game i would get one but i would lose negative would get one but i would lose negative two so i can't start here like it's just two so i can't start here like it's just it's not possible it's not possible right so that's definitely not an option right so that's definitely not an option same story over here i gained so i'm same story over here i gained so i'm starting at zero by default from the starting at zero by default from the question question if i gained two liters and then spent if i gained two liters and then spent four i would be again at negative two four i would be again at negative two and that's no good and that's no good three and five same thing once again net three and five same thing once again net negative negative however once i come across once i come however once i come across once i come across this count here across this count here i notice that okay well i'm getting four i notice that okay well i'm getting four and it's only gonna cost and it's only gonna cost one to get the next station so this is one to get the next station so this is an option for sure and then same thing an option for sure and then same thing over here i'm getting five but it would over here i'm getting five but it would cost me cost me only two to leave so i'm gonna get the only two to leave so i'm gonna get the three so what i did was i calculated three so what i did was i calculated this this net array and basically started net array and basically started iterating through the same iterating through the same if i'm looking at an index i if i'm looking at an index i i'm looking at this index over here if i'm looking at this index over here if the gas the gas is not negative i can't do anything i'm is not negative i can't do anything i'm looking at this looking at this that gas is negative can't do anything that gas is negative can't do anything net gas is negative can't do anything net gas is negative can't do anything once i get to the net positive place once i get to the net positive place then what i figured then what i figured what i wanted to do was to say let me do what i wanted to do was to say let me do a simulation a simulation here so now that i'm doing and walkers here so now that i'm doing and walkers i'm going to do n i'm going to do n more of them every time to try to more of them every time to try to simulate the actual path simulate the actual path and jumping from one to the next and so and jumping from one to the next and so what would essentially happen is what would essentially happen is i've got a net gain here of three and i've got a net gain here of three and then that gain here of three then that gain here of three and then when i start looping back and then when i start looping back around from the start i lose two lose around from the start i lose two lose two two lose two so these gave me six here i lose two so these gave me six here i lost six lost six i got to where i needed to because at i got to where i needed to because at the end i had i had no gas left but i the end i had i had no gas left but i made it i wasn't in the red made it i wasn't in the red and so that that kind of simulation and so that that kind of simulation works and it you know if i i'd urge you works and it you know if i i'd urge you to give it a try to code that out to give it a try to code that out yourself it's yourself it's it's not too bad um it's a bit involved it's not too bad um it's a bit involved and and you know ultimately there's a much you know ultimately there's a much cleaner way to do it that's the way that cleaner way to do it that's the way that i want to show you i want to show you so what we can do actually is uh so what we can do actually is uh is we can do this in one pass is we can do this in one pass so we we can actually do this entire so we we can actually do this entire thing in in one pass thing in in one pass and there's one piece of information and there's one piece of information that we need to realize in doing it in that we need to realize in doing it in one pass one pass and this is what that that one piece of and this is what that that one piece of information is information is and i i don't think this one is obvious and i i don't think this one is obvious at all at all no matter where you start from okay no no matter where you start from okay no matter where you start from matter where you start from your your goal is to touch every single your your goal is to touch every single gas station here there are five gas gas station here there are five gas stations no matter where we start stations no matter where we start if you start here you're gonna have to if you start here you're gonna have to loop all the way around and come back loop all the way around and come back here at the start again here at the start again if you start at index one you're gonna if you start at index one you're gonna have to go to the end and then have to go to the end and then jump over here back to the next one jump over here back to the next one every single time you're taking the same every single time you're taking the same steps steps meaning this net calculation kind of meaning this net calculation kind of holds no matter what holds no matter what right so no matter what happens the right so no matter what happens the total net gas we gain total net gas we gain and and release or spend i guess or and and release or spend i guess or whatever it costs us whatever it costs us that number is the same no matter where that number is the same no matter where we started we started so one thing that we have to notice is so one thing that we have to notice is simply going to be simply going to be if our total if our total net gas if it's net gas if it's less than zero then we're going to say less than zero then we're going to say not possible not possible okay so if our total net gas is less okay so if our total net gas is less than zero than zero it's just going to cost more than we're it's just going to cost more than we're ever going to gain no matter where you ever going to gain no matter where you start it's not going to happen start it's not going to happen and so one way to do this is you know and so one way to do this is you know check for that and then if it's like check for that and then if it's like okay it's not zero let me try to find okay it's not zero let me try to find the next starting point the next starting point that works but again that would kind of that works but again that would kind of be like a two pass solution we want to be like a two pass solution we want to try to do this in one pass try to do this in one pass so again the crux of it here is if you so again the crux of it here is if you can understand that the full net gas can understand that the full net gas doesn't change no matter where we start doesn't change no matter where we start from you're almost there from you're almost there the next thing we got to try to do is to the next thing we got to try to do is to then say at any given point then say at any given point let me keep track of my current gas i let me keep track of my current gas i also start here also start here and i said i'm going to fill up here and and i said i'm going to fill up here and leave to the next time what's my current leave to the next time what's my current gas situation going to be gas situation going to be well if i do that my current gas is well if i do that my current gas is gonna be at negative two so gonna be at negative two so that's no good so that means this is not that's no good so that means this is not a starting point all right it can't be a a starting point all right it can't be a starting point starting point if i go to and this by the way i'm doing if i go to and this by the way i'm doing this all my first pass right now so we this all my first pass right now so we can even can even you know we don't i'm not even going to you know we don't i'm not even going to calculate this sorry i'll leave it here calculate this sorry i'll leave it here just visually so maybe i'll just visually so maybe i'll i'll i'll separate with the perforated i'll i'll separate with the perforated line but i'm not going to be including line but i'm not going to be including this in my solution this in my solution so this one over here clearly didn't so this one over here clearly didn't work and then i tried here and i work and then i tried here and i told myself okay if i if i was to have told myself okay if i if i was to have started here my current gas starts at started here my current gas starts at zero zero um and now well i fill up um and now well i fill up two i lose four i'm not negative two so two i lose four i'm not negative two so that's not gonna work my current gas is that's not gonna work my current gas is like negative i'm gonna like negative i'm gonna you know burn out halfway through i'm you know burn out halfway through i'm not gonna have any gas left i'm gonna be not gonna have any gas left i'm gonna be stuck and deserted stuck and deserted in the middle of the nevada desert and in the middle of the nevada desert and that's bad news bears that's bad news bears we try the next one same story over here we try the next one same story over here now we check over here all right so now we check over here all right so we're checking over here and we realize we're checking over here and we realize okay my current net gas is positive okay my current net gas is positive and every single time by the way every and every single time by the way every single time we're failing at one of single time we're failing at one of these we see okay this can't be my start these we see okay this can't be my start let me try the next let me try the next let me try the next let me try the next let me try the next let me try the next one if i start over here one if i start over here and i set my starting point over and and i set my starting point over and right now i'm at index three i realize right now i'm at index three i realize okay my current gas is positive let me okay my current gas is positive let me keep going i'm not going to move my keep going i'm not going to move my starting point starting point while my current gas is positive if at while my current gas is positive if at any point down the line maybe i have any point down the line maybe i have another stop here another stop here and i realize like i'm just going to and i realize like i'm just going to lose so much i'm going to be a negative lose so much i'm going to be a negative gas if i start here then i can say okay gas if i start here then i can say okay none of these starts would have worked none of these starts would have worked for me for me because no matter what i would have lost because no matter what i would have lost at the end of the day my current gas at the end of the day my current gas would have been negative would have been negative and so whenever we we're going to drop and so whenever we we're going to drop this and like i said this and like i said um that that current gas as long as our um that that current gas as long as our current gas current gas never uh never goes negative never uh never goes negative then we can actually leave the starting then we can actually leave the starting point where it is and we can keep on point where it is and we can keep on going going through the end of the array we're gonna through the end of the array we're gonna make one whole pass through the array make one whole pass through the array and then if our neck has a zero we're and then if our neck has a zero we're going to return negative one going to return negative one right we're gonna return negative one right we're gonna return negative one otherwise otherwise what we're gonna do is we're gonna what we're gonna do is we're gonna simply return that starting point that simply return that starting point that we we that we actually had and and that's that we actually had and and that's gonna be about it gonna be about it so i i know we're almost 12 minutes here so i i know we're almost 12 minutes here into the explanation itself the code is into the explanation itself the code is going to be really simple so i wanted to going to be really simple so i wanted to i wanted to make sure that this made i wanted to make sure that this made sense let me know in the comments down sense let me know in the comments down below if you guys have any questions on below if you guys have any questions on on the logic behind this one on the logic behind this one i think it's kind of intuitive but it's i think it's kind of intuitive but it's a head scratcher like i really had to a head scratcher like i really had to sit in and think about this one when i sit in and think about this one when i when i saw the solution and tried to when i saw the solution and tried to like like try to internalize it but anyways like i try to internalize it but anyways like i said drop the comments if you haven't said drop the comments if you haven't and and uh otherwise we're we're good to go and uh otherwise we're we're good to go and let's let's take a look at the code and let's let's take a look at the code and see what we can do from there so like i suggested at the start we would have we'd have to take care of our or we'd have to track our total gas or current gas in a starting position so obviously total gas equals zero current gas is equal to zero and as well we're going to have some start position um and i'll say start also equals zero just by default we are going to have some sort of for loop sorry i'm going to be luco's here and at the end of the day once we we go through this whole loop we said that we are going to return the starting index only if the total gas ends up being non-negative if the total gas is negative that means it will cost us more than we're going to gain and we can't get to the end no matter where we start so we're going to return the start if it's actually a feasible trip otherwise we're going to return negative 1 because of our instruction so it says that to output negative 1 right here otherwise return negative 1 if it's not possible so otherwise we're going to return negative 1. now we said we're going to do this in one pass so all i'm going to do is just going to set a standard for loop and that's going to walk us through the length of these arrays and both of which again we were kind of guaranteed that they they would be equal so let's say for ion range and the length of gas and that could have been cost as well um what we want to do is we want to always be adding to our total gas so we want to add the net result of how much we're gaining and how much we're losing on our both our total gas and our current gas so we're going to see that total gas plus equals gas of i minus cost of i at every step of the way i'm going to say how much gas can i gain and then how much gas is going to cost me to get to the next town we're going to be tracking this perpetually as we go and at every step of course we're going to do the same thing with with kergus excuse me with current gas as cost of i and then once we do that at every single step we need to ask ourselves am i still good on gas right i do like do i have enough to get to the next spot so rather let's ask the converse am i in trouble if i'm in trouble i realize okay i can't start wherever i said i was gonna start so i need to move my starting point if i'm in a bad current gas situation right now i'm gonna have to say if curve gas is is less than zero then what we're going to need to do is two things one is to say okay this is like no bueno let's reset current gas is back to zero because i'm not starting there anymore moreover oh everything up to now this whole situation is so rad we've been on this this track this section of the road trip is not gonna work i can't start at any of these places because i'm gonna end up with the negative current gas so let me try the next spot over or for you guys sorry this this whole section was no bueno none like not this gas station wouldn't work the previous ones wouldn't work i can't start from any of those all right let's turn a new page let's start from the next one and see if we can do it there so what i do is i'd set my start equal to i plus one and really as long as i haven't made any really dumb mistakes this should be this should be all the all the code i'm just going to run it really quickly to make sure that i haven't made any mistakes i'm going gonna submit it here and there we go performs super well like i said the code was really short here but i i think it was still a good problem to wrap your head around this idea of like again i i'd argue that the the part that's the least intuitive is is the fact that our net net gas gas purchase and gas spent always ends up being the same number no matter what and so that's going to be the deciding factor and if it's possible or not the way we decide if it's possible or not is by actually determining how much current gas we have at any given point if that goes negative then wherever i started is no go we got to start from somewhere else and that somewhere else is going to be at least where we were plus one step ahead and we might have to drag that forward if we if we kind of keep getting into trouble so i i hope that that makes sense i hope this was helpful to you guys yep excuse me any other questions you you want me to answer let me know down below if you have any questions on this let me know like comment share subscribe i don't want to be one of those guys but it would mean a lot like i each my subscriptions it really does mean a lot it makes me happy when i see them and i i really really hope that i'm i'm helping you guys here with you know at least at least in iota so that's it uh and i'll see you guys | 2024-03-21 12:03:07 | 134 | GAS STATION (Leetcode) - Code & Whiteboard |
|
yspxhVUD1xk | Loot Hello Everyone Welcome To My Channel Today 17.3 Problem Is Remedy Issa Gaon 17.3 Problem Is Remedy Issa Gaon Intuitive Who Don't Tanning Correction Kar Intuitive Who Don't Tanning Correction Kar Actor Who Did All Reasons Why All Goals Actor Who Did All Reasons Why All Goals In To-Do Example Which Acts After Running In To-Do Example Which Acts After Running Function Mode Ko Switch Board The To The Media Mode Media Mode Media Mode On The But Not Least Not The Water And Not On The But Not Least Not The Water And Not Connected To No Connected To No A Phone In Water Will Feel To A Phone In Water Will Feel To connected to the subscribe the Video then subscribe to subscribe the Video then subscribe to the Page if you liked The Video Hair the Page if you liked The Video Hair against first in the against first in the first row and last row and the first first row and last row and the first column last problem solved wine depot on To To To Islam and will give for directions from Islam and will give for directions from this lutab skin subscribe voters and this lutab skin subscribe voters and converted to and subscribe the Channel converted to and subscribe the Channel Please subscribe Thanks Please subscribe Thanks Lucknow will revert back temporary variable the Lucknow will revert back temporary variable the various science paper and converted into a various science paper and converted into a very simple problem subscribe very simple problem subscribe implementation first day of subscribe to implementation first day of subscribe to the Video the Video the Video you liked The Video then subscribe to The Amazing 1208 Sexual Number Running From Different Subscribe To China And This Is The Volume To Subscribe Will Spread In The First Chief I That NDA This Is 545 Drishti Yet It Is For a Difficult to Enter in Adheen Dhoy For a Difficult to Enter in Adheen Dhoy For a Difficult to Enter in Adheen Dhoy 900 Mode On Kar 900 Mode On Kar Ki And Boy Should Also Be Greater Than Or Ki And Boy Should Also Be Greater Than Or Equal 10 And Why Should Also Be Equal 10 And Why Should Also Be Electronic The First Number Of Columns And Electronic The First Number Of Columns And Did Border Of Call Me Ishta Devi 209 The Character Revered Character Of The When will replace the current from water board When will replace the current from water board When will replace the current from water board access oil gauge temperature actor this is pain will definitely give one plus one that third Condition which is in place to return is Condition which is in place to return is Condition which is in place to return is second and basic implementation of second and basic implementation of defiance to dare solve already called for differ on we can also all the same defiance to dare solve already called for differ on we can also all the same for for disaster in 10m air chief half minus one disaster in 10m air chief half minus one Maa Kamakhya Yagya in which is equal to Maa Kamakhya Yagya in which is equal to character to end character to end character to end And E - 110 Default Subscribe For The First Time And Distance For Last For Two Years For The Calling Subscribe Number Of Eggs Subscribe Is Very Rare Condition Here Egg Subscribe And Have 9 B Last Column Is Special VPN - Of And Minus One Servi White And Minus One Servi White And Minus One Servi White Hair - 150 Blast To Subscribe Now To Pimples To 10 Plus Turn Off That Pimples To 10 Plus Turn Off That Eye Comedy Pimples To Videos Eye Comedy Pimples To Videos Bizarre All The Question Vighn j2j Is Equal Bizarre All The Question Vighn j2j Is Equal To To That X Service With Another Thing Being That X Service With Another Thing Being Replaced Back Replaced Back Replaced Back City Has Compiled And Were Getting City Has Compiled And Were Getting Correct Answer So Let's Try One More Kasam Correct Answer So Let's Try One More Kasam Test Case For Different Research Soft M Test Case For Different Research Soft M Trying To 2000 Replacing This Too So Let's Trying To 2000 Replacing This Too So Let's Seal Sudhir And No Will Replace With Introduction Introduction Introduction complexity of this software this is the biggest building all the time complexity of mode of a main where am is number of mode of a main where am is number of romance and is number of romance and is number of which pulp columns and space is festival se which pulp columns and space is festival se space complexities of me india not writing all extract Fiction College Thank You Felt Myself Please | 2024-03-21 11:42:18 | 130 | surrounded regions | surrounded regions leetcode | leetcode 130 | graph matrix dfs |
|
aoWHn88nJR4 | this is power of 4 lead code challenge 342. 342. giving an integer n we have to return giving an integer n we have to return true if N is a power of 4 otherwise we true if N is a power of 4 otherwise we have to return false an integer N is a have to return false an integer N is a power of 4 if there exists an integer X power of 4 if there exists an integer X such that 4 to the power of X is equal such that 4 to the power of X is equal to n an example is here we can have 4 to to n an example is here we can have 4 to the power of 2 this is 16 so we can the power of 2 this is 16 so we can return true return true 4 to the power of 0 is 1 4 to the power 4 to the power of 0 is 1 4 to the power of 1 is 4 and 4 to the power of 2 is 16. of 1 is 4 and 4 to the power of 2 is 16. so here if n is 5 we have to return so here if n is 5 we have to return false false and then here we can have 4 to the power and then here we can have 4 to the power of zero and we can get one so if n is of zero and we can get one so if n is one we have to return true according to one we have to return true according to the constraints the value of n is the constraints the value of n is anywhere between negative 2 to the power anywhere between negative 2 to the power of 31 and positive 2 to the power of 31 of 31 and positive 2 to the power of 31 minus one minus one um here they are challenging us to solve um here they are challenging us to solve this without any Loops or recursion but this without any Loops or recursion but that's just a follow-up so in my that's just a follow-up so in my solution here I'm going to use a while solution here I'm going to use a while loop and then perhaps in another video loop and then perhaps in another video I'm going to show you an alternative way I'm going to show you an alternative way of solving this challenge without using of solving this challenge without using any Loop but for today we have a loop so any Loop but for today we have a loop so the name of the function is power of 4 the name of the function is power of 4 is taking an integer so the name of the is taking an integer so the name of the function is here is power of 4 this is a function is here is power of 4 this is a Boolean function returning true or false Boolean function returning true or false and here is the parameter that we need and here is the parameter that we need to evaluate so my first condition is to evaluate so my first condition is that if n is either 0 or a negative that if n is either 0 or a negative value there is no value of x here that value there is no value of x here that can satisfy this condition so we can can satisfy this condition so we can return false another thing if you look return false another thing if you look at the constraints here they give us the at the constraints here they give us the range using 2 to the power of something range using 2 to the power of something but powers of 2 are 2 times slower than but powers of 2 are 2 times slower than powers of four so if they say 2 to the powers of four so if they say 2 to the power of 31 then the maximum value we power of 31 then the maximum value we can reach using a power of 4 will be 4 can reach using a power of 4 will be 4 to the power of 15 because 2 to the to the power of 15 because 2 to the power of 30 is the same as 4 to the power of 30 is the same as 4 to the power of 15. so we can't reach this power of 15. so we can't reach this value anyway exactly using a power of value anyway exactly using a power of four so I'm having this I variable here four so I'm having this I variable here that I'm starting at zero I could call that I'm starting at zero I could call it X like I did in my previous videos it X like I did in my previous videos but basically I here corresponds to X in but basically I here corresponds to X in the instructions so I'm going to check the instructions so I'm going to check here from 0 all the way to 15 to match here from 0 all the way to 15 to match the constraints here and at every the constraints here and at every iteration I'm going to raise 4 to the iteration I'm going to raise 4 to the power of I and verify if it's equal to n power of I and verify if it's equal to n so here I'm testing for this condition so here I'm testing for this condition if it's true I'm going to stop if it's true I'm going to stop everything and return true here so the everything and return true here so the function will terminate otherwise if function will terminate otherwise if it's false I'm going to increment I by 1 it's false I'm going to increment I by 1 and keep checking so 4 to the power of 1 and keep checking so 4 to the power of 1 then 4 to the power of 2 and so on all then 4 to the power of 2 and so on all the way until 15. if this Loop the way until 15. if this Loop terminates it and we never return terminates it and we never return anything it means that we have to return anything it means that we have to return false because whatever n has as the false because whatever n has as the value that was not a power of 4 so we value that was not a power of 4 so we have to return false so that's it for have to return false so that's it for this solution let me run this code we this solution let me run this code we pass the sample test case now when we pass the sample test case now when we submit it submit it we've passed all the various test cases we've passed all the various test cases in zero milliseconds making it a very in zero milliseconds making it a very fast solution if we click on details we fast solution if we click on details we see that we had over 1 000 test cases if see that we had over 1 000 test cases if you like this video you like my you like this video you like my tutorials and my Solutions and you want tutorials and my Solutions and you want to practice more coding interview to practice more coding interview questions please subscribe to my channel questions please subscribe to my channel and I'll catch you next time | 2024-03-24 10:58:30 | 342 | Power of Four - Google Interview Questions - LeetCode 342 Solution - C++ |
|
YuytbXYIa4g | hello guys this is expert Wanda and today we are going to see the little question that we have today is 129 and this question is uh 129 some root 2 Leaf notes and leaf numbers so you are given a root of binary tree and that containing uh this is from 0 to 9 only okay we have digits and that is 1 0 to 9. each route to leave path in the you can say tree representation tree represents a number okay so each route to Leaf path in the tree represents our number okay next for example the root to lift is one two three so one is root and two three each leaf and represents the number one to three return the total uh sum of all the root release numbers and test cases are generated so that the answer will be 15 to 32 which integers and this Leaf node is a node with no children Okay so in this sense it is saying that we have this root this is our root node and this is our Leaf Node 1 and this is for Leaf node 2 okay sorry clear if not o and leave it true okay so these are Leaf node so you can see that and how we will represent this that we will talk about later so it is it is saying that we have to uh represent this into the number and then we have to do what uh these numbers should be fit into 32 bits and number okay so we'll come to here again and we'll try to implement this one so first of all let's suppose uh if someone is given like this low one behavior and two we have given three and one is uh this is our root node and this is our Leaf node style so first to form one to two there is one One path is one two two okay this is root node and this is our channel from one to two so if you really represent this one into a number so it will be convert one two similarly if we'll go from one to three it will become what uh one three one three right and if you do the sum of these two so it will become 25 correct and this should be your answer right as you can see now we will talk about another example that we have here is uh four we have and so now we have nine we have 10 we have right and so rigid API and this is 5 we have and one over here okay so if you go from here to here to here right so it will convert 495 okay we are going actually from here to here first time so 495 we have next time we will go with what 4 9 and 1 because this is double Leaf children okay so it means we are going to from here to here to here okay so it will cover four nine one next time what we have we will have only one path this path is left right so we'll go with one zero so it will convert 4 0 it will do the sum it will become six nine nine eighteen eighteen and uh to 20 and 222 32 2 right and 4 4 and there is what uh two right so become 10. so this will become one zero two six right answer now if we'll talk about uh constant right so the nodes of notes of the uh in the trees what range into two one to one thousand and value will be 0 to 9 of the node value okay so this question is very very important so this question is very very important because this question has been asked in because this question has been asked in the Facebook multiple times and slowly the Facebook multiple times and slowly Google and apple Amazon Microsoft all Google and apple Amazon Microsoft all the other companies also asking these the other companies also asking these questions so you can say this question questions so you can say this question is very very important for the interview is very very important for the interview purpose right so topic is touching the purpose right so topic is touching the uh uh you can say topics that is tree uh uh you can say topics that is tree DFS my research you can use right so DFS my research you can use right so similar question you can uh see in on similar question you can uh see in on the lead code that is a path sum the lead code that is a path sum minority maximum person and smallest minority maximum person and smallest string starting from the leaf if you're string starting from the leaf if you're not able to find this question please not able to find this question please bring in the comments okay bring in the comments okay let's go to the uh solution okay and let's go to the uh solution okay and they will try to implement this one okay they will try to implement this one okay so solution if we'll talk about the so solution if we'll talk about the solution over you right so there are uh solution over you right so there are uh you can say uh 3DF space to uh Traverse you can say uh 3DF space to uh Traverse the three right and we know that DF is the three right and we know that DF is uh only right if you're not aware it you uh only right if you're not aware it you can do some Hands-On using the DFS can do some Hands-On using the DFS algorithm okay so there are three ways algorithm okay so there are three ways of uh you can say DFS to Traverse to the of uh you can say DFS to Traverse to the tree that is we have what uh pre-order tree that is we have what uh pre-order post order and pre-order right if you post order and pre-order right if you know what DFS it is what the first way know what DFS it is what the first way is uh to implement what pre-order right is uh to implement what pre-order right pre-order it will be order and then pre-order it will be order and then another is uh you can say post order and third one is what in order correct okay pre-order post order and in order and if we'll talk about the pre-order right we know that uh first we have to go with the left then we have to go to uh uh right right and then we have to go to uh this one right so only for the Post order is they are in order is there right so we will see yeah you can see that later okay we have to post it on this one so actually D phase we can Implement using the three ways that is free order post order and in order so in this way we will see uh clear height and you can see poster or in order we can implement this one also okay so the you can say why we use right uh uh what what optimal strategy we will we will have to solve this problem right so for the optimal strategy to solve this problem right I will go to the row to Left Right first it's about if this is if this is root tight so we'll go to the left side right and then uh then uh root to left will go so it is called pre-order right first we'll go root then we'll go to upper left and then if we'll talk about our another things right like right and those things so this approach will call pre-order right and uh if you go to the Post order first we'll go to Left Right and then we'll go to this uh root right similarly if you go to the in order first we'll go to the left then right and then uh faster redo and then right right like this so if we are going with what root and then left right from root to left then it is what it is called DFS pre-order traversal and to implement it uh one has to follow the straightforward strategy that is that is you can say root then you can say left and then we can say right okay this is the strategy you have to follow correct and so that uh since one has to visit all the nodes right and the best possible time complexity here is linear Source right so hence if you say uh all the interest here is to improve the space complexity right so there are three ways to implement reorder that is iterative recursive and models right so if we'll talk about these pre-order reversal right so there is three way so in which that in the iterative way you will get the best time complexity if you're the most right approach then you will get the constant space correct and if you use the recursive progress this is the simplest one to write okay so if you are in the interview I will suggest you use the simplest one because it is easy to write okay what you have to see the what what do you need the time complexity you need best time complexity need constant Express need and best way to write the program you need right so we will see the iterative approach right first because this is the best time to complete guide and will try to implement this one so if we'll talk about the identity pre-order traversal right so here we will here we can say will uh how will do the implementation right of the three Auditors you can say okay with hashtag first of all we'll push a root onto the stack let's suppose if this is a stack right let me see open so we'll first of all we'll push root here okay then what will happen while the stack is not empty we'll check the stack is not empty will pop out a node from this type we will remove we will get it about or from here and we'll check and update the current number right if there is a node in the leaf right which means there is a left or right so we'll update the root 2 root 2 leaves and we'll do the sum right and we'll push right and left children put into the state so only one here probably if node is leave right if this is if we will post another thing I will check if the node is leaf node then what we will update root to sum row two Leaf sum okay so we'll update there and similarly if we will push right and leave uh left children into the stack and we will return the root to leave sum we will to have to do the sum and then we each time we will update it okay so what we have to do first of all we have to push onto the we have to push the root into the stack and while stack is not empty we'll pop out the node from the stack and update update the current number okay and if the number is just if the node is leave then what we will do we will update the root to leave sum and if it is right we'll push right and if children onto this type and we'll update the same thing again and again okay so if we'll talk about what I'm trying to say let's understand this so we'll take a root 2 left Leaf node right and we'll take one current number okay so I'll take one int uh there is a we can say root to leave okay so release okay root root two leaves will take and uh do that we say root 2 leave also okay so we have root 2 leave and this is nothing whatever what zero and if we'll talk about another one is current number right so we'll take int current number like this and this is what we have 0 and we will update each time current number right so to do that what we will do we will take up here of three node and its integer right so and we have to take in the queue right so if we'll talk about array Q array DQ it will take a ready queue and it is what we have let's suppose you will take in the pair right so I'll take like this only so it should have appear it should have into appear and that is known onto the stack we will add on to this type and this query will take what a pair of three node and its number right so let's what I'm trying to say we have pair class and in create class will take what three node and this pair will go to where onto DQ and this pair will go to where onto DQ right so we'll take DQ DQ I will add on right so we'll take DQ DQ I will add on to here to here right so DQ will take what DQ will take right so DQ will take what DQ will take this pair of our tree node and integer this pair of our tree node and integer and that is called our stack I think we and that is called our stack I think we are good now what we should do will uh are good now what we should do will uh add a root onto the stack so to do that add a root onto the stack so to do that we will take stack dot will do push right and then we will add what uh new pair we should add and this pair is nothing what that we are doing right root will add and another will do at what zero any series that we have seen right root was 4 and then its value is 0 right number zero so we have initialize this one now what we will do we will uh do the traversing it how we will do that we'll check while and we'll check not null empty his employment method and we'll check if the stack is not empty then we will go with what uh we'll take a pair and that pair will be nothing but dot will do for dot will do for and we will get this pair and this page and we will get this pair and this page is nothing whatever what this viewer we is nothing whatever what this viewer we are getting forward this pair this speed are getting forward this pair this speed will get from will get from here right and we will say here right and we will say like this okay like this okay now if we'll talk about the once we will now if we'll talk about the once we will get the pair right what we will do we'll get the pair right what we will do we'll say root say root and P Dot P dot get value you will get your root value right you have got your root value P dot get and then you will get the from the pair we will get the value from peer value you can see okay next time what we will do um we should check if the root is not null right if root is not no means we have some value then what we should do we have our current we have our current number right on the current number what we'll do current will apply this formula current into first of all we'll multiply with 10 and then then we'll do root Dot value so that we'll update our current number each time correct so if it's a leaf number we will update our root to leave sum right so what we'll do we should check if root Dot it's left kid have some value right or it's a not null [Music] is null is null right if it is null and so we will right if it is null and so we will similarly we should check with root Dot similarly we should check with root Dot write one write one and if it is equal equal to and if it is equal equal to null means both are Leaf node right if null means both are Leaf node right if both are Leaf node then what we will do both are Leaf node then what we will do root 2 root if we have right and this root 2 root if we have right and this root to leave will do plus what our root to leave will do plus what our current number We'll add on to the current number We'll add on to the current number We'll add correct now current number We'll add correct now what we do what we will do if these are what we do what we will do if these are root lift root lift root lift root lift current and this one okay left and right current and this one okay left and right so we'll update our route to here so we'll update our route to here if this is not if this is not if this is not if this is not then we should add on to the stack right then we should add on to the stack right if this is the leaf node then we will if this is the leaf node then we will find our uh we will get the root number find our uh we will get the root number current number and we will add on to the current number and we will add on to the root Leaf right and if this is not if root Leaf right and if this is not if this is not uh you can say Leaf node this is not uh you can say Leaf node then we will not update root to leave then we will not update root to leave but we'll update onto the stack I think but we'll update onto the stack I think you've got so let's add on to the stack you've got so let's add on to the stack what we will do we will say what we will do we will say nuclear and then we'll add this one nuclear and then we'll add this one like this like this but here what will happen here is what but here what will happen here is what where will come from what root Dot where will come from what root Dot left left correct and on to the integer correct and on to the integer this one it will become what this one it will become what it will come uh you can say it will come uh you can say current number current number right current number why it is giving the error because we are taking this one but we will take this one because we are taking construct of this one okay now this will work okay similarly we'll take this one and we'll okay here we'll take right okay so if left and right is not leave right if if left left if leaf if leaf node node and if not found if node node not hot not hot okay then we will do these things okay okay then we will do these things okay I think understood once these are done I think understood once these are done so we'll complete our else then we'll so we'll complete our else then we'll come to our you can say while loop and come to our you can say while loop and then we'll come to our this one you can then we'll come to our this one you can say now say now uh method on right uh method on right here so before that what we will do we here so before that what we will do we will return here will return here [Music] [Music] turn what turn what root root to leave so what I have taken first first of all so what I have taken first first of all I have taken a method name and that is a I have taken a method name and that is a sum and it is taking root will take we sum and it is taking root will take we have taken book Leaf then current number so we have added a stack root onto the stack sorry I'll run the stack then we have what we have did we have did a root Vapors and then zero we similarly we'll get our root and after doing the pop and we'll check on to the uh if it is not null we will find our current love data current number if this is root leaf or if this is the leaf nodes we will find our root to leave and similarly we will find our stack value stack dot push will do if it is not leave nodes and finally we'll get our row to leave okay so I am getting what p p is uh root value right now sorry this would be key okay this would be key value function contains value as a en value okay so I'm getting errors meeting at 145 25 should be the answer okay so let's understand why we are getting here error mm-hmm mm-hmm first of all what we have did first of all what we have did let's start from here let's start from here first we have taken this uh we can say first we have taken this uh we can say uh this one right uh this one right then we have taken what these variables then we have taken what these variables then we have taken our then we have taken our wild condition wild condition in this wild condition in this wild condition we have taken these conditions we have taken these conditions then we we have what then we we have what uh uh um if this is root null um if this is root null will not completed here but will come to will not completed here but will come to here okay this is the thing if this is not null correct and then we will do these things okay let me do 25 okay so if this is if this uh is not right if root is not null then we will do this one and if if this is a Leaf nodes right so we'll do this one if this is if this is not the leaf node then we'll do um root total right and current number root Dot left and left uh left and right okay so actually here we should do first first we should go to the right I think first we should go to the right I think yeah yeah and then we'll go to the left and then we'll go to the left 135 is coming 135 is coming what I'm doing is check okay okay I got it got it we got our okay okay I got it got it we got our root right root right we got our root but we have not updated we got our root but we have not updated current current we have to get our current also right we have to get our current also right current is will take from P dot get key current is will take from P dot get key get value get value mm-hmm mm-hmm how can I do this mistake yeah yeah see you tomorrow so why we're yeah see you tomorrow so why we're getting the mystery word we have updated getting the mystery word we have updated our route right but we have not updated our route right but we have not updated our current number so if you'll do this our current number so if you'll do this update so it will work okay so first we update so it will work okay so first we have taken the root leaf and we'll up have taken the root leaf and we'll up we'll return this Loop rootle collector we'll return this Loop rootle collector so after before after that what we will so after before after that what we will do we have taken the stack and this do we have taken the stack and this stack will take a pair of root note and stack will take a pair of root note and integer we will push the root first and integer we will push the root first and then we'll get the row I will do the pop then we'll get the row I will do the pop and we'll check on to the you can you and we'll check on to the you can you find our root and parent number we'll find our root and parent number we'll check if the root is not null then we'll check if the root is not null then we'll find our current number using this find our current number using this formula into 10 and then plus where root formula into 10 and then plus where root value then we'll check if this is low uh value then we'll check if this is low uh Leaf nodes and we'll update our row to Leaf nodes and we'll update our row to leave leave and if not then we'll update our Stacks and if not then we'll update our Stacks right like this so that's all for today right like this so that's all for today so if you talk about the time complexity so if you talk about the time complexity right if there is total number of node right if there is total number of node is n right so it will become uh right is n right so it will become uh right here so time complex to become what o of here so time complex to become what o of uh n right if n is the number of nodes uh n right if n is the number of nodes right so uh we because we have to visit right so uh we because we have to visit each node right and if we'll talk about each node right and if we'll talk about the space complexity right so it will the space complexity right so it will convert if yeah the till the height convert if yeah the till the height right so height of if H is the height right so height of if H is the height right so we'll say o of right so we'll say o of pitch pitch right right that's all for today thank you so much that's all for today thank you so much guys thank you so much | 2024-03-21 11:40:59 | 129 | Leetcode 129. Sum Root to Leaf Numbers || Iterative Preorder Traversal || Java Solution |
|
PnmfWs5AcGc | hello everyone welcome to myu programming Club welcome to myu programming Club today we will be solving another daily today we will be solving another daily lead code challenge lead code challenge and the challenge name is we move and the challenge name is we move duplicates in letters duplicates in letters so you are given a string s and you have so you are given a string s and you have to remove duplicate letters so that to remove duplicate letters so that every letter appear exactly one and on every letter appear exactly one and on once and only once so for example in this string uh B is repeated twice and C is also repeated twice and in the resultant string all the characters are appearing only once so also it is further mentioned that if there are multiples such answers you have to return the smallest lexiographical order so so for let's consider for this particular for let's consider for this particular string in this particular string you are having two options either you could have deleted uh let me Mark the indices one two three and four either you you could have deleted this 0th index B or you could have not deleted this one and instead of that this one would have been deleted so your resultant string let's say in C let's say you deleted this your resultant string will become BCA which is not the lexicographically smallest possible so you can do better than that so uh how uh finding the lexicographically uh finding the lexicographically smallest one smallest one for that what we will do is and another list visited list or say array whichever uh you are comfortable with uh it depends upon language to language here in C plus so so what we will do is what we will do is this this array will show the visited array will show the visited uh uh characters that have been used or say characters that have been used or say visited there have been or say string or say string now this tag will be present the that you will be forming in reverse that you will be forming in reverse order instead of storing the character what we will do is in both of these uh data structures stack and this visited we will store the relative difference of we will store the relative difference of character with small a for example for B for example for B it will be it will be one for let's say a one for let's say a it will be zero so let's say c it will be zero so let's say c it will be 2 it will be 2 so on so on and from 0 to 25 and from 0 to 25 uh your difference will be ranging from uh your difference will be ranging from 0 to 25 so in total 26 values will be 0 to 25 so in total 26 values will be required required to represent these differences to represent these differences let's call this character differences and the whole stack will be called will be called character difference tag and now what we will do is now what we will do is uh we will iterate the string from left uh we will iterate the string from left to right initially you will push to be in the stack since it it's empty as of now we will not be opposed uh it's a relative difference uh with a small letter A will be boost because the in the constants it's mentioned that lower English let us will only be present in the string and the Order of the string will the length of the string will be your order 10 is to power so what we will do is we will push B now uh we will be visited uh also before proceeding further let's and another data structure I would like and another data structure I would like to introduce to introduce which will be used is which will be used is a vector or say array storing the last index of every character three three or C its last index of occurrences or C its last index of occurrences for for for a last index on the and the only for a last index on the and the only index is two so this is how your values will be stored so for a b and c A to B 3 and c will be 4. let's say uh now you will check let's say uh now you will check if the character that you are going to if the character that you are going to push on the stack push on the stack is greater than the top of the stack is greater than the top of the stack yeah it is the case that the character yeah it is the case that the character we are going to push on the stack is we are going to push on the stack is greater than the top of the stack so greater than the top of the stack so we'll push the character we'll push the character and we will and we will move move our pointer to the next character okay okay now when we move to this character we will see uh that c is greater than a is is greater than the current character that is we are considering for pushing on the so what we will do is so what we will do is as long as we can adjust this C as long as we can adjust this C somewhere else what I'm what I mean by somewhere else what I'm what I mean by adjusting is that another the last index adjusting is that another the last index that at which C is opening is greater that at which C is opening is greater than the index of current character than the index of current character last index at which c will occur is last index at which c will occur is 4 4 so so we can leave this C we can leave this C and tickets last occurrence which is and tickets last occurrence which is beyond the current index beyond the current index uh this is your current index so it will help us to gradually build the smallest lexicographically smaller string because a is smaller than C so we can place it before c provided C is having our friends which is at a index greater than the current index the current index is 2 so C is also occurring at this place so we will remove this similarly we will do for B and B's last occurrence is three and B's last occurrence is three as of now B is zeroth occurrence is as of now B is zeroth occurrence is pushed on the stack so what we will do pushed on the stack so what we will do is is so c will be removed from the so c will be removed from the visit redirect see uh C is no longer visit redirect see uh C is no longer part of the string so also as we see B part of the string so also as we see B is greater than a and its last is greater than a and its last occurrence is greater than the current occurrence is greater than the current index which is two index which is two so we will remove it from also from the so we will remove it from also from the stack and stack and subsequently we will remove it from the subsequently we will remove it from the visited array also so these are not visited array also so these are not visited as of now only a will be pushed visited as of now only a will be pushed so it is visited as of now so it is visited as of now so V is greater than a so it will be so V is greater than a so it will be pushed pushed now B is now B is uh uh greater than greater than C is greater than b so it will be pushed C is greater than b so it will be pushed now let's say further there are some now let's say further there are some other words also other words also b c a b c a these will not be pushed why because these will not be pushed why because visited array is already containing them only one occurrence of each character is allowed and we have already pushed and string string which is having only single occurrence which is having only single occurrence of a character so it will be in reverse of a character so it will be in reverse order ABC order ABC I hope you are able to understand I hope you are able to understand so we will try to so we will try to take the smallest let me quickly change take the smallest let me quickly change the slide we will try to yeah we will try to yeah we will try to take smaller characters left most possible place now let's say let's consider a condition I know it's a little messy I know it's a little messy oh let's say this is not here so you could not because it is not having any other because it is not having any other occurrence you have to put it here occurrence you have to put it here itself itself so you cannot Pope the values of c so so you cannot Pope the values of c so this is the case in which a character is this is the case in which a character is cannot be adjusted so this is the logic of the problem and the one time complexity will be time complexity will be o of n and the space complexity will be and the space complexity will be also order of n where n is the size of also order of n where n is the size of the string the string it will be required for your stack it will be required for your stack and those two vectors already is so let's have a look at the approach will be more clear to you in approach will be more clear to you in the implementation part or say vector we will store index of occurrence foreign and one thing to be noticed is it is to and one thing to be noticed is it is to be noted that reduce the size of the uh required uh required to put characters relative difference with smaller in last index array in last index array and visited our both of these so this last index will store the last index of and last indices will be used to see if and last indices will be used to see if we can adjust the greater character at we can adjust the greater character at the end the end uh last indices uh last indices will be used when uh appears and we have to check adjust at a index smaller character smaller character foreign to build the smallest character possible to build the smallest character possible this is this one is the this is this one is the all all Intuition or logic Intuition or logic so so after storing the last index after storing the last index this is the relative difference of the this is the relative difference of the character with a that I am mentioning character with a that I am mentioning here here or you can move it or you can move it so here visited array will be used to visited array will be used to it will be used to in the in the resultant string and last is which inverse the same the simulation that I have this particular string if you encounter a empty stack or say a known empty stack larger and and those characters those larger characters after the current index after the current index then keep popping the values keep then keep popping the values keep opening those well those characters from opening those well those characters from the stack and this is how you will be building your final resultant string and this is how building your building your resultant string so that's pretty much it and at last you will reverse the string before returning it since in stack it will be in upside down manner at last you will as we was as we was after reversing is as you can see it's getting accepted as you can see it's getting accepted so if you are still having any doubts so if you are still having any doubts please feel free to ask them in the please feel free to ask them in the comment section code will be available comment section code will be available in C plus plus and Java both in C plus plus and Java both so thank you for watching so thank you for watching thanks | 2024-03-24 10:23:18 | 316 | 316. Remove Duplicate Letters | Daily Leetcode Challenge | September | C++ | Java |
|
IQT0ObOMqos | That Hey Guys Welcome Channel White Udayveer A Problem Call Minimum Number Four Equals To Problem Call Minimum Number Four Equals To Forget Problem That Comes In Various From Forget Problem That Comes In Various From Interview Video Problem 28 Without Status Minimum Interview Video Problem 28 Without Status Minimum Number Of Meeting Rooms Spider-Man Uber Number Of Meeting Rooms Spider-Man Uber Of Nations For Its Students Call Minimum Of Nations For Its Students Call Minimum Number Of Every Five Wickets To Number Of Every Five Wickets To Number Of Every Five Wickets To Subscribe Subscribe Please Subscribe This Solve Marriage Sanskar Play And 120 Dars On Ki And The Question Shezwan Jain Adi Festivals Dotted Lines To Balloons To Oriental Wed 29 Aug 2010 2010 Vertically Upward Direction Is The Shooting Dec 2010 Subscribe Position A Little Boy Status Pallu Hai Natwarlal Sabs Iss Par Vishwas 80 Part Of The Year Or So And For Example Bihar From This Point To This Point Distance Distance And And Subscribe subscribe to YouTube Channel and subscribe the Channel Please subscribe the Channel subscribe the Channel subscribe 6 Problem Stamp Vendors subscribe 6 Problem Stamp Vendors Invented This University Invented This University 1121 1080 Boys Will Not Understand 1121 1080 Boys Will Not Understand 200 Grams The Two Two Two Two Two Two Two 200 Grams The Two Two Two Two Two Two Two All So Let's See Who Can File A That Solve This Problem In 24 Hours Will Pay Pay Pay Volume Minimum Maximum Return Problem Volume Minimum Maximum Return Problem Superintendent Hai Shanti Dynamite Bhi Agni Superintendent Hai Shanti Dynamite Bhi Agni Problem Solve Person Door We Are Going Problem Solve Person Door We Are Going To Pickup The Phone Tune With The Earliest And To Pickup The Phone Tune With The Earliest And Will Start Will Start From This Point From This Point Now Room Now Room 9.00 Subscribe News One Example Points Of Side Effect Control Please Please Subscribe Us Unauthorized Unauthorized Unauthorized Gemini Airplane Solves Balloons and Avoids Gemini Airplane Solves Balloons and Avoids Soft Ambient Android Clear 100 Years Boys Win The Three And Not Willing To Give Way To Find Out Which All And Share On Sent And Updated On Updated On Other Channels Best All The Volume Tower Other Channels Best All The Volume Tower Start Exploding 100 Start Exploding 100 Start Exploding 100 Bulb Scorch Indian Roads Will Come True For The Number Four Books For Class Seventh Day Of Starting Point In The Same To Will Do And And Will Not That Grandma Shaitan That Grandma Shaitan 98898 Start Point Of The 98898 Start Point Of The 98898 Start Point Of The Green Earliest And Points Will Update Aryans And 128 And Will Trust Matter ₹100 Note I Left Hand Next Will Get 9 Votes Will See The Stars Current Bollywood This Current Affairs In This Will Be Would Also Would Also Would Also Request Request 2021 President Solution Waqt Example In And Around For This What Is This What Is This What [ Music] Should Return Music] Should Return Solution Solution 810 Subscribe To 56001 Point Are Suno 810 Subscribe To 56001 Point Are Suno Point Se Reserving Ise Jahar Winning Are Two Sides With 300 Daughters From This Daughters From This Daughters From This In To- Do Setting On The Con Is On Is Point To Subscribe The Points Yuvan Dashain 2070 Pims Videos Current In Points Know When To Walk Through It's A Gift For Ourselves Travels and Tours Point This Point on Pimples Current Current and Take No 6000 6000 Years But Not in Years But Not in the Number of Weirever Current and Only Man to Start from Current and Don't Like This Towards Chut Center Point Stop This Point Forced Start Points Wanted The list is Points Wanted The list is Points Wanted The list is requested for you dare not want to requested for you dare not want to update the number of years and not brought to update the number of years and not brought to front end Points Idioms Appoint Soyenge Example Effect This Example front end Points Idioms Appoint Soyenge Example Effect This Example Comes Comes Up with the Stars This Current Balloon is Great Up with the Stars This Current Balloon is Great Dinner and Condition to Dinner and Condition to Andhe Updater Andhe Updater Andhe Updater President Withdraw from 2nd ki Subscribe Switch on the number of kya tak ho ki addressed huge minimum kya tak ho ki addressed huge minimum number of requests for user balloons and number of requests for user balloons and important questions for preparing for important questions for preparing for technical interview technical interview technical interview Want Something Dedh-Dedh Please Like Share With Your Friends And Subscribe Our YouTube Channel And Fear Print Out From Its Always Near The Calling Problem Bank Government Will Open A Country Club Cutting And All Smiles At This Time Is Unique In Some In Some In Some | 2024-03-22 14:28:52 | 452 | MINIMUM NUMBER OF ARROWS TO BURST BALLOONS - CODING INTERVIEW QUESTION - LEETCODE 452 |
|
tT4LIOl5DNo | Hello friends today I'm going to solve liquid problem number 382 linked list liquid problem number 382 linked list random node so in this problem we need random node so in this problem we need to implement the solution class the to implement the solution class the solution class has two um functions the solution class has two um functions the first function is solution linked node first function is solution linked node head and the next function is get random head and the next function is get random function so basically this is a function so basically this is a Constructor function Constructor function and this is a function where we are and this is a function where we are going to get a random node from the going to get a random node from the linked list linked list so in the Constructor function in the so in the Constructor function in the solution function here we are going to solution function here we are going to initialize our linked list object so we initialize our linked list object so we will be given the head and argument and will be given the head and argument and we need to initialize the linked list we need to initialize the linked list object and then from get random we need object and then from get random we need to get a random node from the list and to get a random node from the list and the possibility of probability of the possibility of probability of getting any random node should be equal getting any random node should be equal so let's see how we could solve this so let's see how we could solve this problem problem um basically here what we are given is um basically here what we are given is in the solution function we need to in the solution function we need to create create um um initialize the object so what are we initialize the object so what are we going to do is we are just going to um going to do is we are just going to um create a head of the linked list and create a head of the linked list and store the value of the head in our store the value of the head in our linked list head linked list head and also in the get random and also in the get random um function since we need a random value um function since we need a random value within the linked list so how can we within the linked list so how can we actually achieve a random value let's actually achieve a random value let's suppose if these were an array so suppose if these were an array so um let's suppose if these were an array um let's suppose if these were an array so what would we have is one two and so what would we have is one two and three in an array right so for the array three in an array right so for the array we also know the length of the area so we also know the length of the area so we can just get the length of the array we can just get the length of the array by if this is an error a we could just by if this is an error a we could just get the length by a that length that get the length by a that length that would give us the length of the array would give us the length of the array right suppose L is the length of this right suppose L is the length of this array then we can get the random value array then we can get the random value from this array by from this array by um um multiplying this length with a random multiplying this length with a random number a random number which is in the number a random number which is in the range 0 to 1. so how is that possible range 0 to 1. so how is that possible how is it possible that this gives us a how is it possible that this gives us a random number so since this value is a random number so since this value is a random number and this is a fixed number random number and this is a fixed number right so if we multiply any value with a right so if we multiply any value with a random number we are going to get a random number we are going to get a random value random value so that's why we are going to use this so that's why we are going to use this formula for that let's just take this as formula for that let's just take this as an example since the length is equals to an example since the length is equals to 3 and let's choose a random number 3 and let's choose a random number between 0 and 1. let's choose a value between 0 and 1. let's choose a value 0.2 so what would this return uh that 0.2 so what would this return uh that would return us would return us 1.5 right so do we have a node 1.5 where 1.5 right so do we have a node 1.5 where of course not we do not have a node 1.5 of course not we do not have a node 1.5 we are actually going to take the floor we are actually going to take the floor value of this so that would mean we are value of this so that would mean we are taking the node at index one so this is taking the node at index one so this is 0 so this is one so that's we are taking 0 so this is one so that's we are taking this value now let's suppose we get a this value now let's suppose we get a random number of random number of um 0 point um 0 point seven so in this case what's the value 7 seven so in this case what's the value 7 times 3 is 21 right so we get 2.21 and times 3 is 21 right so we get 2.21 and since we are taking the floor value we since we are taking the floor value we get we take the node at index two so we get we take the node at index two so we take this node value and suppose we get take this node value and suppose we get a random number 0.5 that in that case we a random number 0.5 that in that case we would get would get okay so I did this calculation wrong okay so I did this calculation wrong here this would be here this would be 0.6 which would be the node at index 0 0.6 which would be the node at index 0 and in this case this would be 1.5 and and in this case this would be 1.5 and that would be node at index five one so that would be node at index five one so we are actually getting all the random we are actually getting all the random values right and all of these are in the values right and all of these are in the range 0 2 2. range 0 2 2. so in this way we can actually obtain a so in this way we can actually obtain a random note from an error right but in random note from an error right but in case of linked list we do not know the case of linked list we do not know the length of the linked list right so what length of the linked list right so what are we going to do is we are first of are we going to do is we are first of all going to determine the length of the all going to determine the length of the linked list when we are actually linked list when we are actually initializing the object so in the initializing the object so in the solution function we will solution function we will um also determine the length of the um also determine the length of the linked list so now let's do that linked list so now let's do that so let the length initially be zero and so let the length initially be zero and then we Loop over a while loop while we then we Loop over a while loop while we have the heat have the heat um the length will keep on increasing um the length will keep on increasing and then we move to the next hit every and then we move to the next hit every single time so this will give us the at single time so this will give us the at the length of our linked list and the the length of our linked list and the heat so basically heat so basically now we will take this length and find now we will take this length and find the random index for our the random index for our um random get random function so what um random get random function so what are we going to do is let a random value are we going to do is let a random value be equals to be equals to um method floors we are taking the floor um method floors we are taking the floor value and we are using the random value and we are using the random function from our JavaScript function from our JavaScript library to generate a random number and library to generate a random number and then multiply that with the length of then multiply that with the length of our linked list our linked list so this will now give us a random value so this will now give us a random value we are taking the floor value of that we are taking the floor value of that random number and then random number and then what are we going to do is we are going what are we going to do is we are going to find the right known at that index so to find the right known at that index so while hit okay not 8 while Rand value minus minus so we are looping over oops I'm sorry so we have our head and now from that is from the beginning we are now going to iterate until unless we reach that node so here it goes to head that next and then finally we are going to return our head let's try to run our code okay so I have oh actually we need to return the value all right since it's been accepted let's all right since it's been accepted let's submit it awesome so the time complexity to solve this problem would be since we are um iterating over each of the node in the link list this would be and off and time complexity and in this function as well since we are iterating over each of the Heat this would also be an off and time complexity and the space complexity is constant for both of the functions we could also solve this problem in a constant in um of an um space complexity and of one time complexity for get random I mean of one time complexity for the solution function and of and time complexity for this one so how could you solve this in of one time complexity let me know in | 2024-03-24 11:55:07 | 382 | 382. Linked List Random Node | O(1) SC | O(N) TC | LeetCode Daily Challenge |
|
rkWBTDX5fm0 | hey hello there today's recording challenge question is coin change - it's challenge question is coin change - it's a dynamic programming question so let's a dynamic programming question so let's talk about the structure we have a few talk about the structure we have a few different type of coins that we can use different type of coins that we can use to sum up a to a certain amount each to sum up a to a certain amount each type of coin definitely have a different type of coin definitely have a different value for this question we want to write value for this question we want to write a function to compute the number of a function to compute the number of combinations we can use those coins to a combinations we can use those coins to a sum up to that amount so we are only sum up to that amount so we are only looking at combinations we're not looking at combinations we're not looking at the sequential order of the looking at the sequential order of the coins being picked we may assume that we coins being picked we may assume that we have infinite sand number of coins for have infinite sand number of coins for each kind the examples let's look at the each kind the examples let's look at the one we have a total that's fine and we one we have a total that's fine and we have three type of coins one two five have three type of coins one two five there are four unique combinations of there are four unique combinations of the coins we can do to sum up to five the coins we can do to sum up to five single phi2 to single one one two and a single phi2 to single one one two and a three one or five ones so that's the three one or five ones so that's the four different two distinct the ways of four different two distinct the ways of combined or the coins we have to sum up combined or the coins we have to sum up to five the order of you know if we to five the order of you know if we consider some some some combination that consider some some some combination that involves two different types of coins we involves two different types of coins we can do two to one but there is no but can do two to one but there is no but two one two is not considered us of one two one two is not considered us of one unique combination the order does not unique combination the order does not matter so so it's important to have that matter so so it's important to have that in mind when we reason about the in mind when we reason about the subproblems so let's talk about let's subproblems so let's talk about let's look at this a little bit more look at this a little bit more graphically the initial problem for the graphically the initial problem for the example is that we have we have to make example is that we have we have to make up a to five and we have three different up a to five and we have three different coins one two five so one we are coins one two five so one we are attempting to divide this into three attempting to divide this into three different subproblems if we choose one different subproblems if we choose one so the total reduced to four we still so the total reduced to four we still have those three different types of have those three different types of coins at our disposal we reduce the coins at our disposal we reduce the Stono by two if we choose a coin to the Stono by two if we choose a coin to the total reduced to three and we still have total reduced to three and we still have those three different coins those three different coins or we reduce the amount to zero by or we reduce the amount to zero by choosing a single file choosing a single file you know that's by that's if we try to you know that's by that's if we try to set this three different subproblems to set this three different subproblems to sum up a to the to the original parent sum up a to the to the original parent problem there will be seriously problem problem there will be seriously problem for this here we choose one here we for this here we choose one here we choose to what do you that which is choose to what do you that which is another two and choose choose the one to another two and choose choose the one to reduce this total to zero so here will reduce this total to zero so here will be one and on this branch if we choose be one and on this branch if we choose continuously choosing two from now on continuously choosing two from now on after choosing the initial one this big after choosing the initial one this big reduced to two and now zero so the reduced to two and now zero so the problem was setting the sub apartment to problem was setting the sub apartment to be only reducing the amount but not be only reducing the amount but not limiting the options of the coins is limiting the options of the coins is that we're going to have two to one and that we're going to have two to one and wanted to consider separately so we are wanted to consider separately so we are basically topic hunting and in this case basically topic hunting and in this case we actually in this set up we actually we actually in this set up we actually explicitly implicitly actually thinking explicitly implicitly actually thinking that assuming that the order of coins that assuming that the order of coins being picked does count as a unique way being picked does count as a unique way but in fact for this problem it's it's but in fact for this problem it's it's not so there's problem in this sub power not so there's problem in this sub power of the set up so what's the correct way of the set up so what's the correct way of doing that so let's say that we are of doing that so let's say that we are picking two and reducing the total to picking two and reducing the total to three the in the other branch we will three the in the other branch we will actually want to eliminate the option of actually want to eliminate the option of choosing two because whatever the choosing two because whatever the combination that involves two is going combination that involves two is going to be the sub problem fall from the to be the sub problem fall from the branch and on from this other branch branch and on from this other branch anything that if we continue to have two anything that if we continue to have two as an option we're gonna have overlap as an option we're gonna have overlap with the other branch that's illustrated with the other branch that's illustrated by this here so the set before the by this here so the set before the corrected sub problem set corrected sub problem set we're gonna form one of the sovereign we we're gonna form one of the sovereign we reduce the amount using the using using reduce the amount using the using using the option the other branch we're going the option the other branch we're going to eliminate that options altogether so to eliminate that options altogether so that's the correct way of setting up the that's the correct way of setting up the subproblems so just let me make this a subproblems so just let me make this a little formulary CLE we have a month we little formulary CLE we have a month we have some options so one thing we can do have some options so one thing we can do is still you know have the option have is still you know have the option have the amount intact and then just pop out the amount intact and then just pop out one of the options and the other branch one of the options and the other branch is going to be the amount subtracted by is going to be the amount subtracted by the last options the order of the the last options the order of the options being popped out really doesn't options being popped out really doesn't matter just for convenience purpose I'm matter just for convenience purpose I'm putting it to us as if we're we're putting it to us as if we're we're removing the last one or we can remove removing the last one or we can remove the remove the first one - so the the the remove the first one - so the the problem basically being broke down into problem basically being broke down into two sub problems the this first sub two sub problems the this first sub problem is the same amount but with one problem is the same amount but with one last option the second sub problem is last option the second sub problem is that we reduce the amount by the first that we reduce the amount by the first option by by the first option you know option by by the first option you know this has to be aligned with the one that this has to be aligned with the one that being popped out so if we pop front we being popped out so if we pop front we have to reduce the amount by the first have to reduce the amount by the first option by the front coins value and to option by the front coins value and to have the options intact so that's how we have the options intact so that's how we that's this transition formula the base that's this transition formula the base case is going to be if we don't have any case is going to be if we don't have any amount the amount is zero we return one amount the amount is zero we return one that means we reached the we that means we reached the we successfully reduce the amount into zero successfully reduce the amount into zero so we find one combination so that's the so we find one combination so that's the base case base case so whatever the options we have that's so whatever the options we have that's gonna be one or we still have some gonna be one or we still have some amount that's greater than zero but we amount that's greater than zero but we run out of four options run out of four options let's just use an empty cell here to let's just use an empty cell here to indicate that then we want to return indicate that then we want to return zero meaning that's it's not feasible so zero meaning that's it's not feasible so there's no not not one but zero there's no not not one but zero combinations through this searching so combinations through this searching so that's that's the base case all right that's that's the base case all right what else run out of the choice or or what else run out of the choice or or another one if we just choose one another one if we just choose one options that's just so happened to options that's just so happened to reduce the amount to be negative whatever the options we have remained it's gonna be zero as well so that's the three base case so I'm gonna just cope this top-down version a top-down version recursive version using some lazy man's memorization method in Python just for this make change a month and we are using an index instead of actually plopping callings so this is I here means we consider coins index I and on towards the end so that's a faculty popping out the first one the reason for so for two using this the arguments to so for two using this the arguments to the function has to be hashable hash Bo the function has to be hashable hash Bo so so I think a list is not so that is so so I think a list is not so that is why I'm using an index to indicating why I'm using an index to indicating what what options has been element what what options has been element eliminated in the in using this eliminated in the in using this according to this formula so just gonna according to this formula so just gonna copy this function this transition copy this function this transition function here translate that into code [Music] so the first branch supportin is the same amount but with one less option so that's why plus 1 the second the branch is we change among abstracted by the first available coin that's currently in our odd-numbered disposal so it's coins right and have the I to be the same still have all the options from I and all so that's the recursive relationship of the transition function and we just kind of put three different base case here so if a month I don't the other one actually can be combined so this is run out of the coins so eliminate all the options of coins or amount is less than zero zero so that's just to use this function to calculate requirements we're going to passing the full amount initial amount and saying that we consider all the options from 0 and lots of all the options this cash is going to handle whatever it is calculating some some arguments and actually return a number that's going to cash that combination so putting this to us the keys and so that little when doing the recursive call it's going to use the already cached Evalia so that's a lazy man's memorization in Python so all right so this is the top-down all right so this is the top-down approach the tricky part is to have the approach the tricky part is to have the correct some father setup it's important correct some father setup it's important to realize the sequential order of how to realize the sequential order of how the coins are picked is not does not the coins are picked is not does not matter in this case if it that makes if matter in this case if it that makes if that that's that sequential order that that's that sequential order actually matters the the problem is much actually matters the the problem is much easier so all we have is the amount easier so all we have is the amount subtracted by the option just for how subtracted by the option just for how many options we have we break that into many options we have we break that into how many branches that would be this how many branches that would be this naive kind of a setup it will be a easy naive kind of a setup it will be a easy level question instead of this one this level question instead of this one this one is a medium so let's talk about how one is a medium so let's talk about how we do this from the bottom and button up we do this from the bottom and button up if we analyze this recursive really of if we analyze this recursive really of the transitional function it's a two the transitional function it's a two dimensional one we have the options and dimensional one we have the options and the amount so let's just say that the the amount so let's just say that the options are the the so the amount is the options are the the so the amount is the rose and the the options is the columns rose and the the options is the columns note that you know on this based on this note that you know on this based on this transition function we have the options transition function we have the options pop front that's basically saying that pop front that's basically saying that we are looking at a previous row sorry we are looking at a previous row sorry options is the current previous column options is the current previous column and the samsam rule here is the same and the samsam rule here is the same column but some previous rows so the the column but some previous rows so the the the immediate previous row so we're the immediate previous row so we're dropping one of the options here we drop dropping one of the options here we drop in deducing the yeah it's the same in deducing the yeah it's the same column previous row some previous row column previous row some previous row here is the previous Colin Sam Sam Sam here is the previous Colin Sam Sam Sam row so we noticed that this is actually row so we noticed that this is actually can be compressed to be a single single can be compressed to be a single single DP single one DP single one it's not even though it has two options it's not even though it has two options but although here is the you know the but although here is the you know the Sam Colin some previous row or the same Sam Colin some previous row or the same row previous Colin immediately previous row previous Colin immediately previous column so it's a can be space optimized column so it's a can be space optimized using a single single one D D P so using a single single one D D P so instead of doing the 2d table tabulation instead of doing the 2d table tabulation I'm just going to do a lot one I'm just going to do a lot one dimensional and if we only if we dimensional and if we only if we consider about the relationship here consider about the relationship here it's additive so it's not taking me a it's additive so it's not taking me a max and anything so we actually don't max and anything so we actually don't need to store the previous column all we need to store the previous column all we need to do is just work row by row need to do is just work row by row inside this Colin that was just adding inside this Colin that was just adding the number adding the number and that the number adding the number and that would be be done so we worked this Colin would be be done so we worked this Colin by Colin so Colin value by value and for by Colin so Colin value by value and for each value we we're looking at the each value we we're looking at the different amount and just add the number different amount and just add the number based on this formula right so that that based on this formula right so that that would be the solution so yeah so let's would be the solution so yeah so let's do this actually to reason about this I do this actually to reason about this I think we should we could just transpose think we should we could just transpose that so that it become a little bit more that so that it become a little bit more intuitive when we reason about that in intuitive when we reason about that in 1d so let's just use a row as the yes 1d so let's just use a row as the yes yes we're gonna keep our row but it's yes we're gonna keep our row but it's going to be rotated to be a vector ring so the base case is going to be here so Rho is the amount so we have a zero so Rho is the amount so we have a zero to the total amount so that's why I'm to the total amount so that's why I'm transposing that to have have that here transposing that to have have that here and I'm just going to doing that column and I'm just going to doing that column by column so if I'm gonna go beyond the by column so if I'm gonna go beyond the actual amount I should break otherwise actual amount I should break otherwise I'm just gonna go and go ahead and I'm just gonna go and go ahead and updating that so this is pretty much just a function of amount is equal to function of amount subtracted by the calling value and that so it's a this but we are doing instead of dis abstraction we are doing the you know addition so it's kind of a reverse this is top-down this formula record it's basically the button up in the reversed ordering of how this works we are not adding another second term because that second term is going to be handled in the next iteration for different type of coin so that's that well the for the return is just going to be returning the last item there so sumit okay working too so so that's a sumit okay working too so so that's a converting from top down to button up we converting from top down to button up we analyze this here we realize even though analyze this here we realize even though it's a 2d but we can compress that into it's a 2d but we can compress that into to be a single one-dimensional and so so to be a single one-dimensional and so so the way to think about this system this the way to think about this system this is going to be handled by the previous is going to be handled by the previous iteration over the coins and this one is iteration over the coins and this one is going to be when we handle for this going to be when we handle for this particular coin here all right so that's particular coin here all right so that's this question today | 2024-03-22 16:32:59 | 518 | Leetcode 518 Coin Change II |
|
3OxgmzezTG8 | [Applause] hello and welcome today we'll be doing a hello and welcome today we'll be doing a question from weeks ago called K closest question from weeks ago called K closest points to origin is a medium let's get points to origin is a medium let's get started so we have a list of points on started so we have a list of points on the plane find the K closest points to the plane find the K closest points to the origin 0 0 here the distance between the origin 0 0 here the distance between two points on a plane is a Euclidean two points on a plane is a Euclidean distance so that's just x squared plus y distance so that's just x squared plus y squared square root of that you may squared square root of that you may return the answer in any order the return the answer in any order the answer is guaranteed to be unique except answer is guaranteed to be unique except for the order that it is in example 1 for the order that it is in example 1 given points 1 3 and I give 2 to K given points 1 3 and I give 2 to K equals 1 we output negative 2 to Y equals 1 we output negative 2 to Y because the distance between 1 3 is because the distance between 1 3 is square root of 1 plus 9 or square root square root of 1 plus 9 or square root of 10 and 4 negative 2 2 it is square of 10 and 4 negative 2 2 it is square root of 8 so in square root of 8 is less root of 8 so in square root of 8 is less than square root of 10 we return than square root of 10 we return negative 2 to the second example given negative 2 to the second example given points 3 3 5 negative 1 negative 2 for K points 3 3 5 negative 1 negative 2 for K equals 2 we can return either negative 3 equals 2 we can return either negative 3 3 negative 2 4 sorry 3 3 negative 2 4 or 3 negative 2 4 sorry 3 3 negative 2 4 or negative 2 4 3 3 since order doesn't negative 2 4 3 3 since order doesn't matter um okay so this is fairly simple matter um okay so this is fairly simple the easiest approach to this would just the easiest approach to this would just be sorting the list of points based on be sorting the list of points based on their Euclidean distance taking that their Euclidean distance taking that sorted list and slicing on K or turning sorted list and slicing on K or turning that this will take and log n because we that this will take and log n because we do want to sort but is there a way we do want to sort but is there a way we can do better we can actually do it in can do better we can actually do it in linear time o of N and it's this phrase linear time o of N and it's this phrase right here you may return the answer in right here you may return the answer in any order we're going to be taking any order we're going to be taking advantage of so if you've ever done advantage of so if you've ever done quick find quick select or if you know quick find quick select or if you know how quicksort works we're going to be how quicksort works we're going to be using the same principle here so let's using the same principle here so let's take a look at a few examples first take a look at a few examples first suppose were given points such that suppose were given points such that their distances come out to be 2 5 4 3 & their distances come out to be 2 5 4 3 & 6 and suppose K is 3 now of course we 6 and suppose K is 3 now of course we can just sort you know 2 3 4 5 6 return can just sort you know 2 3 4 5 6 return 2 3 4 2 3 4 but what I'm gonna do instead I'm gonna but what I'm gonna do instead I'm gonna pick a random point and call it my pivot pick a random point and call it my pivot suppose I pick five now I'm going to go suppose I pick five now I'm going to go through and see how all other numbers through and see how all other numbers compared to my pivot if there are less compared to my pivot if there are less than the pivot I'm going to store it in than the pivot I'm going to store it in left there greater than it I'm going to left there greater than it I'm going to store it in right so in the end the store it in right so in the end the order would be left then pivot and then order would be left then pivot and then right right so when left I would have two four and so when left I would have two four and three in my right I would just have six three in my right I would just have six now what do we notice about the lengths now what do we notice about the lengths of these lists of these lists left is three it is just the one element left is three it is just the one element one and right is also one but we can one and right is also one but we can just return left as is because we know just return left as is because we know left is less than pivot which is less left is less than pivot which is less than right so it's left if the length of than right so it's left if the length of left three equals K then we can just left three equals K then we can just return left because we know those are return left because we know those are three closest points and if K equals 4 three closest points and if K equals 4 then we can apply the same logic we then we can apply the same logic we already have left during T to be less already have left during T to be less than pivot and right and we also have than pivot and right and we also have pivot guaranteed to be less than right pivot guaranteed to be less than right so we have 3 plus 1 4 we have our 4 so we have 3 plus 1 4 we have our 4 closest elements and there's something closest elements and there's something really cool going on here right so if I really cool going on here right so if I actually sorted this list 2 3 4 5 6 actually sorted this list 2 3 4 5 6 where is 5 located it's in its true where is 5 located it's in its true ordered position and with this when I ordered position and with this when I did left pivot right it was the same did left pivot right it was the same position 5 is in now so I had 2 4 3 then position 5 is in now so I had 2 4 3 then 5 and then 6 so what does it mean to be 5 and then 6 so what does it mean to be sorted right if I have a list and I say sorted right if I have a list and I say it's sorted it means that every element it's sorted it means that every element is in a place such that all the elements is in a place such that all the elements before it are less than the element that before it are less than the element that almonds after it are greater than the almonds after it are greater than the element but in this case we don't want element but in this case we don't want to apply it to all elements we just want to apply it to all elements we just want to apply it to our pivot and that is how to apply it to our pivot and that is how we're saving time so to go back to our we're saving time so to go back to our example suppose K wasn't foreign it was example suppose K wasn't foreign it was - and yet still pigs pivot 5 what do we - and yet still pigs pivot 5 what do we do now well we don't actually want to do now well we don't actually want to pass in the whole list again if you just pass in the whole list again if you just pass in left and our same cage equaling pass in left and our same cage equaling - so in this case we just pass in 2 for - so in this case we just pass in 2 for 3 and apply the same thing again so I 3 and apply the same thing again so I pick another pivots holes I pick 4 pick another pivots holes I pick 4 well then my left would have 2 and 3 and well then my left would have 2 and 3 and my right we just had nothing so in this my right we just had nothing so in this case I see that the length of left is 2 case I see that the length of left is 2 which equals K and I would return and which equals K and I would return and end there but what if K wasn't - what if end there but what if K wasn't - what if it was 5 let's do 6 suppose we have it was 5 let's do 6 suppose we have another element here 7 so 7 would go on another element here 7 so 7 would go on the right and this one can be 2 so we the right and this one can be 2 so we still pick 5 as our original pivot what still pick 5 as our original pivot what do we do now well now we only need to do we do now well now we only need to pass in whatever is in right so now we pass in whatever is in right so now we passing right and for K we actually set passing right and for K we actually set it equal to K - length of left - 1 and it equal to K - length of left - 1 and why are we doing this because we already why are we doing this because we already know we have our 4 closest taking into know we have our 4 closest taking into account both left and pivot so we need account both left and pivot so we need whatever is left from right so if K whatever is left from right so if K equals 6 we have 6 minus pole end of equals 6 we have 6 minus pole end of left which is 3 - whatever the pivot is left which is 3 - whatever the pivot is which is just 1 so this equals 6 minus 2 which is just 1 so this equals 6 minus 2 minus 1 or sorry left was 3 so this was minus 1 or sorry left was 3 so this was 6 minus 3 minus 1 which is 6 minus 4 and 6 minus 3 minus 1 which is 6 minus 4 and this equals 2 so now we pass in right 6 this equals 2 so now we pass in right 6 & 7 8 equals 2 and we just return that & 7 8 equals 2 and we just return that and this is how the logic would go now and this is how the logic would go now let's take a moment to understand why let's take a moment to understand why this is faster and for that I'm actually this is faster and for that I'm actually going to start off by saying it's not going to start off by saying it's not always fast always fast what if we run into the worst case so what if we run into the worst case so going back to this example what if our going back to this example what if our first pivot we picked was 7 and we first pivot we picked was 7 and we wanted K equaling 1 so the first pivot wanted K equaling 1 so the first pivot is 7 well then we need to make is 7 well then we need to make comparisons with 2 5 4 3 & 6 so that's 5 comparisons with 2 5 4 3 & 6 so that's 5 comparisons so then we take in our left comparisons so then we take in our left and pass it in again so close now our and pass it in again so close now our pivot is 6 which case we're going to be pivot is 6 which case we're going to be making comparisons with 2 5 4 & 3 so making comparisons with 2 5 4 & 3 so forth and now we pick pivot 5 we make 3 forth and now we pick pivot 5 we make 3 comparisons and so forth until we find K comparisons and so forth until we find K in this case 1 so in this case we would in this case 1 so in this case we would be doing n minus 1 up until 1 and be doing n minus 1 up until 1 and summing all of that up we know it's n summing all of that up we know it's n into n minus 1 over 2 which is N squared into n minus 1 over 2 which is N squared order of N squared which is much worse order of N squared which is much worse than n log n however this is just the than n log n however this is just the worst-case amortize on average we can worst-case amortize on average we can approximately say we get around path approximately say we get around path each time we pick up ticket so we pick each time we pick up ticket so we pick up pivot so that it divides the input up pivot so that it divides the input list into hat each time so the first list into hat each time so the first time we would go check n elements then time we would go check n elements then make another comparison with about + / - make another comparison with about + / - since supposing our first pivot dividing since supposing our first pivot dividing hat then if we still haven't found our hat then if we still haven't found our answer divide in half again and keep answer divide in half again and keep going until we really find it and this going until we really find it and this is just a geometric sequence that is just a geometric sequence that converges to 2 n which is order n which converges to 2 n which is order n which is better than n log n so this is the is better than n log n so this is the main concept for it let's just go ahead main concept for it let's just go ahead and code this up now the first thing I'm and code this up now the first thing I'm going to do is write a list of tuples going to do is write a list of tuples taking in the points and their distances taking in the points and their distances so for that I'm going to make a helper so for that I'm going to make a helper function to find the distance for the function to find the distance for the points point turn swear and the reason I'm not gonna ask where beat this again is because it's an unnecessary step of computation if I have a hundred and then I had 64 I know 100 is greater than 64 the square root 10 is also greater than 8 so squaring or square rooting doesn't really change that relationship since we're dealing with positive numbers so I'm gonna do Alice team I'm so consistent on this I before I and now I'm going to call my name function and okay let's write this up and if the input list has a length of K then I can just return that so it went okay now I'm gonna do i of 0 because we want to return the actual points not the distances so the points were stored in that zero with index and if this is not true so if the lens does not equal K then we won't apply our logic so for that I'm going to import random you have a random tuple from this list and now I'm just gonna go ahead and neutralize everything so empty empty in fact I'm gonna make another list of equal and the reason I'm doing this is if you read the question again the answer is guaranteed to be unique except for the order that it is in so if we have five points all with the same distance and K equals two I can then pick any two from the five and the answer were not unique so that can never happen so if I come across points in which their distance is equal to the pivot then I know either all of them have to be included in our answer or none of them will be included in our answer because otherwise we would be only picking some out of the whole people which just won't happen so this can actually save this commutation by keeping another list for equal so now while I less than munch probability if our different point that were looking at one well if this distance is less than one well if this distance is less than the pivot the pivot I mean appended to the left appendix I mean appended to the left appendix equal else if the distance is greater equal else if the distance is greater than the pivot I added to the right after this while loop is over we have everything in left people right when I just wanted to check the length so if this equals K well then I just want our return so I'm going to use the same return I had up here and return it except only for left this one and if the people stay and I'm gonna do the same people stay and I'm gonna do the same return over here with the addition of return over here with the addition of equal so same thing equal so same thing but this time on people and if K is less but this time on people and if K is less than left I'm just gonna call this than left I'm just gonna call this function again so the salt off you find function again so the salt off you find its return on left and pass on K again its return on left and pass on K again and Ellis if we know it's not less than and Ellis if we know it's not less than K not equal to K and not equal to k plus K not equal to K and not equal to k plus whatever is in equal then it has to be whatever is in equal then it has to be greater than whatever isn't a plus equal greater than whatever isn't a plus equal in which case I return will be half from in which case I return will be half from left what we have from equal and then left what we have from equal and then whatever else I need from right so I'm whatever else I need from right so I'm gonna return this plus sulphate dot find gonna return this plus sulphate dot find on right with pay - length of left - on right with pay - length of left - lend of equal and that's about it so you lend of equal and that's about it so you can run this phone now eridan cookies alright so accepted it and it is accepted it's faster than 74 and it is accepted it's faster than 74 percent of other Python three percent of other Python three submissions um before I leave I want to submissions um before I leave I want to talk about another optimization you can talk about another optimization you can make you can actually do this in make you can actually do this in constant space as well right now we're constant space as well right now we're storing extra arrays for left-right storing extra arrays for left-right equal you can actually do this in place equal you can actually do this in place just running Dutch flag I did this about just running Dutch flag I did this about what three hours ago just to see the what three hours ago just to see the difference we worsened in runtime but difference we worsened in runtime but memory improved slightly if you want to memory improved slightly if you want to know more about that let me know I can know more about that let me know I can like talk about how I did it make like talk about how I did it make another video about leaf invariants and another video about leaf invariants and the algorithm I use for that or just the algorithm I use for that or just show you the code for that otherwise if show you the code for that otherwise if you don't have any questions all see you you don't have any questions all see you next time next time [Music] | 2024-03-25 14:11:59 | 973 | K Closest Points to Origin - LeetCode 973 - Python [O(n) time!] |
|
gqXU1UyA8pk | hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today we're going to solve we're going to solve longest repeating character replacement longest repeating character replacement and so this is another problem from that and so this is another problem from that blind 75 list blind 75 list so we are going to be one step closer to so we are going to be one step closer to completing the entire list completing the entire list the link will be in the description to the link will be in the description to this spreadsheet if you do want to take this spreadsheet if you do want to take a look a look and hello to the six people that are and hello to the six people that are currently viewing the currently viewing the spreadsheet right now you're gonna be in spreadsheet right now you're gonna be in the next video but okay so let's get the next video but okay so let's get into this problem because it's another into this problem because it's another pretty fundamental problem that's really pretty fundamental problem that's really good to understand so we're given a good to understand so we're given a string string s and a single integer k and so s and a single integer k and so basically they tell us that we can basically they tell us that we can choose choose any of the characters in the string and any of the characters in the string and change it to any other uppercase english change it to any other uppercase english character so in this problem character so in this problem every character in the input string is every character in the input string is going to be limited to uppercase english going to be limited to uppercase english characters and we know that there's 26 characters and we know that there's 26 uppercase english characters from uppercase english characters from capital a to capital z capital a to capital z and so basically we can perform a and so basically we can perform a replacement on replacement on any of the characters at most k times any of the characters at most k times so we are allowed to replace k different so we are allowed to replace k different characters in the string to any other characters in the string to any other character we want character we want and what we want to do is return the and what we want to do is return the length of the length of the longest substring containing the exact longest substring containing the exact same character we can get after same character we can get after performing performing at most k different replacements at most k different replacements so we just want to return that length we so we just want to return that length we don't actually have to make those don't actually have to make those replacements in the input string replacements in the input string so in this case when we take a look at so in this case when we take a look at the input string we have a the input string we have a b a b and we're allowed to replace two b a b and we're allowed to replace two of the characters of the characters so what's the longest substring we could so what's the longest substring we could get with the exact same character well get with the exact same character well we could replace we could replace one of the b's we could basically one of the b's we could basically replace both of the b's replace both of the b's with a capital a and then we get four with a capital a and then we get four a's in a row a's in a row which would give us an output of four which would give us an output of four and we could technically also do the and we could technically also do the opposite we could replace the a's opposite we could replace the a's with capital b's and that would give us with capital b's and that would give us the exact same result a length of four the exact same result a length of four so i'm going to show you how you can so i'm going to show you how you can solve this problem in big solve this problem in big o of n time and technically it's going o of n time and technically it's going to be big o of to be big o of 26 multiplied by n which we know is also 26 multiplied by n which we know is also reduces to reduces to big o of n but there's actually big o of n but there's actually technically an easier technically an easier way to do it or at least a more simple way to do it or at least a more simple way to do it which is just going to be way to do it which is just going to be a flat big o of n we don't even need a flat big o of n we don't even need this 26 constant this 26 constant but this way is actually pretty tricky but this way is actually pretty tricky to get to to get to so i'll be going over a little bit of it so i'll be going over a little bit of it but this is kind of the main way that but this is kind of the main way that you'd want to solve this problem you'd want to solve this problem so let's say we're given an input string so let's say we're given an input string like this and we're given a k value now like this and we're given a k value now the most brute force way would just be the most brute force way would just be check every single substring right check every single substring right and if we were checking every single sub and if we were checking every single sub string in the entire input array we know string in the entire input array we know there's n squared sub string so that there's n squared sub string so that wouldn't be the simple wouldn't be the simple that wouldn't be the most efficient way that wouldn't be the most efficient way to do it but even if we were doing it to do it but even if we were doing it like that what exactly are we like that what exactly are we looking for if we're looking at a looking for if we're looking at a particular substring particular substring how do we know if this substring is how do we know if this substring is valid because remember at the end of the valid because remember at the end of the day day we want to maximize the result right the we want to maximize the result right the result is going to be the longest result is going to be the longest sub string that contains a single sub string that contains a single character and we can make character and we can make two replacements so let's look at this two replacements so let's look at this substring alone substring alone how do we know if it's valid well which how do we know if it's valid well which character are we going to replace are we character are we going to replace are we going to want to replace the b's going to want to replace the b's in order to make it all be amount to in order to make it all be amount to match a or would we want to replace the match a or would we want to replace the a in order to match it with the rest of a in order to match it with the rest of the b's the b's of course we're going to replace the of course we're going to replace the character that occurs less frequently character that occurs less frequently right because the number of replacements right because the number of replacements we have is we have is limited so we would want to replace the limited so we would want to replace the character character that the characters that are less that the characters that are less frequent so in other words frequent so in other words we want all characters in a particular we want all characters in a particular window to window to match the most common character match the most common character in that window so what we're going to be in that window so what we're going to be doing is we are going to have a doing is we are going to have a hash map or a array which is going to hash map or a array which is going to take take every single character in this case we every single character in this case we only have characters a and b only have characters a and b and we're going to count the number of and we're going to count the number of occurrences of each character occurrences of each character so for example if we were looking at so for example if we were looking at this substring we see that there's three this substring we see that there's three b's and we have a single b's and we have a single a so how do we know if this window is a so how do we know if this window is valid what we're gonna do is we're gonna valid what we're gonna do is we're gonna take take the length of the window which is gonna the length of the window which is gonna be four be four right we're gonna take the length of the right we're gonna take the length of the window right which we know in this case window right which we know in this case is four is four and we're gonna take the length or the and we're gonna take the length or the count of the most frequent character in count of the most frequent character in this case this case we know that that's b and the count of we know that that's b and the count of it happens to be it happens to be three so we're gonna take four minus three so we're gonna take four minus three and three and from that we're gonna get a one now what from that we're gonna get a one now what does this value one tell us does this value one tell us it tells us the number of characters in it tells us the number of characters in our window right our window right now that we need to replace in order to now that we need to replace in order to make it make it match the most frequent character b match the most frequent character b right we have a b here right we have a b here we want everything to match a b in this we want everything to match a b in this case we only have an a right but it case we only have an a right but it could be possible like could be possible like who knows maybe that we would have a c who knows maybe that we would have a c over here right or an x over here right or an x over here and it doesn't really matter over here and it doesn't really matter what the characters what the characters are we just know that b is the most are we just know that b is the most frequent character in the window frequent character in the window and the other characters that are not b and the other characters that are not b a and z a and z for example are the characters we want for example are the characters we want to replace so we can calculate the to replace so we can calculate the number of characters we want to pull number of characters we want to pull that we want to replace just like this that we want to replace just like this and so so we want to replace one and so so we want to replace one character how do we know if we have character how do we know if we have enough enough replacements to do one character well of replacements to do one character well of course that's our input parameter course that's our input parameter k right so what we're confirming here is k right so what we're confirming here is that that this value is less than or equal to this value is less than or equal to k as long as this condition is true k as long as this condition is true that means our current window is valid that means our current window is valid that means we have enough replacements that means we have enough replacements to make those replacements to make those replacements in our current window so this is the in our current window so this is the main condition that we're going to be main condition that we're going to be checking the other question is how are checking the other question is how are we going to know which character is the we going to know which character is the most frequent well most frequent well the brute force way is gonna be taking a the brute force way is gonna be taking a look at our map look at our map of counts and we know that the max size of counts and we know that the max size of this could possibly be of this could possibly be 26 because we'd only have 26 different 26 because we'd only have 26 different characters characters so doing finding the max character is so doing finding the max character is going to be big o of 26 so that's going to be big o of 26 so that's a little bit more inefficient than we a little bit more inefficient than we would like but it's technically still would like but it's technically still linear time like the overall algorithm linear time like the overall algorithm is still going to be linear time is still going to be linear time the the last thing that we're gonna have the the last thing that we're gonna have to do though is to this to do though is to this uh equation we're gonna have to add a uh equation we're gonna have to add a sliding window technique so basically sliding window technique so basically what we're gonna do is we're gonna take what we're gonna do is we're gonna take our window our window start at the beginning expand it as much start at the beginning expand it as much as we can as long as the as we can as long as the the condition that we mentioned is valid the condition that we mentioned is valid if the condition is not valid then we're if the condition is not valid then we're going to take our left pointer going to take our left pointer and then take our left pointer and then and then take our left pointer and then shift it as well shift it as well until the string becomes valid once until the string becomes valid once again again so we're going to have a left and right so we're going to have a left and right pointer so initially left is gonna be at pointer so initially left is gonna be at the beginning and the beginning and right is also gonna be at the beginning right is also gonna be at the beginning and also the counts of a and also the counts of a and b are initially gonna be zero now and b are initially gonna be zero now we're gonna look at the first character we're gonna look at the first character right right that's where our right pointer happens that's where our right pointer happens to be we're gonna look at it we're gonna to be we're gonna look at it we're gonna say okay we have a say okay we have a we have a single a right we're going to we have a single a right we're going to take our count of a take our count of a and set it to 1 now so is this and set it to 1 now so is this window valid as in can this window be window valid as in can this window be the exact same character the exact same character with within two replacements of course with within two replacements of course it can right that's kind of the trivial it can right that's kind of the trivial case but case but we would still calculate it and the way we would still calculate it and the way we would calculate it is get the size of we would calculate it is get the size of our window right now we can see the size our window right now we can see the size of our window is of our window is one subtracted by the count of one subtracted by the count of the most frequent character in this case the most frequent character in this case we know the most frequent character is a we know the most frequent character is a one minus one one minus one is that greater is that less than or is that greater is that less than or equal to k we know k is two so of course equal to k we know k is two so of course uh this is going to equal zero zero is uh this is going to equal zero zero is less than equal to two which is k less than equal to two which is k right so of course this window is valid right so of course this window is valid that's kind of a trivial case that's kind of a trivial case next we're going to shift our right next we're going to shift our right pointer to the next character right pointer to the next character right so now we have a b so we're going to so now we have a b so we're going to increment the count of b in our map increment the count of b in our map so b is now going to be set to 1. in so b is now going to be set to 1. in this case the length of our window is 2 this case the length of our window is 2 the most frequent character is either of the most frequent character is either of these right and the these right and the the count of that frequent character is the count of that frequent character is gonna be one so we're gonna have two gonna be one so we're gonna have two minus one equal to one minus one equal to one so this is the number of replacements so this is the number of replacements that we would have to do and that we would have to do and looking at our current window that makes looking at our current window that makes sense right we'd have to replace at sense right we'd have to replace at least one of these two characters least one of these two characters so we're going to ensure that this the so we're going to ensure that this the number of replacements that we need to number of replacements that we need to do is less than or equal to k which is do is less than or equal to k which is two of course that's true so two of course that's true so our window is currently valid i guess i our window is currently valid i guess i did forget to did forget to update our result so since this window update our result so since this window is valid the length of the window is is valid the length of the window is gonna be gonna be set to the result right so right now the set to the result right so right now the result is two two is the length of the result is two two is the length of the longest window that we can get longest window that we can get so that's our result for now so now so that's our result for now so now let's continue next we're gonna shift let's continue next we're gonna shift our right pointer to the third character our right pointer to the third character so now so now we get another a so we're gonna take the we get another a so we're gonna take the count of a count of a and increment it all the way to two and and increment it all the way to two and we're basically going to repeat our we're basically going to repeat our algorithm so once again we're gonna get algorithm so once again we're gonna get the length of the window three minus the the length of the window three minus the count of the most frequent character we count of the most frequent character we see the most frequent character is see the most frequent character is a so the count of is two three minus two a so the count of is two three minus two is one is one is that less than or equal to two which is that less than or equal to two which is k yes of course it is so is k yes of course it is so this window is also valid we can update this window is also valid we can update our result now to three so we found our result now to three so we found another window even longer so i'm going another window even longer so i'm going to take to take our right pointer once again and then our right pointer once again and then shift it over to the b shift it over to the b so now we're going to be since we so now we're going to be since we reached another b we're going to reached another b we're going to increment the count of b increment the count of b to 2 now and so the length of our window to 2 now and so the length of our window now is 4 now is 4 and the count of the most frequent and the count of the most frequent character is either of these and that's character is either of these and that's going to be 2 going to be 2 4 minus 2 is equal to 2. is that less 4 minus 2 is equal to 2. is that less than or equal to k than or equal to k k is 2 in this case so of course once k is 2 in this case so of course once again this condition does hold so again this condition does hold so once again we found a window that's once again we found a window that's longer than our result we found a window longer than our result we found a window now of length now of length four and so once again we're going to four and so once again we're going to take our right pointer and shift it so take our right pointer and shift it so now now another b let's increment the count of b another b let's increment the count of b to three so the length of the window now to three so the length of the window now is five is five minus the count of the most frequent minus the count of the most frequent character charac that character is b character charac that character is b five minus three is this two in that and five minus three is this two in that and less than or equal to k less than or equal to k of course it's still true because when of course it's still true because when you look at our window you look at our window we have three b's so that means we're we have three b's so that means we're going to be replacing the a's going to be replacing the a's so we're gonna need to make two so we're gonna need to make two replacements and we are allowed to make replacements and we are allowed to make two replacements two replacements okay so now we're finally gonna get to okay so now we're finally gonna get to the case that i mentioned earlier where the case that i mentioned earlier where we're gonna have to take our left we're gonna have to take our left pointer and then slide it to the right pointer and then slide it to the right which is why this is a sliding window which is why this is a sliding window problem so now we reached an problem so now we reached an a so we're gonna take the count of a and a so we're gonna take the count of a and set it to three so now we have a set it to three so now we have a count three and b count three so let's count three and b count three so let's take the size of our window six take the size of our window six subtract from it the count of the most subtract from it the count of the most frequent character it's gonna be frequent character it's gonna be either of these so six minus three means either of these so six minus three means we need to make three replacements we need to make three replacements is that less than or equal to k k is two is that less than or equal to k k is two so we exceeded k right we exceeded the so we exceeded k right we exceeded the number of replacements we're allowed to number of replacements we're allowed to make make if we wanted this window to be valid we if we wanted this window to be valid we have to replace three characters in it have to replace three characters in it but we're not allowed to do that so what but we're not allowed to do that so what we have to do we have to do is shrink the size of our window until is shrink the size of our window until we we are valid so we're going to take our are valid so we're going to take our left pointer and left pointer and shift it to the right so now the left shift it to the right so now the left pointer is going to be over here it's pointer is going to be over here it's going to be at the b going to be at the b so since we removed this a from our so since we removed this a from our window window we have to decrement the count of a in we have to decrement the count of a in our window so i'm going to cross this our window so i'm going to cross this three out and now it's three out and now it's actually going to be set to 2. i kind of actually going to be set to 2. i kind of ran out of room but i hope this is still ran out of room but i hope this is still readable readable so now the count of a is two so now so now the count of a is two so now let's once again let's once again check is our window valid well the size check is our window valid well the size of the window now is of the window now is five and the count of the most frequent five and the count of the most frequent character is character is b and that's gonna be three so five b and that's gonna be three so five minus three is gonna be equal to two minus three is gonna be equal to two is that less than or equal to k yes we is that less than or equal to k yes we are once again are once again valid so this is technically a valid valid so this is technically a valid window and i think i forgot to update window and i think i forgot to update the result earlier when we had a window the result earlier when we had a window of size five so of size five so the result right now would be size five the result right now would be size five because the longest window we can make because the longest window we can make is either this window or the window that is either this window or the window that we had we had uh earlier with you know these first uh earlier with you know these first five characters five characters but yeah and so at this point we would but yeah and so at this point we would stop our algorithm because we did find a stop our algorithm because we did find a window of window of 5 that is valid and our right pointer 5 that is valid and our right pointer cannot be shifted cannot be shifted anymore so this is the general algorithm anymore so this is the general algorithm so it's a basic sliding it's a so it's a basic sliding it's a fundamental sliding window problem with fundamental sliding window problem with this particular condition this particular condition being important but there's actually one being important but there's actually one way you can do it without way you can do it without having to look through the entire having to look through the entire hashmap hashmap every time you want to find the most every time you want to find the most frequent character frequent character that occurs and it's kind of tricky that occurs and it's kind of tricky to arrive at the solution but it's to arrive at the solution but it's pretty easy to implement once you can pretty easy to implement once you can figure it out figure it out i'll explain the algorithm at a high i'll explain the algorithm at a high level i don't want to waste too much level i don't want to waste too much time on it but basically we're going to time on it but basically we're going to be having another variable be having another variable and it's going to be called max and it's going to be called max frequency basically the count of the frequency basically the count of the most frequent character at any given most frequent character at any given time time so basically you know for example if we so basically you know for example if we had a as had a as a count of three and b is count two we'd a count of three and b is count two we'd say okay the count of the mo say okay the count of the mo the most frequent character occurs three the most frequent character occurs three times so max f is going to be three times so max f is going to be three and so any time you know if we got a b and so any time you know if we got a b we inc we inc let's say we incremented our b all the let's say we incremented our b all the way up to four then we want to update way up to four then we want to update our max frequency to four right so we'd our max frequency to four right so we'd always want this to be the most frequent always want this to be the most frequent character character now the one problem is if we're trying now the one problem is if we're trying to maintain the count of the most to maintain the count of the most frequent character frequent character what happens when we take our left what happens when we take our left pointer for example right and then pointer for example right and then shift it right when we do that we're shift it right when we do that we're basically removing a character basically removing a character and therefore we're gonna have to update and therefore we're gonna have to update our count map right we are gonna do that our count map right we are gonna do that but and if that does happen right let's but and if that does happen right let's say we took b and then say we took b and then from four we decremented it all the way from four we decremented it all the way down to down to two for example then we have to rescan two for example then we have to rescan this entire map this entire map and then find okay what's now what's the and then find okay what's now what's the new most frequent character right so new most frequent character right so we'd have to take our max frequency we'd have to take our max frequency and from four downgrade it all the way and from four downgrade it all the way to to a three for example so then we'd have to a three for example so then we'd have to set it to a three set it to a three but and that would basically defeat the but and that would basically defeat the purpose right we'd still have to do that purpose right we'd still have to do that big o of 26 calculation to scan through big o of 26 calculation to scan through this this but it's technically true that you but it's technically true that you don't have to decrement this max don't have to decrement this max frequency frequency but the main idea is this the result but the main idea is this the result is only going to be maximized as we find is only going to be maximized as we find a a new max frequency right because remember new max frequency right because remember what we were doing we were taking the what we were doing we were taking the length of the window length of the window subtracted by the max frequency right subtracted by the max frequency right whatever the most occurring character whatever the most occurring character was and we wanted to minimize this right was and we wanted to minimize this right so basically we want the so basically we want the length we want the length to be length we want the length to be maximized because that's what our result maximized because that's what our result is going to be set to is going to be set to so therefore we also want the max so therefore we also want the max frequency to be maximized because we frequency to be maximized because we want to ensure want to ensure that this is less than or equal to that this is less than or equal to k and k is going to be a constant k and k is going to be a constant so for example let's say i had a max so for example let's say i had a max frequency of four frequency of four but let's say now the new max frequency but let's say now the new max frequency got downgraded to a three i'm got downgraded to a three i'm still gonna leave this as a four because still gonna leave this as a four because it's not going to it's not going to change our result because for example if change our result because for example if i had a i had a 6 minus 4 that was that was less than or 6 minus 4 that was that was less than or equal to k which is 2 in our example equal to k which is 2 in our example and if i leave this as a 4 i'm basically and if i leave this as a 4 i'm basically overestimating what the max frequency is overestimating what the max frequency is but we know at least at but we know at least at one given point in time it was a four so one given point in time it was a four so therefore we were able to take the therefore we were able to take the length length six and then set it equal to our result six and then set it equal to our result and now and now if we're ever so let's say our result is if we're ever so let's say our result is now six if we're now six if we're ever going to increase the result from 6 ever going to increase the result from 6 to another to another number like for example 7 we would number like for example 7 we would require require our max frequency to increase if it our max frequency to increase if it stays the same stays the same or if it decreases our result is never or if it decreases our result is never going to change because we only change going to change because we only change our result our result when we increase our max frequency when we increase our max frequency because that's the only way because that's the only way this condition here is going to be true this condition here is going to be true so so if our max frequency is downgraded we if our max frequency is downgraded we don't have to actually update it we don't have to actually update it we don't have to look through the entire don't have to look through the entire hash map to find the new max hash map to find the new max frequency but if we increase our max frequency but if we increase our max frequency for example if i took this frequency for example if i took this a and then from three i set it equal to a and then from three i set it equal to a five a five then that's that's something we can then that's that's something we can check and big o of check and big o of one time and then if we increase this one time and then if we increase this then we definitely then we definitely do want to update our max frequency and do want to update our max frequency and increase it and that's something we can increase it and that's something we can do in big o of one time so do in big o of one time so i know i probably went a little too long i know i probably went a little too long into this but the main idea here into this but the main idea here i'm trying to get at is the easy way to i'm trying to get at is the easy way to solve this problem with a sliding window solve this problem with a sliding window is going to be big o is going to be big o of 26 times n which is technically of 26 times n which is technically linear but there is a linear but there is a clever way to do this in big o of end clever way to do this in big o of end time that honestly i didn't figure out time that honestly i didn't figure out on my own and i wouldn't really expect on my own and i wouldn't really expect other people to be able to figure it out other people to be able to figure it out on their own like in an interview at all on their own like in an interview at all but i will show this the standard but i will show this the standard solution and i'll also show the code for solution and i'll also show the code for this more optimized solution this more optimized solution okay so now let's jump into the code and okay so now let's jump into the code and the code is actually a lot easier than the code is actually a lot easier than the visual example that i gave a lot the visual example that i gave a lot shorter for sure so we're gonna have a shorter for sure so we're gonna have a hash map to count the occurrences hash map to count the occurrences of each character and we're also gonna of each character and we're also gonna have a result which is going to tell us have a result which is going to tell us the longest the longest substring that we can create with k substring that we can create with k replacements and we're going to have a replacements and we're going to have a left pointer which is going to be at 0 left pointer which is going to be at 0 and then our right pointer is going to and then our right pointer is going to go through every single position go through every single position in the entire string s so what we're in the entire string s so what we're going to do going to do is for the character at position r we're is for the character at position r we're going to increment the count of it going to increment the count of it we're going to take 1 plus whatever the we're going to take 1 plus whatever the count currently was count currently was count dot get this character and if the count dot get this character and if the character doesn't exist in our hash map character doesn't exist in our hash map we're just going to return a default we're just going to return a default value of zero that's what this function value of zero that's what this function is doing is doing and so before what we're going to and so before what we're going to obviously do is update our result right obviously do is update our result right and we want to set the result equal to and we want to set the result equal to the max that it's ever been the max that it's ever been and set it basically equal to the size and set it basically equal to the size of the window we can get the size of the of the window we can get the size of the window window so we're going to take the max of result so we're going to take the max of result and the size of the window the size of and the size of the window the size of the window can be gotten with the window can be gotten with right minus left plus one and right minus left plus one and but before we do this before we update but before we do this before we update the result we want to make sure that the the result we want to make sure that the current window is current window is valid so what i'm going to do is valid so what i'm going to do is basically say while and i don't think basically say while and i don't think you'd actually need a while here you you'd actually need a while here you could just do if but i'm just going to could just do if but i'm just going to do while just do while just because so while the window is not valid because so while the window is not valid and we would know that by taking the and we would know that by taking the length of the window which we have down length of the window which we have down here so i'm just going to copy and paste here so i'm just going to copy and paste that the length of the window that the length of the window subtracted by the most the count of the subtracted by the most the count of the most frequent character which can be most frequent character which can be gotten with max gotten with max of count dot values of count dot values right we're basically going through the right we're basically going through the hash map which could be size 26 and just hash map which could be size 26 and just getting the max value from it getting the max value from it so this is the number of replacements so this is the number of replacements that we have to do and if the number of that we have to do and if the number of replacements was replacements was greater than the number of replacements greater than the number of replacements that's allowed which is equal to k that's allowed which is equal to k that's when we would want to shift our that's when we would want to shift our left pointer so we'd want to increment left pointer so we'd want to increment our left pointer our left pointer but before we increment the left pointer but before we increment the left pointer we'd want to take the count of the we'd want to take the count of the character character at the left position and then decrement at the left position and then decrement it it by one and that is the entire algorithm by one and that is the entire algorithm after all of that is done after we've after all of that is done after we've gone through the entire string then we gone through the entire string then we can just simply return our result can just simply return our result and as you can see this is pretty and as you can see this is pretty efficient it's linear time it's about efficient it's linear time it's about as efficient as you would need i think as efficient as you would need i think but i'm going to make that slight but i'm going to make that slight optimization that i showed you i'm going optimization that i showed you i'm going to maintain the max frequency in a to maintain the max frequency in a single variable single variable so that we won't have to do this so that we won't have to do this operation where we're getting the max of operation where we're getting the max of the entire the entire hash map instead up here before we hash map instead up here before we execute that loop i'm going to say max execute that loop i'm going to say max frequency is going to be equal frequency is going to be equal to the max of what it currently is max to the max of what it currently is max frequency or frequency or it's equal to the frequency of the it's equal to the frequency of the character that we just added a value to character that we just added a value to maybe that character became the most maybe that character became the most frequent character frequent character so we would have to update our max so we would have to update our max frequency and we can do that frequency and we can do that just like this and this is a constant just like this and this is a constant time operation we're not scanning any time operation we're not scanning any list or anything list or anything and then once we have this max frequency and then once we have this max frequency we can use it in we can use it in this loop execution right so we can this loop execution right so we can replace this replace this and just use max f for that and the and just use max f for that and the thing is thing is notice how even when we're shifting left notice how even when we're shifting left we're incrementing the left pointer we're incrementing the left pointer we're potentially removing characters we're potentially removing characters from our window we're still not from our window we're still not decrementing max f because we actually decrementing max f because we actually don't need to don't need to it won't end up affecting the result if it won't end up affecting the result if we for if we just don't decrement it we for if we just don't decrement it and that very slight optimization which and that very slight optimization which is really simple is really simple in terms of code but it's kind of hard in terms of code but it's kind of hard to see why we're allowed to do that to see why we're allowed to do that watch how much more efficient it makes watch how much more efficient it makes our algorithm our algorithm so as you can see look it definitely so as you can see look it definitely improved it i think it was improved it i think it was 50 milliseconds different so this is 50 milliseconds different so this is significantly faster significantly faster it's hard to see why though i would it's hard to see why though i would definitely definitely not expect most people to be able to not expect most people to be able to figure that out figure that out so i hope that this was helpful if it so i hope that this was helpful if it was please like and subscribe it was please like and subscribe it supports the channel supports the channel a lot and i'll hopefully see you pretty a lot and i'll hopefully see you pretty soon thanks for watching | 2024-03-15 18:47:21 | 424 | Longest Repeating Character Replacement - Leetcode 424 - Python |
|
Ig2CdcRzWhg | hi everyone today i'm going to be solving the lead code question solving the lead code question search a 2d matrix search a 2d matrix so the problem is telling you to write so the problem is telling you to write an efficient algorithm that searches for an efficient algorithm that searches for a value target a value target in the m by n in the m by n integer matrix and you're sold and integer matrix and you're sold and you're told that it's already sorted so you're told that it's already sorted so the elements are sorted from left to the elements are sorted from left to right right and the first integer of each row is and the first integer of each row is greater than the last integer of the greater than the last integer of the previous row so if you see here the previous row so if you see here the matrix is like sorted 1 3 5 7 10 11 16 matrix is like sorted 1 3 5 7 10 11 16 20 23 30 34 60 20 23 30 34 60 and you're trying to find out if a value and you're trying to find out if a value is in that matrix so you're given is in that matrix so you're given like 3 in this matrix which is there like 3 in this matrix which is there and then you're also given 13 in the and then you're also given 13 in the next example which is not in that matrix next example which is not in that matrix so this is the problem so this is the problem and since the array is sorted and since the array is sorted it already gives you an idea of using it already gives you an idea of using binary search which is a way that you binary search which is a way that you can solve this problem but because it's can solve this problem but because it's a 2d matrix it's a little bit complex to a 2d matrix it's a little bit complex to do that do that so let me just go over a couple so let me just go over a couple approaches to solve this problem approaches to solve this problem and i'll switch over to my ipad to show and i'll switch over to my ipad to show you a couple ways you can do this you a couple ways you can do this this problem this problem the first one is that the first one is that is the most basic brute force which is n is the most basic brute force which is n square where you will just be checking square where you will just be checking all the rows and all the columns so and all the rows and all the columns so and then seeing if there's a value and then seeing if there's a value and actually this is not n squared it would actually this is not n squared it would be be if there's n rows and m columns it would if there's n rows and m columns it would be n times m so that would be be n times m so that would be the most basic solution the most basic solution uh second solution is you can actually uh second solution is you can actually use the fact that the array is sorted use the fact that the array is sorted and the way you can do that is if you and the way you can do that is if you start off at eight start off at eight you will notice that all the elements to you will notice that all the elements to the left of eight in that first column the left of eight in that first column are smaller than eight and if you go are smaller than eight and if you go down down all of these elements all of these elements so basically like to the left all of so basically like to the left all of these elements are smaller and down are these elements are smaller and down are all these elements are greater all these elements are greater so if you just start off at eight so if you just start off at eight um um at which is like the first row and the at which is like the first row and the last column last column you can basically just make it a linear you can basically just make it a linear time which would just be n plus m time which would just be n plus m so for example like if we're trying to so for example like if we're trying to find 11 find 11 what you can do is what you can do is you can first start off at eight you can first start off at eight and then you'll see that eight is and then you'll see that eight is smaller than 11. so what we'll do is smaller than 11. so what we'll do is we'll go down we'll go down and we'll see 20 and we'll see 20 and then once we see 20 we see that 20 and then once we see 20 we see that 20 is is um um is greater than 11 so we'll go to the is greater than 11 so we'll go to the left left and then we'll reach 16 and then we'll reach 16 and we'll see that 16 and we'll see that 16 is smaller than i is greater than 11 so is smaller than i is greater than 11 so we'll go to the left again and then we'll go to the left again and then we'll get to 11. so that's how you find we'll get to 11. so that's how you find it and basically any number you can do it and basically any number you can do it with this n plus m complexity it with this n plus m complexity uh so for example like if we're trying uh so for example like if we're trying to find a number that is not in the to find a number that is not in the matrix matrix like let's say like let's say we try to find uh like 40 we try to find uh like 40 uh what we'll be doing is we'll go to 20 uh what we'll be doing is we'll go to 20 and then we'll see that 20 is and then we'll see that 20 is smaller than 40 which is the target so smaller than 40 which is the target so what we'll do is we'll go down again 60 what we'll do is we'll go down again 60 and it will go to and it will go to 34 34 and we'll see that it's greater and we'll see that it's greater that is less than 40 that is less than 40 but but there is no down because we'll go down there is no down because we'll go down and then we'll reach the end of the and then we'll reach the end of the matrix and when we have this condition matrix and when we have this condition we'll know that we'll know that um we can't find the value and it will um we can't find the value and it will just return false so that is a way that just return false so that is a way that you can solve this problem in linear you can solve this problem in linear complexity instead of the quadratic that complexity instead of the quadratic that we found before we found before and there's actually a better approach and there's actually a better approach so the final solution so the final solution which is the best approach is to use which is the best approach is to use uh bina uh bina binary binary binary search so binary search is going binary search so binary search is going to be a log to be a log n plus m solution n plus m solution uh because uh because because um the array is already sorted because um the array is already sorted um like it's 1 4 7 8 10 11 16 20. 2330 um like it's 1 4 7 8 10 11 16 20. 2330 3460 like all of these are already 3460 like all of these are already sorted so what you'll have to do is you sorted so what you'll have to do is you just have to modify the original binary just have to modify the original binary search search that way that we're typically used to to that way that we're typically used to to use uh this logarithmic use uh this logarithmic complexity and i'm going to show you how complexity and i'm going to show you how i did that i did that because that's the best approach to because that's the best approach to solve this problem okay so this is how i solve this problem okay so this is how i solve this problem using logarithmic solve this problem using logarithmic time time so there's it's basically binary search so there's it's basically binary search but basic you have to but basic you have to try to make it into a 2d matrix try to make it into a 2d matrix so it's it's it's very similar to the so it's it's it's very similar to the to the regular binary search to the regular binary search so first i'm getting these uh variables so first i'm getting these uh variables to set get the to set get the matrix length of the rows and columns matrix length of the rows and columns also m and n also m and n and then like in typical binary search and then like in typical binary search i'm setting the left equal to zero i'm setting the left equal to zero um but for the right um but for the right i'm doing m cross n minus one so because i'm doing m cross n minus one so because it's basically uh it's basically uh like this where we have 1 3 5 7 10 11 16 like this where we have 1 3 5 7 10 11 16 20. so the last index is basically is 20. so the last index is basically is the right and it's going to be the the right and it's going to be the greatest element greatest element uh and then uh and then what i have is two different what i have is two different mids so typically in binary search we'll mids so typically in binary search we'll just have just have one mid element like we will just do one mid element like we will just do left plus right divided by two but in left plus right divided by two but in this case um there's a linear mid and this case um there's a linear mid and then there's also a matrix mid then there's also a matrix mid so the linear mid is what is the regular so the linear mid is what is the regular mid that you would be used to in binary mid that you would be used to in binary search but then you have to convert this search but then you have to convert this into the matrix value and that's why i into the matrix value and that's why i have this matrix mid variable so how i have this matrix mid variable so how i did this is that i first do the linear did this is that i first do the linear mid which is just a regular binary mid which is just a regular binary search left plus right divided by two search left plus right divided by two then matrix mid then matrix mid so to find the row you actually have to so to find the row you actually have to divide by divide by the number of columns like in the linear the number of columns like in the linear so you do divided by n so you do divided by n and then you have to do modulo and then you have to do modulo n to get the n to get the uh the column number so that's that's uh the column number so that's that's how it's like split up when we do m how it's like split up when we do m times n minus one um and like when you times n minus one um and like when you when you actually get it into the when you actually get it into the uh to get the values in the matrix you uh to get the values in the matrix you have to do these have to do these conversions conversions uh and then so that's that's the value uh and then so that's that's the value that we use based on the linear mid and that we use based on the linear mid and then we if the target is equal to that then we if the target is equal to that then we return true which is regular then we return true which is regular binary binary uh binary search and then uh binary search and then we check the other two conditions so if we check the other two conditions so if it's less than then we do it's less than then we do the regular linear mid minus one the regular linear mid minus one and then left and then left on the other case it would be plus one on the other case it would be plus one so this is just basically the same as so this is just basically the same as binary search binary search and of course like if we can't find the and of course like if we can't find the value we return false value we return false so the main so the main thing of this the only difference thing of this the only difference between binary search and between binary search and and this problem is that is this and this problem is that is this conversion conversion and this is only and this is only specific to matrix problems specific to matrix problems uh but like once you understand this uh but like once you understand this conversion uh this problem is very conversion uh this problem is very straightforward straightforward and once i submit this problem you can and once i submit this problem you can see that see that it's accepted and i'm getting a run time it's accepted and i'm getting a run time of 100 of 100 uh which is which is very good uh which is which is very good so thanks for watching this video uh let so thanks for watching this video uh let me know if you have any questions about me know if you have any questions about the solution the solution and subscribe for more videos in the and subscribe for more videos in the future | 2024-03-20 11:38:05 | 74 | Leetcode #74 (Java) - Search a 2D Matrix (Daily Challenge Mar 30, 2022) |
|
5UWEVMg10rY | Hello everyone welcome to my channel with mike so today you are going to do video number nine of linked list ok the today you are going to do video number nine of linked list ok the name of the question is name of the question is remove zero sum consecutive notes from remove zero sum consecutive notes from linked list it is a medium level question linked list it is a medium level question but bill will be very easy if we understand it but bill will be very easy if we understand it ok ok ok is fine and you have to understand the question by looking at the input and output. See what the question is by leading the question. Sorry link's question has two specialties. First, if you have made this diagram then it becomes very easy. Question because you are able to visualize the story work in the question from the second link. The story is really fine, isn't it? If I tell you then you can do the code very well by yourself. People do not need to tell anything. Okay, so Let us understand Let us understand Let us understand what is the question, what is the question, so the question is quite simple to understand, so the question is quite simple to understand, a link has been given to you in it and it has been told to you a link has been given to you in it and it has been told to you that if the that if the sum of the consecutive elements of the linked list is zero then it has to be sum of the consecutive elements of the linked list is zero then it has to be removed from the notes, but see the example here. removed from the notes, but see the example here. What is the value of linkluf? What is the value of linkluf? Here is one. Next, you are one plus 2. It has become 3. Here, Here is one. Next, you are one plus 2. It has become 3. Here, as I have come, you are seeing that the sum has become zero. There as I have come, you are seeing that the sum has become zero. There is one here, this is 2 -3. Total is one here, this is 2 -3. Total sum has become zero, so what does it mean? sum has become zero, so what does it mean? We have to remove this, okay, now let's We have to remove this, okay, now let's move ahead, there are 3 here, if one is done here, move ahead, there are 3 here, if one is done here, then this will not be removed, so look at what has gone then this will not be removed, so look at what has gone back, just look at this, this is my back, just look at this, this is my LinkedIn child, okay and look at the head LinkedIn child, okay and look at the head starting. starting. starting. but now the head is pointing to the right, so many things have to be kept in mind that the head can also change. Okay, we have to delete more and the painter also has to adjust. Okay, let me But But But if we take an example, our link is like this: if we take an example, our link is like this: 2 - 2 is pointing to 3, it is pointing to one, okay pointing to 3, it is pointing to one, okay then both of these will be there so that there is no change in the head, here there It is possible, It is possible, It is possible, okay, the sum of any consecutive element can be okay, the sum of any consecutive element can be zero, then it is okay, the zero, then it is okay, the question is very simple to understand, now let's see question is very simple to understand, now let's see how to solve it, okay how to solve it, okay see, now coming to the best part, how to see, now coming to the best part, how to build the intion, okay what, how to solve it. build the intion, okay what, how to solve it. How will they bill come up but they will How will they bill come up but they will see the solution? The most important thing see the solution? The most important thing is okay, so this is a sample of mine taken to understand it, okay, before going on the link lift, I will show you one before going on the link lift, I will show you one okay, but the example. okay, but the example. okay, but the example. yours, we are doing this, okay here is one, you are three, here is -3, here is four, let me index 0 1 2 3 4 okay, consider this as a very important thing and we will It is a very basic It is a very basic It is a very basic thing, it is a logical thing, but I look at you thing, it is a logical thing, but I look at you like see, see, see, let's see the like see, see, see, let's see the prefix, we leave, okay, this is prefix, we leave, okay, this is my forest, okay, now look, my forest, okay, now look, what is my prefix in the beginning, it is zero, I have what is my prefix in the beginning, it is zero, I have not added anything yet. not added anything yet. not added anything yet. prefix prefix even is okay now here so one is added then one comes here so one plus tu three correct that that I am adding the numbers no one plus tu plus three minus three so number So, the number should have been filled, the number should have been increased, 1 + 2 + 3. Look, the number is also big, after one, three, A, after 3, six, A, after that, Ghat, but it is okay, Ghat and when I have I have I have seen this 3 nearby, look here, I saw it seen this 3 nearby, look here, I saw it nearby, okay, so tell me one thing, the nearby, okay, so tell me one thing, the sum till here is looking correct to me, the after this I added something to which go after this I added something to which go back. back. back. Okay, that means first I was three, the whole even or the sum of so many words was three, then I added something, I ask for it from the red box, after this I added something, then again I went, I added something to it, did I add anything, I don't know, then I have I went, I added something to it, did I add anything, I don't know, then I have come back to 3. You come back to 3. You see, here it was on 3, see, here it was on 3, then I added something and then look again, it came back then I added something and then look again, it came back to 3, what does it mean? to 3, what does it mean? What would have been its value? The value that What would have been its value? The value that I added must have definitely been zero, that is why I added must have definitely been zero, that is why 3 + 0 came back to 3A. What does it mean 3 + 0 came back to 3A. What does it mean that brother, this area must have that brother, this area must have definitely been zero. Okay, listen again, it definitely been zero. Okay, listen again, it is very important, question on this. is very important, question on this. is very important, question on this. understand that you have been vaccinated then everyone will understand. Okay, I am saying that brother, I know that till this much is even three, this is okay with you and so and so and this is what I am marking with a red box, I I I added it on this, but it came back to 3, so added it on this, but it came back to 3, so what would be the meaning of this, what would be the meaning of this, surely the sum of this box must have been zero, it surely the sum of this box must have been zero, it is only 3 - 30, okay, it is clear till now, this is only 3 - 30, okay, it is clear till now, this thing will apply here also. thing will apply here also. thing will apply here also. carefully what I am saying, what is my time now, in the beginning everything is my zero, okay, prefix zero, now one became one plus you three till now everything was going well, it till now everything was going well, it reached three but after this so much reached three but after this so much After adding the part, it again After adding the part, it again went back to three. Okay, what does it mean went back to three. Okay, what does it mean that that this is the area, its sum must have been zero. this is the area, its sum must have been zero. Okay, then this thing will be known that how will you catch it, brother, how many parts. First of all, there was no tension, how many notes have to be removed, that ended my tension, notes, either notes, either part, have to be part, have to be removed from the link list, we have found out which is most link list, we have found out which is most important important and whose sum is zero, I have found it, and whose sum is zero, I have found it, brain. brain. brain. okay now the matter has come, let's catch it, brother, I have to curse them, I have to remove them, now how will I remove them from my link, you should understand how that too should be understood, meaning, you should understand that Okay, so let's Okay, so let's Okay, so let's see, let's do it directly, it will become see, let's do it directly, it will become clear immediately, see how, remember, first of all, what I said that I will extract all the prefixes, so I will keep a variable for extracting the prefix, ok, prefix, Is it zero? Okay, what did Is it zero? Okay, what did Is it zero? Okay, what did I say when I I say when I find a prefix sub which I have already find a prefix sub which I have already seen in the paste, then I will be seen in the paste, then I will be suspicious there, no, what is the suspicion, I will come to suspicious there, no, what is the suspicion, I will come to know there that yes, zero component has been found in know there that yes, zero component has been found in it. it. it. now along with it I will have to store in the map that brother, when did I last see this prefix and in which note did I see it? Otherwise, the map that will be mine will be something like what is the Wait and Wait and Wait and second thing, in which road did you see it, then there second thing, in which road did you see it, then there is a list note, so my map will be something like this, is a list note, so my map will be something like this, okay, then the prefects come out, if we get okay, then the prefects come out, if we get starting prefix, then three prefixes, we too, I have not seen till date, it was not there in the map, And on And on And on which note was it found? B was found on note. Okay, which note was it found? B was found on note. Okay, now here it is 3 + 3 = 6. Six is also now here it is 3 + 3 = 6. Six is also not present in the map, so six was given. not present in the map, so six was given. Here, C was given and six was found on C. Here, C was given and six was found on C. So okay, now look at this very important thing, So okay, now look at this very important thing, as soon as I came here, as soon as I came here, I got free again in the prefix. Okay, so I I got free again in the prefix. Okay, so I saw that three is already present saw that three is already present in my map. Look here and in my map. Look here and where did I see this three last? where did I see this three last? where did I see this three last? means, after B, till here, where am I standing now, currently, I am standing here on three, na - if I am standing on 3, then I am head, I am late, It was flooding slowly, It was flooding slowly, It was flooding slowly, okay, so let's take mom, now I am okay, so let's take mom, now I am standing here, okay, so I saw that okay standing here, okay, so I saw that okay now my prefix is we 3 and 3, I have already now my prefix is we 3 and 3, I have already seen it in the map, so from here I came to seen it in the map, so from here I came to know that and this I got this. know that and this I got this. know that and this I got this. that from this map, take this from B to this B. How did I know that I had stored it here, after this B till the head, after this B till the head, the notes will have to be Let's Let's Let's see, it is see, it is obvious that they will have to be removed obvious that they will have to be removed and what will have to be done to remove them. Think and what will have to be done to remove them. Think what I will do, brother, I will what I will do, brother, I will make his next head the next one. Okay, so this make his next head the next one. Okay, so this note was there, this connection was cut, it note was there, this connection was cut, it is right. is right. is right. start pointing to the direct four and we will have to remove this prefix from the map, no, we will have to remove the six, okay, we will have to remove this, okay, that's the only thing because now it is okay, that's the only thing because now it is not in our picture, so map it. not in our picture, so map it. Okay, so now let's focus on Okay, so now let's focus on what to do next. Okay, so look, I am clearing it a little bit what to do next. Okay, so look, I am clearing it a little bit so that we can flood further. so that we can flood further. Okay, I am removing all of these as well. Okay, I am removing all of these as well. I am okay, I am removing all of these as well. I am okay, I am removing all of these as well. I am okay, I am removing all of these as well. now if we see the story, what was going on with us was that brother, when we came here, our prefix we 3 mine which is already we can see, where we have seen here on B, we are looking at it, okay here I have seen three, I have seen three, I have seen three, what does it mean that we do not need it, we do what does it mean that we do not need it, we do not have to enter it in the map, if it has its not have to enter it in the map, if it has its entry then it is not removed and does not have to be entered, entry then it is not removed and does not have to be entered, like we take it for granted that we will like we take it for granted that we will not enter it in the map, why would we do it in the map not enter it in the map, why would we do it in the map because because because and preference is 3, we have seen it in the last, okay, we have seen it here, that is why not enter it, no, okay, has it gone back, has not enter it, no, okay, has it gone back, has it gone back, no, it gone back, no, we just have to remove it. we just have to remove it. we just have to remove it. okay with you, one thing I have to do is delete it, plus one more thing, what I have to do is to delete this connection and how to move here, it's so to do all this, I have to do this a little bit. so to do all this, I have to do this a little bit. so to do all this, I have to do this a little bit. cleaning it so that you can understand it well, so look, it is an obvious thing, you know that yes, last time three, where did you see it, saw it here, right here, saw it here, so let's mark here that I Let's start with this, Let's start with this, Let's start with this, okay, and science, I will have to remove okay, and science, I will have to remove it. It's okay, if there were others in between, let's it. It's okay, if there were others in between, let's remove them too. Okay, and remove them too. Okay, and I have not included this in the map, so there I have not included this in the map, so there is no need to remove it, right? is no need to remove it, right? is no need to remove it, right? this has to be removed, now from here I will start moving from the start and will keep removing everyone until I get what I want, until I get this, I am now standing here until I So you So you So you think for yourself, then when I remove it at the end, think for yourself, then when I remove it at the end, this is the start, no, I started this is the start, no, I started from here, so what will happen next, do from here, so what will happen next, do this, I will mark it, okay, this, I will mark it, okay, so that this link gets broken, right, it's so that this link gets broken, right, it's okay. okay. okay. and have kept a template which will move forward and remove all of them. If it is okay then how will our file look? File 10 note is equal, you are the head, then Ok, come on, Ok, come on, Ok, come on, this is what you guys must have understood. this is what you guys must have understood. Okay, what happened now? What is the Okay, what happened now? What is the value of the prefix in temp key? It is three here. There value of the prefix in temp key? It is three here. There are only three here. Okay, now are only three here. Okay, now I have moved the time forward. Temp is here. I have moved the time forward. Temp is here. Okay, what is the value of team and the prefix of team is Okay, what is the value of team and the prefix of team is stored as three and its bar is stored as three and its bar is three becomes six, so it becomes 6, so what will I do, three becomes six, so it becomes 6, so what will I do, I will see in the map that okay here, the value of its prefix till this note was 6, so value of its prefix till this note was 6, so value of its prefix till this note was 6, so I deleted it from here, made it six, okay, what did I do? MP Dot A Race, what a very very six, it was 6, I erased it, okay, I erased it, okay, that's very good. After this, temp will flood my front, it will go to 10, now from here, I have removed time pay note equal tu head only, so my fruit look is finished and I have removed this from the map, this also from the map, It has been removed and at the end when the It has been removed and at the end when the It has been removed and at the end when the follow is over, what did I say that follow is over, what did I say that I will make it equal to whomever is next at the start, I will make it I will make it equal to whomever is next at the start, I will make it equal to this one, okay equal to this one, okay my current one, I was standing on the head, neither is the my current one, I was standing on the head, neither is the head which is next i.e. it is only four. head which is next i.e. it is only four. Isn't it a net of time, so what will I do, Isn't it a net of time, so what will I do, this is the start of mine, this is the start of mine, its next, now whom am I making equal to the its next, now whom am I making equal to the head's next, head connections have been made equal to the head's next, these people have agreed, these people are We We We leave this in the map and when it has been entered, I leave this in the map and when it has been entered, I removed it. I am there, these are already there, removed it. I am there, these are already there, okay, these people are already there and okay, these people are already there and I have made this connection of CAT, here I have made this connection of CAT, here it is, okay, so if you see. it is, okay, so if you see. How simple will our code be? How simple will our code be? Understand the story, you do the code now. Okay, Understand the story, you do the code now. Okay, Story 2, understand it carefully. Okay, Story 2, understand it carefully. Okay, before supporting the story, think of one more thing, just before supporting the story, think of one more thing, just a small thing as I told you, a small thing as I told you, Maa, let's take the head only. Maa, let's take the head only. Maa, let's take the head only. this is mine, you are mine, this is my 3, pay we, it has become zero, I have not seen a but three yet, I will have to put zero also, there should already be zero in the map, so zero in the map, so what will I do, remember. what will I do, remember. what will I do, remember. was one here but remember in the beginning my prefix was zero, dispatch was zero but there is no note for it yet but what will I do, one I will make a dummy note, Let's Let's Let's keep its value zero, let's keep its value zero, let's keep its Dumin and Dum, Damini note is okay keep its Dumin and Dum, Damini note is okay and I mark it next to the dummy note, and I mark it next to the dummy note, A is okay, I mean what I am saying is A is okay, I mean what I am saying is that I will make a dummy note and that I will make a dummy note and point it to whom next head. point it to whom next head. point it to whom next head. point it to, right? If the head says, A A will point it, okay, so now see how I will reduce it, I saw that okay, I have just got zero, I have just got zero, I am already looking at it, okay, I must have already written it and I must have already written it and I must have already written it and this is the dummy note which I must have inserted here in the map. I must have this is the dummy note which I must have inserted here in the map. I must have inserted it in the starting itself. Okay, so now as soon as I got zero again, I saw that the terminal is already present in the map. Okay, so what can I do? I will do it, I will go here, okay, I went here, this is my start, okay, and this is my temp, no, this is my I removed it here, okay, I removed it, I removed it here, okay, I removed it, after that temp came here, I have removed 'C' as I had I have removed 'C' as I had I have removed 'C' as I had not inserted it. It is not necessary to remove 'C'. It is not not inserted it. It is not necessary to remove 'C'. It is not necessary to remove 'C' necessary to remove 'C' yet. Okay, now look at yet. Okay, now look at what I said in the last section, what I said in the last section, when the wiring loop will end. when the wiring loop will end. when the wiring loop will end. what I said was that whatever will happen next at the start, what will I do? what will I do? Whom will I call next at the start? It means Whom will I call next at the start? It means that what will happen now is to watch carefully, it was here, so what will I do now, it will And in the last, know And in the last, know And in the last, know what I will do, I will return, okay, so what is the most important thing, what we have to do in the beginning is that we will make a map, okay, we will definitely make an entry in it, MP of zero, because In this In this In this equal, you will make a note and put its equal, you will make a note and put its address here, the land is fine and the most address here, the land is fine and the most important thing is that if you make the land, then what will have to be done is the important thing is that if you make the land, then what will have to be done is the dog, but the dummy note will also have to be pointed, after termining the dog, but the dummy note will also have to be pointed, after termining the head, the next thing that will happen will head, the next thing that will happen will also be pointed to the head. also be pointed to the head. In the beginning, the value of the head should be done. Okay, In the beginning, the value of the head should be done. Okay, this example was important. Okay, so now whatever story you I will make it by asking questions from almost all the links. Okay, so in the beginning, I will have to do these three steps, that is, Signed, made a map Signed, made a map Signed, made a map okay, the prefix is going to be in the starting okay, the prefix is going to be in the starting is okay and then my form will run is okay and then my form will run from its starting until the head is null from its starting until the head is null until the head is null and what is until the head is null and what is okay then I prefix we come out okay then I prefix we come out I will remain prefix sum plus it is equal to the I will remain prefix sum plus it is equal to the value of head. If it is present then it will reduce the delete one by putting a loop on the delicious one Okay, this is very important and if you write the code now, then you Okay, this is very important and if you write the code now, then you will listen to the story again but will listen to the story again but will listen to the story again but searching you again dry and do n't forget to take this one example and return dry. Okay on this so let's code it. Now let's code it and I will repeat again Must do story you Must do story you Must do story you code, now we are going to convert, first of all code, now we are going to convert, first of all what I said was that what I said was that we are going to keep a prefix with the name, what will we keep in the variable, we are going to keep a prefix with the name, what will we keep in the variable, we will keep zero which will be in the starting, the prefix will be we will keep zero which will be in the starting, the prefix will be zero, right and we are going to keep a map in it, zero, right and we are going to keep a map in it, right in these inches. right in these inches. right in these inches. prefix will be even and I am writing on which note I got this prefix, I am then let's make it, ok, I have made a dummy note, I have made a dummy note, ok, now let's start our vile. ok, now let's start our vile. Head note is equal, you tap this, I will keep going, Head note is equal, you tap this, I will keep going, okay, now you say that the head will keep changing, okay, now you say that the head will keep changing, then in the last, that is why I am saying right next to the then in the last, that is why I am saying right next to the dummy, add the address of the head dummy, add the address of the head and I have done it okay, which was the and I have done it okay, which was the actual address of the head here. actual address of the head here. actual address of the head here. then I don't care whom I am going to return last, whatever value will be next in the dummy note, I am going to return last, okay, so now we keep calculating the prefix as Whatever the value of head is going to be, it Whatever the value of head is going to be, it Whatever the value of head is going to be, it is okay. Now what I is okay. Now what I said is that if said is that if I get MP sum, it is I get MP sum, it is okay, if I get it already in the map, then the okay, if I get it already in the map, then the delete one will reduce this one, now the head will be pointing to whomever it is, The next part of the head will keep The next part of the head will keep The next part of the head will keep moving, okay, now this moving, okay, now this is less of mine, this is my part, this is the part of this entire code, is less of mine, this is my part, this is the part of this entire code, okay, okay, we will reduce the delicious one, so what I said was we will reduce the delicious one, so what I said was okay, I have started a quandle. okay, I have started a quandle. okay, I have started a quandle. who will point to whom? MP of prefix sum, which I have just seen, I have seen it nearby, so I went there, it is good, this is where I last saw it last time, this prefix Let's Let's Let's take the name temp which take the name temp which will start from the beginning and it will keep moving forward will start from the beginning and it will keep moving forward and we will also keep deleting it, okay and the current is and we will also keep deleting it, okay and the current is my prefix, what is we, brother, prefix my prefix, what is we, brother, prefix equal, this is my current prefix, okay and how equal, this is my current prefix, okay and how long will it last until the time note is equal to you. long will it last until the time note is equal to you. Okay, let's get the head and I will keep deleting from you. Okay, let's get the head and I will keep deleting from you. Okay, now let's see what is my Okay, now let's see what is my tempo. This is equal to your tempo. We were moving ahead. tempo. This is equal to your tempo. We were moving ahead. Remember, we did the next of 10 = 10. Remember, we did the next of 10 = 10. Okay and we will also keep updating the prefix. Okay and we will also keep updating the prefix. Okay and we will also keep updating the prefix. prefix we, which I have made here as temporary, prefix sum plus it is equal to 10, the value is fine and we will keep arranging it. mp.ej This piece is there, but look pay attention, when will we raise it, for how long we will keep doing it till. how long we will keep doing it till. how long we will keep doing it till. not be equal to that of the head, nor should it be equal to that of the team's head, because remember, I have not even entered the person whom the head is pointing to. It is not in the map, so even We will keep We will keep We will keep racing and then later on there will be a similar racing and then later on there will be a similar break. Okay, after that when we were taken break. Okay, after that when we were taken out, what did I tell you that I am going to out, what did I tell you that I am going to change the start, it will become change the start, it will become equal to the next one of the head, so I want to say, make a diagram. so I want to say, make a diagram. so I want to say, make a diagram. make a story and dry it. Do it properly. I have taken two diaries of this and one more test of mine too. Dry it on this code. It is okay. This is a very easy code. Let's Let's Let's run and see, there will be no new note, there will be a run and see, there will be no new note, there will be a new list note. Here, now let's run and see, if you are able, you will pass the example. Okay, great, submit, let's see. Indias, they have solved this question, viewers are already ready. Have any doubt please in this common session and try help see you gas video | 2024-03-25 18:39:41 | 1,171 | Remove Zero Sum Consecutive Nodes from Linked List | Made Super Easy | Leetcode-1171 |
|
9iyTClnfBKc | hey what's up guys this is sean here so today let's take a this is sean here so today let's take a look at look at uh last problem of last week's uh last problem of last week's weekly contest number one thousand 1611 weekly contest number one thousand 1611 minimum one bit operations minimum one bit operations to make integers zero okay to make integers zero okay so you know this is like a quite so you know this is like a quite interesting problem you know okay given interesting problem you know okay given like an integer like an integer and you must transform it into zero and you must transform it into zero using the following operations any using the following operations any number of the times number of the times return the minimum number of operations return the minimum number of operations to transform into zero to transform into zero so which it means that you're given like so which it means that you're given like a a number n here and you can only perform number n here and you can only perform one of those two operations so let's and so what are those two operations so the first one is that change the right the right most bit in the binary representation of n so the zeros bit means that you know let's say if we have 1 0 1 0 1 0 1 0 1 0 0 1 it means that you can only change the right the the right most bit which is the last bit you can either change this one to from to zero from zero to one or or from one to zero okay so that's the first thing you that's the first uh the first operation you can do which means you can only change the the last digit and the second one is a little bit a little bit weird basically you know if you want to change the ice bit okay um for example if you want if you want to change this the leftmost bit here in the binary representation of n here you can only change it if the and the if the i minus 1 bit is 1 and the rest is 0. so what does this mean it means that if you want to change this bit here you can only change it when the uh when when the the bit is is like this one one zero zero zero zero okay only then you can change this one from one two to zero or from zero to one but for this problem i there's no point of changing this one from zero to one because we're trying to move trying to change this what is n convert this n into zero so which means in order to change uh the not the none last none uh right most digits we have to somehow convert this this binary strings into this format then we can then we can change the we can change this one to zero right and then the rest will be uh what i mean will be this will be this one yeah so that's basically those those two yeah so that's basically those those two those rules of those rules of of this problem okay and okay so in order to do that right i mean let me try to write something here you know for example right let's say we have a num we have a uh we have integer we have a string like one zero uh one one zero one one zero okay let's let's say this that that's the end here okay and so in order to change this one okay and so in order to change this one to zero so we have to to zero so we have to first basically we will be look we will first basically we will be look we will always try to change the the left most always try to change the the left most uh digits from if it is one okay uh digits from if it is one okay because that's basically we're trying to because that's basically we're trying to use it like this kind of greedy use it like this kind of greedy approach here basically if the left most approach here basically if the left most uh uh digit is one we'll try to we'll try to digit is one we'll try to we'll try to uh change this one to zero uh change this one to zero but in order to change this one to zero but in order to change this one to zero so we need to convert we need to do this so we need to convert we need to do this right right we need to do something like we need to do something like uh we need to change this this one uh we need to change this this one to uh to what 201 to uh to what 201 one zero zero zero zero zero okay basically we need to change this all right this part to it okay now i'm gonna i'm gonna do a like a comments here right so the first step is that we have to somehow change the change the this strings to one one zero zero zero zero so that the net we can then change this one to uh to to i mean to zero okay so now so basically from this from the first step to to this step what do we have here we have i mean we have like uh somehow right we somehow have to change this one to two one zero zero zero zero step one right step one is is this okay step step one is this we need to change this one to that and the second step is what so the second step is we we we do a plus one here because the second step is that we just now we we can simply we can uh we can use the second uh operations here where we added where we revert this thing the one two to zero okay so change one to zero to zero and then how about this the second step here so the second step is now we just need to convert now the the left most bits have been changed to zero now we just need to change the rest thing into a into zero so which means as you guys can see before we had like uh uh seven digits now we only have have six that's like uh like a sign of recursion right basically now we just need to uh convert this one zero zero zero zero to two zero basically that's the that's the three step uh to convert that okay and for this part for the second so basically and this one this one will result to one right and this one the third step uh will result to what uh assuming we have a dfs we have a dfs then it's going to be a one zero zero okay right because at okay right because at here we have like at the beginning we here we have like at the beginning we have a beginning we have dfs right df have a beginning we have dfs right df dfs one dfs one zero one one zero one zero zero one one zero one zero right at the beginning we have that so right at the beginning we have that so now now the first step is we are is equal to what basically we need somehow first up we need to convert this part into one zero zero zero zero okay assuming we have a we have a function here we have a helper function here to help us to help us uh convert these things right to uh to to this one here and then the next one is with plus one because the next step is we plus we will convert we revert the leftmost bit okay and then we do what the rest is dfs and we have five zeros okay so that's the uh that basically that's the dfs there's a dfs transition function here right and now about this helper because remember so the dfs the definition of dfs is the what's the dfs the dfs the minimum minimum steps to convert convert n to zero okay and the helper so what what is the helper the helper is like helper n right so how helper n is the mini mom stops to convert n to what and to uh basically one one zero zero zero zero basically the uh the the same length of of n but with the is one at the at the first bit and the zero for the rest bits okay and so we we already have like the definition of the dfs now we just need to uh consider how can we implement this helper function right which will be converting this n to uh to this uh to one to one zero zero zero zero okay so you mean okay so now to to be able to convert 1 0 0 1 0 0 to uh to 1 0 0 zero zero zero so we also need to we have to make some observations here right so i mean they're they're basically they're like there are like uh two cases here i mean you guys just need to uh take a close look and so the first case is the uh if basically if the the bits i'm let's say i'm i'm defining a bit here right if the bit 0 which means the first bit y the bit value okay so uh well actually you know what so i think the the one case is is easier okay so if the first if the first the bit y the first value the first bit value is one and then we just need to convert the remaining the remaining parts into zero so and as you guys can see so this is exactly what the dfs is doing right basically if the so if the if this the bit the first bit is one we can simply do what we can simply do a one plus the dfs dfs and this part right so the the remaining part assuming like say this is the that that's the that's the case right it's going to be a 1 1 one x x so we have we have uh we have 6x here right so uh let's see there's the s uh let's see there's the s and five x here right so if the s and five x here right so if the s if s is is one then we have one plus d f if s is is one then we have one plus d f s s x x x five x here because all we need to x x x five x here because all we need to do is just do is just oh basically we don't even need the one oh basically we don't even need the one here because we just need to convert the here because we just need to convert the remaining to zero remaining to zero and that will give us this one zero zero and that will give us this one zero zero zero okay zero okay and and and the more complicated cases and and and the more complicated cases if the s is zero okay if the s is zero okay so if if s is zero so if if s is zero uh and we want to flip basically we want uh and we want to flip basically we want to flip this zero to flip this zero to one so that we can convert to one so that we can convert these things to 1 and 0 0 0. these things to 1 and 0 0 0. but so again right so in in order to but so again right so in in order to flip this flip this the first bit in order to flip the first bit in order to flip that the first bit so we have to that the first bit so we have to first convert uh these things to what first convert uh these things to what to uh to s to uh to s one zero zero zero one zero zero zero zero right so the first step is this so uh 2.1 okay so the first step is from us this to to this right because only only when we have when we convert this uh this string to the form to the form of this one then we can we can uh flip this ass remember this is a zero here right and then we can flip this one to uh to to one one zero zero zero zero right then we can we can flip that and now and now the the the remaining part is what the remaining part is we just need to convert the remaining one zero zero zero zero two zero zero zero and this is also happens to be the definition of of the right so and now we just need to convert the these things here this uh the remaining part into zero which happens to be the dfs here so it's going to be a dfs one zero zero zero zero now we only have four zeros here okay so so that's the that's the second part so the first part right so the first part what is the first part the first part is we convert these things the xx xx to one to one zero zero zero zero so well so what's what's this that's the definition of our hyper helper function right so basically you know so now we have the functions here so we basically if the first one is zero so the first step is that we have to convert this part to one zero zero zero zero which which it happens to be our hyper function itself okay it's gonna be a uh five x here right and then after that we uh we flip the the first bit right to be it to convert this zero to one so we plus one and then the remaining part is still right we still have to uh now we have one one zero zero zero now the rest is just to use this dfs to convert this one zero zero zero to zero so that we will have this final answer right it's gonna be df as one zero zero yep so i think now we have we yep so i think now we have we we have already defined these two we have already defined these two functions functions completely and we can start implementing completely and we can start implementing those two those two those two functions oh but remember so those two functions oh but remember so for those dfs right for those dfs right since we we also need to uh use uh like since we we also need to uh use uh like the the memorizations the the memorizations just to save some time because with the just to save some time because with the you know for the dfs for n you know for the dfs for n and helper ends here you know as long as and helper ends here you know as long as we have define uh calculated once we can we have define uh calculated once we can simply store those the result into a simply store those the result into a into a hash table into a hash table so that we it can be reused so this so that we it can be reused so this something like a dp something like a dp right and now right and now and for the uh for the base case and for the uh for the base case for the base case it it'll be a little for the base case it it'll be a little bit different bit different uh in terms of the dfs and helper so uh in terms of the dfs and helper so let's let's see let's take a look at the let's let's see let's take a look at the base case so for the base case base case so for the base case the base case right so for the how for the base case right so for the how for the dfs the dfs for dfs the base case is just though for dfs the base case is just though has the has one digit right so for one has the has one digit right so for one digits digits if it's zero if it's zero what so for if it's zero if it's zero what so for the zero the zero we don't need to do anything to convert we don't need to do anything to convert to zero so which means if this is zero to zero so which means if this is zero we simply we simply return zero so if if one return zero so if if one uh we return one because for to be able uh we return one because for to be able to convert one to zero to convert one to zero we just need to flip the we can just we just need to flip the we can just simply use the first simply use the first operations to do it so which means we operations to do it so which means we will need will need a one step okay but for the helper here a one step okay but for the helper here that that right so just be be careful when you right so just be be careful when you define the base case for the helper define the base case for the helper remember the purpose of helper is to remember the purpose of helper is to convert convert this n to one and then this n to one and then follows the uh follow zeros follows the uh follow zeros okay so which means if okay so which means if it's zero if it's zero it's zero if it's zero so we need to return one why is that so we need to return one why is that because because now the purpose of the top rate is to now the purpose of the top rate is to convert this value convert this value into one something and in case of of into one something and in case of of only one digit it means that only one digit it means that just one without any zero so which means just one without any zero so which means we can simply use the first we can simply use the first rules the first operations to convert to rules the first operations to convert to zero to one okay zero to one okay and if one then returns zero and if one then returns zero basically it's just opposite because if basically it's just opposite because if it's one then we okay we have already it's one then we okay we have already have have the the desired format we need here the the desired format we need here so that we just need we don't need to do so that we just need we don't need to do anything anything that's why we return 0 here cool so i think yeah with this kind of definitions we can start uh writing writing the code now right uh so first uh we need the dfs okay we uh so first uh we need the dfs okay we need dfs need dfs and then i'm going to pass in the bits and then i'm going to pass in the bits here okay here okay and then we all have like a helper and then we all have like a helper functions here okay so halfway we also functions here okay so halfway we also need to define like a bits need to define like a bits because you know the the the input is is because you know the the the input is is integer but you know integer but you know uh it's easier for us to convert it into uh it's easier for us to convert it into a into a string format a into a string format and then here i'm going to have like a and then here i'm going to have like a memorization for dfs okay memorization for dfs okay and also the uh another memorization is right for the for the helper okay i'll just call it helper here and here in the end we simply return the dfs and oh sorry so before doing that let me let's try to convert uh the string the the integer into the b twice so the way in pi in python we have a function called bin here so the binary the bin like function basically will give you the uh return the string here but the binary will also returns like a string like a at i at zero b at the front so in term for example if there's a six here so uh we have this one the binary string is one one zero but if you use a binaries i think it's got i think they added like zero b out of as a prefix so it would be like zero b one one zero but here we only need the the the remaining parts so that that's why we i'm going to simply use like a slice of the string here basically we just need to get everything starting from the third the third character okay here yeah sorry now we have the bits we here yeah sorry now we have the bits we simply return the bits here simply return the bits here so that's the uh that's the so that's the uh that's the the precalculation we convert this thing the precalculation we convert this thing to to the bits to to the bits and then here right now we have this so and then here right now we have this so first let's try to uh first let's try to uh uh write this the memorization part uh write this the memorization part basically if the bits in the basically if the bits in the memorization dfs memorization dfs okay we simply uh okay we simply uh return that okay bits simply return it okay and then later on right so answer equals to zero and here i'm going to just uh copy and paste here so this is just like a template for the top down dp right and then return answer okay so that that's that and now the uh the base case right since we have already talked about a base case i think we can simply uh uh write the base case here first basically if if the bits uh equals to zero right so so for the dfs we are converting everything to zero so which means here we don't need to do anything which means we can simply return zero or if the bits equals to one okay so in order to convert one to zero we return one because we need one step or one operations okay okay so now there's a place we need to be careful there's a place we need to be careful because you know because you know it could be it could be uh possible that it could be it could be uh possible that the df at the beats the df at the beats stream we pass in the first one is not stream we pass in the first one is not zero zero because it could be uh zero one one zero because it could be uh zero one one zero zero one because later on because uh zero one because later on because uh when we do this when we do this like the recursions you know even though like the recursions you know even though this this bin this this bin is being here at the first at the is being here at the first at the beginning this beats will not have like beginning this beats will not have like uh precede uh uh precede uh as zero as a prefix but during the as zero as a prefix but during the calculations calculations it's possible that the the path in bits it's possible that the the path in bits will have it will have it starting with zero because we will be starting with zero because we will be doing this like a substring doing this like a substring later on right so for if the if the later on right so for if the if the the first one is zero it means that we the first one is zero it means that we don't need we don't want to don't need we don't want to handle the the first case we don't want handle the the first case we don't want to handle the to handle the the zero the zero bit because there's no the zero the zero bit because there's no because we're getting the minimum because we're getting the minimum number which means we just need to uh number which means we just need to uh start start our logic from the first uh non-zero our logic from the first uh non-zero bits bits okay so which means if the bit okay so which means if the bit zero is equal to zero right so in this zero is equal to zero right so in this case case we can simply [Music] you know we can we can do do a while loop here i think and or or we can just use the uh the dfs itself here right so we can simply do a uh uh um let's see we have an answer here answer is the uh it's zero okay if the if the first one is is zero and then we simply do a dfs of the the bits uh uh one okay basically we just passed this uh the remaining parts to the answer to the two to the the dfs so that when we just ask the uh else right yeah else uh like i said so else it's yeah else uh like i said so else it's it's this case right we just we will it's this case right we just we will need to need to somehow convert the the substring right somehow convert the the substring right to the one zero zero zero and then plus to the one zero zero zero and then plus one and then do a dfs of this one and then do a dfs of this so basically here we'll do a helper here so basically here we'll do a helper here right helper right helper is what we uh we do a helper bits from is what we uh we do a helper bits from this this okay that's that's the first step and then and then plus the dfs and then plus the dfs of uh of uh so of of this right so how do we so of of this right so how do we calculate that right basically calculate that right basically we need a one at the beginning right so we need a one at the beginning right so we need a one here we need a one here plus zeros so how how many zeros plus zeros so how how many zeros so assuming the length of the bits so assuming the length of the bits is is five basically if if there are is is five basically if if there are like five like five uh digi five digits here i mean uh digi five digits here i mean here we we what we want to get is one here we we what we want to get is one zero zero zero that's what we're going zero zero zero that's what we're going to pass in here right so which means to pass in here right so which means we have one here and how many zeros we have one here and how many zeros basically the length of zero is the the basically the length of zero is the the length of the bits length of the bits minus two okay so we can do a zero minus two okay so we can do a zero times uh times uh the length of the bit and then and then a minus two right so that's how we get this one zero zero zero here right cool so yep i think that's it for this dfs okay now the uh the helper so the helper is i think it's quite similar as the dfs here i mean we can somehow copy these things here i mean i'll just copy this part here and then i will try to modify accordingly here of course so now we need to use this thing here right so this part and i also copy this part here so i'm going to remove this okay so i'm going to remove this okay replace that but remember for the helper replace that but remember for the helper the base case is in the the base case is in the is reversed right when it's zero we need is reversed right when it's zero we need one one wins one we need zero so that's why we wins one we need zero so that's why we have to reverse this part have to reverse this part okay now again so okay now again so now it's the time to implement this part now it's the time to implement this part remember remember in the helpers we have two cases right in the helpers we have two cases right same thing same thing if the bit is one okay so if the bit is if the bit is one okay so if the bit is one then it means that we simply we simply pass the remaining uh it's this right so uh it's this right so that's the that's the one case right so that's the that's the one case right so if it's one we simply do this we simply if it's one we simply do this we simply do a do a answer equals to df as uh answer equals to df as uh bits one right so that's the that's the bits one right so that's the that's the one case one case and for the zero case we have this uh and for the zero case we have this uh function here okay function here okay so else answer equals to uh like helper right bits one zero okay bits one zero okay plus one and then plus what plus the uh plus one and then plus what plus the uh the dfs of of this part okay the dfs of of this part okay actually it's the same of of the of this actually it's the same of of the of this part i will just copy it here because part i will just copy it here because we're also going to do a we're also going to do a the the length of the base -2 yep so that's the uh that's the implementation of the helper functions here and then yeah and then we i think we it's ready to run the code here okay so this one accept it let's let's try to submit it no what ah three zero why i'm returning at zero here let me see here i thought i did let me see here i thought i did everything right here everything right here so we have this things dfs so we have this things dfs 0 0 1 1. 0 0 1 1. um um oh here we didn't assign we didn't oh here we didn't assign we didn't assign this thing back to the answer assign this thing back to the answer right that's the that's why i think here right that's the that's why i think here oh oh okay but we did a sign here weird okay okay but we did a sign here weird okay uh uh let's try to test that three here okay um oh yeah sorry i why why define set the value twice here okay all right okay cool so now this time it's accepted this is humiliating knight is six but i'm getting okay so here we have zero okay so here we have zero uh the base case and this is the bits uh the base case and this is the bits okay helper bits plus one plus df as one zero helper is the same we reverse that and then if it's okay yeah i think because i know since it's always hard to type while you're talking basically we're trying to check if the first bit is one right and then yeah okay cool so i think this should pass all right finally cool so it's it's finally accepted cool yeah i think that's that's the first solutions here right i mean i mean this is the solution that's i approach approach and in terms of time complexity you know and in terms of time complexity you know since i think let's assume assuming that since i think let's assume assuming that the length of the bits the length of the bits is uh is n here or or the l here right is uh is n here or or the l here right so every time when we do a bit here so every time when we do a bit here right we have dfs right we have dfs and we uh we do dfs basically and we uh we do dfs basically every time when we will reduce the every time when we will reduce the length of the uh length of the uh of the bits by one until we reach the of the bits by one until we reach the the the last one so i would say like the time last one so i would say like the time complexity is something complexity is something similar like o of l which l is the similar like o of l which l is the length of the uh length of the uh the the beat the bit string the the beat the bit string okay so yeah i think that's okay so yeah i think that's that's the first solution i want to talk that's the first solution i want to talk about today i would be talking about about today i would be talking about another unusual solutions which is another unusual solutions which is called which is called the great code called which is called the great code you know you know but first let's try to let's recap this but first let's try to let's recap this solution a little bit solution a little bit basically you know for these solutions i basically you know for these solutions i mean the mean the the the main approach is that we have to be to utilize those two two options to utilize those two two options you know you know and you have to be you know you know and you have to be able to find out right so in order able to find out right so in order to to uh to change to to uh to change the values of of the none the values of of the none uh other than the rightmost bits you uh other than the rightmost bits you have to use the second rule have to use the second rule and to and to use the second rule rule and to and to use the second rule rule you have to you have to be able to transfer this original string be able to transfer this original string into something like this into something like this so that you can flip this the first so that you can flip this the first the the left most bit okay the the left most bit okay and to do that first uh you have we need and to do that first uh you have we need the helper functions basically to the helper functions basically to to uh to convert uh to uh to convert uh the remaining string into a into a one the remaining string into a into a one zero zero zero pattern okay zero zero zero pattern okay and then and then late and then we can and then and then late and then we can just uh recursively call just uh recursively call the dfs to help us to uh the dfs to help us to uh to convert the remaining right for us to convert the remaining right for us and then the next the next one will be a and then the next the next one will be a sim the next one sim the next one step is just to uh define the helper step is just to uh define the helper functions here functions here and for helper functions here they're and for helper functions here they're like there are two cases like there are two cases right so if the first if the left most right so if the first if the left most bit is one then it's easy we simply bit is one then it's easy we simply so now we just need to uh convert this so now we just need to uh convert this xxx xxx to uh to zero zero zero so that's the to uh to zero zero zero so that's the that's the definition of the dfs and that's the definition of the dfs and and for the zero case it's a little bit and for the zero case it's a little bit more complicated more complicated which means that to be able to flip zero which means that to be able to flip zero to one because that's our our to one because that's our our goal state right we have we then we will goal state right we have we then we will go back to the second go back to the second rules here so we have to somehow convert rules here so we have to somehow convert these things to uh to s these things to uh to s 0 0 0 uh s one zero zero zero zero 0 0 0 uh s one zero zero zero zero and then we can flip the first and then we can flip the first bit to one and then and then the bit to one and then and then the remaining will be uh remaining will be uh i mean we'll fall back to the dfs which i mean we'll fall back to the dfs which is to convert this one zero zero zero is to convert this one zero zero zero zero zero to zero zero to i mean to zero which we to zero zero to i mean to zero which we can just can just recursively call the dfs so hence this recursively call the dfs so hence this is the definition of the helper function is the definition of the helper function and after that it's just like a field and after that it's just like a field base case right that we need to be base case right that we need to be careful careful and then uh it's this right so for dfs and then uh it's this right so for dfs we just need to uh we just need to uh be careful with the the leading zeros be careful with the the leading zeros which will be uh skipping in this case which will be uh skipping in this case okay cool so now okay cool so now for those who are who are interested in for those who are who are interested in the second the second unusual solution this thing is called unusual solution this thing is called grey code so what is a great code grey code so what is a great code i mean for example right let's say we i mean for example right let's say we have have like this uh n equals to six here right like this uh n equals to six here right i mean i mean if you watch it closely you mean you if you watch it closely you mean you guys can see here so guys can see here so we have one one zero we have one one zero for one one zero it it converts to uh for one one zero it it converts to uh zero one zero okay and then from zero zero one zero okay and then from zero and zero it and zero it it goes to uh zero one one it goes to uh zero one one okay and then it goes to uh zero okay and then it goes to uh zero zero one and then in the end it's zero zero one and then in the end it's zero zero zero um if you up if you observe this uh long enough you might be able to find out you know basically between each of those two adjacent numbers there's only one digits difference for example right so if for this two right the difference is this one basically the the zero uh the one was changed to zero and between those those two right so not the zero becomes to one same thing for this one the this one becomes to zero and for this for the last one this is the last digit it becomes to one oh sorry the last bit digit from from one uh to i to zero so any any two adjacent numbers the difference the only there's only one bit difference and that's exactly the definition of of the gray code so you know actually there in lead code if i remember correctly there is like this midi level problem ask you to generate like the uh uh generate the uh a list of the uh after the grade code given like an integer so that's exactly what that problem is asking us to do and it tells you the definition of that i think it's number 89 or 98 i don't quite remember that but if you're guys interested you can take a look at that and so if you can realize that this is like a gray code uh format so and if you are so and if you are the uh for the for the numbers equals to three equal to three right so basically there are three uh bit bit digits and to generate to generate the degree code alpha of n equals to three right so that's going to be a what it's going to be a 0 0 0 and then it's a 0 0 1 and then 0 1 1 0 1 0 and then 1 1 0. so the next one is let's see what's the next one so the next one is one one one and then then the the one zero one and the the last one is one zero zero okay so that's the uh that's the one of the the grey code for for the digit uh for the bit size length equals to three and now you can see that so now we just need to it ha now the problem comes down to what's the how many uh the what's the the numbers right what so what's the number that's that's uh how many steps we need to convert from the uh uh from zero zero to this one one one zero so how many of that so we have a one two three and four and four it's just it happens to be our answer okay okay i i know you guys still uh confused okay i i know you guys still uh confused at this moment so let me comment out at this moment so let me comment out this algorithm here this algorithm here and then so i think and then so i think first in order to use that the gray code first in order to use that the gray code solutions you solutions you guys need to to know what's the uh guys need to to know what's the uh how did we calculate that how did we calculate that basically you know the uh basically you know the uh to calculate the uh the grid the grid to calculate the uh the grid the grid code right the gray code is the uh code right the gray code is the uh we do a i in range of the uh we do a i in range of the uh divided by by n right so and then the uh the answer is this the answer is like for example we have a list here so so the greek code is answered dot append the uh what is that the the i uh x or the uh i moved by by one so that basically that's how the how we uh calculate the uh the grid code so why is that right and okay so first we have zero zero zero we have zero zero uh zero uh zero we have zero zero uh zero uh do a right shift by one is also zero so do a right shift by one is also zero so zero zero or zero equals to what or zero equals to what equals to zero okay right so that's the that's our first that's our first grade code and now the i equals to to one here right so the or one so the one moved by right shift uh by one is also zero okay but with the xor here now we we have one here so this is like zero zero zero now we have one so now we have uh so now we have uh we have two here okay so now i we have two here okay so now i is equal to two which means is the one is equal to two which means is the one zero and zero and do x or with the what with the uh do x or with the what with the uh so 1 0 we do a right move a right shift so 1 0 we do a right move a right shift is going to become 2 0 1 is going to become 2 0 1 right so with this right so with this do it with xor we have 0 do it with xor we have 0 1 1 okay 1 1 okay and so on so first right now we have 3 and so on so first right now we have 3 here so 3 here so 3 i equals to 3 is this is 1 1 i equals to 3 is this is 1 1 and 1 right we do a so 1 and 1 right we do a so 1 and 1 we do a right shift and 1 we do a right shift by 1 it's going to be a okay right and now 1 1 dual okay right and now 1 1 dual x or with 0 1 we have x or with 0 1 we have uh let's see what we have we have uh zero one zero okay now the next one is what we have uh so now the i i equals to four right so four is this four is the uh uh one zero zero right to uh xor so this one moved by one is zero one zero so what do we have here we have a one one zero and this is the uh the answers we we need here right so it happens to be six okay i'm just doing this just trying to show you guys how do we calculate this grade code right and that's basically the formula of of calculating the uh the degree code and if you guys watch closely now we have a what do we have here we have this six here right so six it happens to be the one one zero and what's the uh the answer here so what what what's the uh the values we're looking for here basically we're looking for because i is the is the times because i is the is the times right it's the time that we got right it's the time that we got converted converted right we got to convert it how many right we got to convert it how many times it's got converted times it's got converted to the to this one two to six here to the to this one two to six here that's that happens to be our answer right because the uh you know the i represents the times right times we uh how many how many steps we have taken from zero to this one one zero that's and that's exactly what we what we need because at this moment right so the i is equal to four right so it means that because you know see the i is the index as the index to get to the current state and that's the uh that's the so basically when i equals to four we get uh by doing this i do a xor with uh i shift by right to right by one we uh we get four uh we we got this one one zero so now the problem comes down to the uh uh if you want uh with this given like uh 1 1 0 here how can we get the i here where i with this with this formula okay um so how do we do that right i mean we can see we can do a simple check here right basically you know if we draw it so with i and i uh right shift by one so with i and i uh right shift by one let's say we have a a b c d e and f a b c d e and f and this is i okay and this is i okay this is i and so so i this is i and so so i shift by one what do we have we have shift by one what do we have we have zero zero a b c d and e right so this is zero okay this is the i shaped by by one here and here we have it doesn't really matter let's say we have one zero uh one zero zero one okay and and this this and basically this is going to be our n here right so which is n here and this is formula can we get i here we can right so because you know uh let's take a look so with one here and we and remember we're doing like an uh an over here okay we're doing like an x or here so when we do an xor so to to be able to get one here so so we only get one when when these two numbers are different and with the first one equal to zero it means that a has has to be has to be one okay and when a equals to one here right and a is one a is also one we have zero zero means same when the when the numbers are the same then we have zero which means b is also one and when b is one uh we have we have one here it means that c and b has to be different now the c is zero so on so forth we have zero okay so with zero it has it means that that has to be the same so d is also zero and with d goes to zero we have zero here and e is also zero okay and with e equals to zero and we have one here so so we have one dual x or then we have we have we have one here so that's so the final answer is basically one one zero zero zero one and that's that's going to be our our i here so that's that okay cool so now the so that's that okay cool so now the problem comes down how can we problem comes down how can we calculate that right so as you guys can calculate that right so as you guys can see all we need see all we need is just like up a last digit to record is just like up a last digit to record what was the last digit and then what was the last digit and then and then we just uh with uh based on and then we just uh with uh based on the current digit the is current dj if the current digit the is current dj if it's one or zero we have a it's one or zero we have a different logic here okay different logic here okay so so what what i mean by so so what what i mean by that is this okay i'm going to comment that is this okay i'm going to comment out these things here out these things here so for for your guys reference so for for your guys reference so uh uh we have so uh uh we have answer equals to zero right and then of answer equals to zero right and then of course we have a bits course we have a bits uh yeah we we still need the bits here uh yeah we we still need the bits here okay okay so we have a bit here now uh like i said so we have a bit here now uh like i said we need the last we need the last bit right to uh to tell us the uh bit right to uh to tell us the uh what was the last one and at the what was the last one and at the beginning if you guys remember we had beginning if you guys remember we had like a zero like a zero at the beginning right so because at the at the beginning right so because at the beginning we have a b beginning we have a b c d here right and there's a a b c so at c d here right and there's a a b c so at the beginning the last digit the beginning the last digit is this one right which is zero okay is this one right which is zero okay so and cool so we have four so and cool so we have four i and bit right in enumerate i and bit right in enumerate numerator bits okay numerator bits okay so and since we're going to check to so and since we're going to check to to flip it right and i'm going to to flip it right and i'm going to convert this bit to convert this bit to its integer format first because its integer format first because remember so now the bit is remember so now the bit is is a string here so the reason i'm doing is a string here so the reason i'm doing it is it's because i it is it's because i i'll be checking that right so i'll be checking that right so uh here okay one zero one zero uh here okay one zero one zero okay so it means that okay so now we are okay so it means that okay so now we are at this this bit here right at this this bit here right so if the bit is equal to one so if the bit is equal to one so what does it means that you know so what does it means that you know it means that uh the the the answer we're looking for here has to be different as the last digit okay in this case it has to it needs to be one right so which means that let's say we have a current bit right we have current bit it means that it has to be uh i've been the opposite of the last bit which means if the last bit is zero uh this one will be one if it's one then this this one will be zero so to do that we simply do our xor we is one that's how we convert basically how we flip the numbers of this last the last bit okay so that's that and else as it means else means if the bit is zero in this case if it's zero it means that uh our this our current bit has to be the same as the last bit okay so current bit equals the last bit okay now we have the last bit now we just need to uh since we're calculating these things since we're calculating these things from left to right so from left to right so in order to do that right we just need in order to do that right we just need to do a answer to do a answer uh do a left shift by one and then we uh do a left shift by one and then we plus plus our current bit okay that's how we our current bit okay that's how we calculate because at the beginning we calculate because at the beginning we have we have one here right have we have one here right and then let's say for example let's say and then let's say for example let's say the second bit is is also the second bit is is also it's also one here so what's what's the it's also one here so what's what's the total number of this total number of this so we we have to move this left so we we have to move this left and move this the the previously and move this the the previously answered to the left by one so that we answered to the left by one so that we can can uh have a position for the current bit uh have a position for the current bit that's what we're doing here and here that's what we're doing here and here if we have a zero here right i mean we if we have a zero here right i mean we have to move the the previously answer have to move the the previously answer back uh back uh left to left by one so that we can add left to left by one so that we can add this one this one cool and yeah don't cool and yeah don't don't forget to update the last bit here don't forget to update the last bit here with the current bit okay and in the end with the current bit okay and in the end we simply return the answer we simply return the answer right like like i said that's the the right like like i said that's the the answer is the i answer is the i here cool let's try to run the code here here cool let's try to run the code here accept it submit yeah as you guys can accept it submit yeah as you guys can see this one is it's faster see this one is it's faster because i think for this one the time because i think for this one the time complex there is just complex there is just it's one right because the uh for the it's one right because the uh for the bits the length of bits is fixed bits the length of bits is fixed i think if it's in the range of 32 i think if it's in the range of 32 that's why that's why this one is much faster cool yeah i think that's pretty much everything i want to talk about for this problem yeah if you guys do have some questions just leave a comment i'll try to try my best to explain to answer it and otherwise yeah i think thank you so much for watching this video i know it's a long video thank you so much and stay tuned i'll be seeing you guys bye | 2024-03-15 18:19:02 | 1,611 | LeetCode 1611. Minimum One Bit Operations to Make Integers Zero |
|
QcY61aBwibI | hi everybody today we're going to solve a graph question from lee code a graph question from lee code number 1254 number of number 1254 number of closed islands this question is very closed islands this question is very similar to the number of islands similar to the number of islands questioned questioned but with one additional requirement so but with one additional requirement so the question says the question says given a 2d grid consisting of zeros given a 2d grid consisting of zeros representing lands representing lands and once representing water an island is and once representing water an island is a maximal four directionally connected a maximal four directionally connected group of zeros group of zeros and the closed island is an island and the closed island is an island totally oh left top right and bottom totally oh left top right and bottom surrounded by once and then we should surrounded by once and then we should return the number of closed islands return the number of closed islands for this example you're given a 2d grid for this example you're given a 2d grid with zeros and ones with zeros and ones islands of four directionally connected islands of four directionally connected zeros top left right and bottom zeros top left right and bottom and closed islands are completely and closed islands are completely surrounded by once surrounded by once and you should count the number of and you should count the number of closed islands closed islands for this example the total number of for this example the total number of closed eye lens would be two closed eye lens would be two so you're given this grid this 2d matrix so you're given this grid this 2d matrix and you should return 2 and you should return 2 as the output because this grid has 2 as the output because this grid has 2 closed islands so let's manually check closed islands so let's manually check the number of closed islands the number of closed islands based in this example we can see that we based in this example we can see that we have 4 have 4 directionally connected zeros here so we directionally connected zeros here so we mark that mark that as a potential island that's this this as a potential island that's this this this and this so they're connected this and this so they're connected at the top at the left at the bottom at the top at the left at the bottom and at the right so four directionally and at the right so four directionally connected zeros connected zeros is a potential island and a closed is a potential island and a closed island island is one that's completely surrounded by is one that's completely surrounded by ones ones so we can see that this island is also so we can see that this island is also completely surrounded completely surrounded by once so this is a closed by once so this is a closed island we can also see another instance island we can also see another instance of zero here of zero here this is a lone island with just one zero this is a lone island with just one zero and that's something you might want to and that's something you might want to clarify with your interviewer clarify with your interviewer but an island with just one zero is but an island with just one zero is valid at least for this example valid at least for this example and it's completely surrounded by once and it's completely surrounded by once so it's a valid closed island so it's a valid closed island so let's mark that so this so let's mark that so this is a lone island with just one instance is a lone island with just one instance of zero of zero which you might want to clarify with which you might want to clarify with your interviewer which your interviewer which is completely surrounded by once is completely surrounded by once here here here here so it's a valid here here here here so it's a valid closed closed island we do have other instances of island we do have other instances of zeros that could potentially zeros that could potentially be closed islands for this example here be closed islands for this example here uh uh this one at the top also not a closed this one at the top also not a closed island because it's not completely island because it's not completely surrounded by uh by once i'm not also surrounded by uh by once i'm not also sure if it could be a valid island sure if it could be a valid island because it's not four directionally because it's not four directionally connected zeros just one connected zeros just one not at the left um right and not at the left um right and it's only connected at the top and at it's only connected at the top and at the bottom so might be a potential the bottom so might be a potential island but not a closed island because island but not a closed island because it's not completely surrounded by once it's not completely surrounded by once it's only surrounded by ones on the left it's only surrounded by ones on the left side side so how do we solve this question the so how do we solve this question the first thing we should note is that we first thing we should note is that we first of all have to determine whether first of all have to determine whether something is an island something is an island before checking if it's a closed island before checking if it's a closed island any four directionally connected series any four directionally connected series of zeros of zeros could be a closed island so when we could be a closed island so when we encounter a particular instance of zero encounter a particular instance of zero in the 2d grid um as you know i'm going in the 2d grid um as you know i'm going to be using the words to be using the words grids and matrices interchangeably we grids and matrices interchangeably we just know they mean the same thing in just know they mean the same thing in this context this context so when we encounter a particular so when we encounter a particular instance of zero in the 2d grid instance of zero in the 2d grid we can proceed to run a depth first we can proceed to run a depth first search on its four search on its four neighbors to see if we can get a series neighbors to see if we can get a series of directionally connected zeros of directionally connected zeros while doing the depth first search if we while doing the depth first search if we encounter a 1 encounter a 1 we stop traversing that path and keep we stop traversing that path and keep traversing other paths traversing other paths if we have fully exhausted all the paths if we have fully exhausted all the paths without going out of bounds without going out of bounds then we know that this is a valid closed then we know that this is a valid closed island because we exhausted all the island because we exhausted all the paths paths and then we encountered once without and then we encountered once without going out of bounds going out of bounds if we ever go out of bounds without if we ever go out of bounds without seeing a 1 then it's not a valid closed seeing a 1 then it's not a valid closed island so i'm going to do a quick island so i'm going to do a quick simulation of how this would work simulation of how this would work so we're traversing this 2d matrix and so we're traversing this 2d matrix and we encounter we encounter an instance of zero in this case let's an instance of zero in this case let's say we encounter say we encounter this instance of zero so when we this instance of zero so when we encounter this instance of zero encounter this instance of zero we then proceed to run a depth first we then proceed to run a depth first search and check search and check for all its four neighbors so we run a for all its four neighbors so we run a dfs here dfs here dfs here dfs here and dfs here dfs here and here and here so if we encounter a one here and here so if we encounter a one we don't actually stop the dfs um we don't actually stop the dfs um completely completely we just stop traversing that path and we just stop traversing that path and keep traversing all the paths keep traversing all the paths so for this one we've encountered a one so for this one we've encountered a one here so we stop traversing this path we here so we stop traversing this path we encounter one here stop traversing this encounter one here stop traversing this path encounter one here path encounter one here stop traversing this path but notice stop traversing this path but notice that the path that the path on the right this path has a zero to it on the right this path has a zero to it so in this other zero that we encounter so in this other zero that we encounter on the right on the right we're going to keep traversing its other we're going to keep traversing its other neighbors we run a dfs here neighbors we run a dfs here for each other neighbors run a dfs here for each other neighbors run a dfs here uh we don't run a dfs here because we're uh we don't run a dfs here because we're going to have a case that checks for going to have a case that checks for that since we've already checked it that since we've already checked it when the df is here and here so at the when the df is here and here so at the top top we see that it's a one so we stop we see that it's a one so we stop traversing this path traversing this path and then keep traversing its other paths and then keep traversing its other paths the other paths have another instance of the other paths have another instance of zero zero that's this one here so we proceed to that's this one here so we proceed to run a dfs run a dfs on its four neighbors so that's this one on its four neighbors so that's this one this one this one at the top we don't go this one this one at the top we don't go to the left because we've already to the left because we've already um gone through it we're gonna have a um gone through it we're gonna have a check that checks for that check that checks for that and then this one has an instance of one and then this one has an instance of one so we stopped reversing so we stopped reversing and then we come to this other guy here and then we come to this other guy here we also do the same thing we also do the same thing we go to its four neighbors which is top we go to its four neighbors which is top right left we don't check bottom we right left we don't check bottom we check and then check and then we've encountered all of them have we've encountered all of them have a one so we stop this path stop this a one so we stop this path stop this path path stop this path and then stop this path stop this path and then stop this path but notice that we already have other but notice that we already have other depth-first searches depth-first searches running on these paths that have zeros running on these paths that have zeros that we haven't checked that we haven't checked uh the bottom neighbors the left uh the bottom neighbors the left neighbor neighbor and then we'll do that for this path as and then we'll do that for this path as well so when we come here well so when we come here it's an instance of zero we check its it's an instance of zero we check its four neighbors this also has an instance four neighbors this also has an instance of of one at its bottom neighbor so we stop one at its bottom neighbor so we stop this dfs this dfs we stop it here also and then we do the we stop it here also and then we do the same thing same thing for its other neighbors which is this for its other neighbors which is this one and then we come down one and then we come down uh you kind of get the idea we get a one uh you kind of get the idea we get a one and then we go to this other guy that's and then we go to this other guy that's a zero so the guy's a zero a zero so the guy's a zero and then they both have ones at the and then they both have ones at the bottom so we stop here bottom so we stop here stop here stop here so this is it after stop here stop here so this is it after we've we've completely exhausted all the paths and completely exhausted all the paths and then we've encountered once without then we've encountered once without going going out of bounds without going out of out of bounds without going out of bounds in this 2d grid bounds in this 2d grid then we know that this is a valid closed then we know that this is a valid closed island island so this is how you solve this question so this is how you solve this question as always with these types of questions as always with these types of questions we need to mark the cells that we've we need to mark the cells that we've visited so we don't count them again visited so we don't count them again if not we're going to have the risk of if not we're going to have the risk of running into running into a potential cycle and we don't want that a potential cycle and we don't want that so how we're gonna do this so how we're gonna do this is to change the value of zeros that is to change the value of zeros that we've already seen we've already seen as part of a series to a one as part of a series to a one so we don't get to that again so for so we don't get to that again so for instance when we've encountered this instance when we've encountered this zero here zero here we change its value to one uh gonna this we change its value to one uh gonna this is going to be messy is going to be messy we change its value to one so when we're we change its value to one so when we're on this path and we're checking its four on this path and we're checking its four neighbors we check to the left and we neighbors we check to the left and we see see oh this is a one so we don't check it so oh this is a one so we don't check it so after encountering a zero after encountering a zero in a particular series we have to change in a particular series we have to change the value to one so we don't come back the value to one so we don't come back to it again to it again and we're going to do this for all these and we're going to do this for all these zeros in this zeros in this in this island i hope this makes sense in this island i hope this makes sense to you and now we're going to proceed to to you and now we're going to proceed to the time and space complexity the time and space complexity the time complexity for this algorithm the time complexity for this algorithm would be o of n would be o of n in the average case since we're going in the average case since we're going through all the cells in the grid through all the cells in the grid in the worst case it could potentially in the worst case it could potentially go above that because uh go above that because uh we can also do potentially an amount of we can also do potentially an amount of work for the dfs work for the dfs and while doing the iteration uh and while doing the iteration uh traversing the matrix we could also do traversing the matrix we could also do an amount of work an amount of work but that's in the worst case for but that's in the worst case for instance consider like you have a instance consider like you have a huge 2d grid of like just once huge 2d grid of like just once on the edges on all the edges top left on the edges on all the edges top left right and bottom right and bottom and then zeros in the middle completely and then zeros in the middle completely filled with zeros in the middle filled with zeros in the middle what you'll find is when you encounter a what you'll find is when you encounter a particular instance of zero particular instance of zero in the middle you're going to in the middle you're going to potentially do an amount of work potentially do an amount of work on the dfs and you're also going to go on the dfs and you're also going to go into the iterative into the iterative approach while you're iterating through approach while you're iterating through to check for zeros to check for zeros now you're not going to hit the dfs now you're not going to hit the dfs again but you're still going to check again but you're still going to check whether because we're going to change whether because we're going to change all the zeros to once so when you're all the zeros to once so when you're going back you're going to check whether going back you're going to check whether it's a 1 or it's a 0. it's a 1 or it's a 0. you're not going to hit the dfs again you're not going to hit the dfs again but you're still going to do that check but you're still going to do that check but in the average case it's o oven in but in the average case it's o oven in terms of terms of space complexity space complexity would space complexity space complexity would run run in of d because we're going to have a in of d because we're going to have a recursive dfs search which would store recursive dfs search which would store frames on the cool stack frames on the cool stack and the number of frames in the code and the number of frames in the code stack would be as much as the deepest stack would be as much as the deepest path path so we'll say space complexity is o of t so we'll say space complexity is o of t where d where d is the depth of the deepest path so is the depth of the deepest path so that's it let's dive into the code that's it let's dive into the code alrighty so we have our closed island alrighty so we have our closed island function here it should return an function here it should return an integer integer we also have our input 2d grid so the we also have our input 2d grid so the first thing we want to do is initialize first thing we want to do is initialize a counter variable a counter variable so our initialized count we set it to so our initialized count we set it to zero and then now we're going to iterate zero and then now we're going to iterate through through uh the 2d grid this is going to be a uh the 2d grid this is going to be a nested for loop nested for loop so for an i is equal to zero i is less so for an i is equal to zero i is less than than i would say grid.length and then i plus i would say grid.length and then i plus plus plus that's not the way you spell length i'm that's not the way you spell length i'm gonna fix it and then gonna fix it and then you say for j j is gonna go through the you say for j j is gonna go through the columns columns so j is less than let's say grid of i so j is less than let's say grid of i dot length j plus plus dot length j plus plus and now we have access to grid of i and and now we have access to grid of i and j a particular cell in this grid and j a particular cell in this grid and then we can check if that grid then we can check if that grid is equal to a zero is equal to a zero so if grid of i j was equal to zero so if grid of i j was equal to zero this could be a potential island so this could be a potential island so whenever we encounter an instance of whenever we encounter an instance of zero zero we're going to run all run a dfs we're going to run all run a dfs on this instance of zero on this instance of zero because it could be a potential island because it could be a potential island let me fix the length spelling let me fix the length spelling and then we're here so we're gonna and then we're here so we're gonna declare like a declare like a a method that returns say a boolean a method that returns say a boolean value value if it's a closed island and then we add if it's a closed island and then we add one to it so let's say one to it so let's say boolean uh closed uh boolean uh closed uh the method would be called is closed we the method would be called is closed we haven't made it yet we'll make it soon haven't made it yet we'll make it soon bear with me and then we pass the grid bear with me and then we pass the grid we pass i and j we pass i and j into it and then we can check into it and then we can check if closed if this returns true then we if closed if this returns true then we increase the count increase the count plus one so now let's define the close plus one so now let's define the close um um method that we just used here method that we just used here so we have a public boolean so we have a public boolean is closed it takes in a 2d is closed it takes in a 2d grid takes in a row and it also takes in grid takes in a row and it also takes in a column so for this a column so for this we're going to have a base case that we're going to have a base case that checks this is our depth first search by checks this is our depth first search by the way the way we're going to have a base case that we're going to have a base case that checks if we're not out of bounds so if checks if we're not out of bounds so if rho rho is less than zero or the value of the is less than zero or the value of the row is greater than grid the length row is greater than grid the length mints were so far down that we're out of mints were so far down that we're out of bounds bounds and then we have column is less than and then we have column is less than zero means we're so far left that we're zero means we're so far left that we're out of bounds out of bounds or the column is greater than or equal or the column is greater than or equal to the grid to the grid of row dot length means we're so far of row dot length means we're so far right that we're out of bounds if this right that we're out of bounds if this is ever the case is ever the case then we can just go ahead and return then we can just go ahead and return false because we know that we're out of false because we know that we're out of bounds so we turn false bounds so we turn false so this is the base case otherwise if so this is the base case otherwise if we're not out of bounds then we can we're not out of bounds then we can check check to see if this value is a zero or a one to see if this value is a zero or a one remember if this value is remember if this value is a one then we can just stop traversing a one then we can just stop traversing this path this path so if grid of row so if grid of row and column is equal to you guessed it and column is equal to you guessed it one then we can just return true and one then we can just return true and stop traversing this path so returning stop traversing this path so returning true because we don't want to return true because we don't want to return false and then stop the whole dfs false and then stop the whole dfs and then if it's a one otherwise if it's and then if it's a one otherwise if it's not a one not a one it's going to be a zero so if it's a it's going to be a zero so if it's a zero then we have to change the value zero then we have to change the value of comments change the value of comments change the value to 1 so we don't come here again to 1 so we don't come here again so we're going to set grid of row so we're going to set grid of row and column is equal to 1. so this is a and column is equal to 1. so this is a quick check quick check that makes sure that we mark the cell as that makes sure that we mark the cell as visited so we don't visited so we don't come here again i'm going to do a more come here again i'm going to do a more detailed comments detailed comments for the code that i upload to github so for the code that i upload to github so please check it out and then please check it out and then we're going to run a dfs on its four we're going to run a dfs on its four neighbors so we're going to have a neighbors so we're going to have a boolean variable boolean variable we call it bottom this is going to check we call it bottom this is going to check for its bottom neighbor for its bottom neighbor so this is is closed we call the same so this is is closed we call the same function function that's why it's called recursion i have that's why it's called recursion i have grid grid row plus one it's going to go at the row plus one it's going to go at the bottom and then we have column bottom and then we have column uh this is for bottom and then we have uh this is for bottom and then we have another variable another variable this is going to check for the right this is going to check for the right neighbor neighbor let's call it right uh is closed let's call it right uh is closed we pass in the grid we pass in the row we pass in the grid we pass in the row and then we pass in column plus one just and then we pass in column plus one just gonna check for the right gonna check for the right and just call this right and then we and just call this right and then we have another one for the left have another one for the left this is gonna be is closed this is gonna be is closed we pass in the same grid same row now we pass in the same grid same row now column column minus one and then this is going to be minus one and then this is going to be left left and then we have another one for the top and then we have another one for the top and this is going to be is closed we and this is going to be is closed we have grid have grid pass in the same grid now row becomes pass in the same grid now row becomes row minus one and our column remains the row minus one and our column remains the same same and this is going to be for the top so and this is going to be for the top so this is going to run four dfs searches this is going to run four dfs searches on its four neighbors on its four neighbors and now we want to make sure that all of and now we want to make sure that all of these return true these return true because they're only going to return because they're only going to return true if they encounter a one at the true if they encounter a one at the particular path particular path so we return at the end bottom so we return at the end bottom returns true and right returns true returns true and right returns true and top returns true and left also and top returns true and left also returns true returns true they're only going to return true if we they're only going to return true if we encounter a one before encounter a one before going out of bounds awesome so this is going out of bounds awesome so this is the method the method and then here if it's close we call this and then here if it's close we call this method method and then we increase count plus one now and then we increase count plus one now the only thing we have to do the only thing we have to do is return count that's it that's how you is return count that's it that's how you solve this question let's run this solve this question let's run this and see what happens awesome it's and see what happens awesome it's accepted i'm gonna submit it accepted i'm gonna submit it yeah it's uh it's successful and it's yeah it's uh it's successful and it's really fast really fast so that's how you solve this question so that's how you solve this question guys uh i hope you learned something guys uh i hope you learned something from it from it well in my experience asking clarifying well in my experience asking clarifying questions is a major part of the questions is a major part of the interview interview so please let me know if you want to me so please let me know if you want to me to include some of the clarifying to include some of the clarifying questions that you might ask for a questions that you might ask for a particular question particular question you know like inputs edge cases uh in my you know like inputs edge cases uh in my videos and i will do that videos and i will do that so comment down below let me know what so comment down below let me know what you think so that's how you solve this you think so that's how you solve this question if you like this type of question if you like this type of content please consider subscribing to content please consider subscribing to the channel the channel share this video on the community smash share this video on the community smash the like button for the youtube the like button for the youtube algorithm algorithm comment down below if you have something comment down below if you have something to say and i'll see you in the next one bye | 2024-03-19 17:27:52 | 1,254 | Number of Closed Islands | LeetCode 1254 |
|
PCzyU_qL5AM | Effect of Come in City Will Discuss Your Problems and a Good Practice Problem Problems and a Good Practice Problem Number S-10 600 800 How to Problem Previous Number S-10 600 800 How to Problem Previous Two Pure Problem Statement Saying You This Collection and Stones is a Stone When Positive and subscribe the Channel Please and subscirbe and subscirbe and subscirbe kal su appeal will see a kal su appeal will see a distinguished to example som political science the distinguished to example som political science the winners in three ok channel every element is winners in three ok channel every element is point office to every time you will have to pay point office to every time you will have to pay a a and pintu highest slips to share the and pintu highest slips to share the first hai bittu stories 80 to them first hai bittu stories 80 to them inconsistent check subscribe The Channel 2451 subscribe to hai subscribe The Channel 2451 subscribe to hai next time in new topic on next time in new topic on jiomusic to every fluid floor and to its jiomusic to every fluid floor and to its key and differences to su 22.51 key and differences to su 22.51 phone number is trick height acidity 2.1 phone number is trick height acidity 2.1 difference is lineage effects to the native with difference is lineage effects to the native with a big station between itself a big station between itself a big station between itself Contested Polls While Some Differences 0 Friends Paper Solved With One And Only One Will Be Given To So Alas At The Time Of Vansh Arise And So Alas At The Time Of Vansh Arise And That Nothing Can Visit Us At Same One Was That Nothing Can Visit Us At Same One Was Left With Differences 09 2012 When Glass Left With Differences 09 2012 When Glass Is Broken And Arrival To This Position In Jawa Aa And Arrival To This Position In Jawa Aa And Arrival To This Position In Jawa Aa Birthday To You And Sunao Then Difficult Problems And Sunao And Laughter They Need Active Left Which Suit States Were Doing First Step More Into Every Storm On We Will Bring You To Harishchandra For 20 Minutes Sentence with same to oo ke din but this trick dil vigrate difference office to it back into the I am behind it a cigarette global economic Indian servi a cigarette global economic Indian servi servi dil report servi dil report tomorrow su up into her best to generation tomorrow su up into her best to generation supporting but set supporting but set supporting but set Subscribe To's Comfort Is Produce Problem That Needle Normalized Money On This Photo A Superlative Inspired Other Day Updater Have To Think How To Make A Game And Where To Check The Next Come 12.28 Will Get Located Difference Between The Two Difference Between The Two Difference Between The Two Retail Pack Looting Back Retail Pack Looting Back A Victim Has Never Had To Find The A Victim Has Never Had To Find The Maximum Minimum Set Max Planck Maximum Minimum Set Max Planck Institute For Looting In School Me Sonth Developed In The Other It Is Not Reflecting Upon A Time When Ever Taken Back In The Distic One Chakra Chakra Chakra Ki Can Help Us In This Case Ki Can Help Us In This Case So So So So Remember What Is That Don't Get So So So So Remember What Is That Don't Get A Structure Which Will Always Give Me The A Structure Which Will Always Give Me The Highest Element Pepperment Is Remedy Hai Highest Element Pepperment Is Remedy Hai 125 I Pick And Tagged Statement 125 I Pick And Tagged Statement Outfits Words Outfits Words A Requested Status Questions Page A Requested Status Questions Page President Will Quit Comment President Will Quit Comment President Will Quit Comment that this is the same and something to get a structure relative that this is the same and something to get a structure relative automatically modified just automatically modified just how to take and give me the house film the how to take and give me the house film the swift deliverer from the same options swift deliverer from the same options updates the loop updates the loop this time frill slow this this time frill slow this is so then I no numbers and you will get any is so then I no numbers and you will get any If you are happy enemy but for If you are happy enemy but for profit subscribe to I profit subscribe to I want you to high school at you will get want you to high school at you will get in we fight positive group are those who have in we fight positive group are those who have village text sidhu loot-loot subscribe Video subscribe subscribe to the students to a hit is the good choice students to a hit is the good choice that that that How Little Things Pay Next Key Facility Program New Super Store Here Designer Maximum subscribe and subscribe the Channel Please subscribe and subscribe the Play List This Too Phone The Input Tray Weeks Hind Desh Hai Mix It Open Store Open Store Open Store New Delhi Stories And A Massive And Stuart And Stuart And Sunao The Match Declared Photo Are Different This And Sunao The Match Declared Photo Are Different This Film With Obscene Mail Send That Film With Obscene Mail Send That New Item Different Oil Filter And Oil That New Item Different Oil Filter And Oil That Playing With This By Playing With This By Maximizing That Maximizing That Sudhir To Get So Thokta Hai Sudhir To Get So Thokta Hai A look size duets to sanch ki should be but incomplete ko suhaagin kitchen retention the sizes is vansh rate so imported to subscribe to main day bhar due to il spoch to first elementum settings hua hi is the fastest man made it's next flight Take Take Take A Sweat In Return To The First Festival 200 Is All About This Cool Message Do Call Me 200 Is All About This Cool Message Do Call Me Three Minutes Ago Vitamin Root Element And Three Minutes Ago Vitamin Root Element And To Do Don't Forget To Subscribe And Subscribe Is While That's Is While That's Not Equal To subscribe to subscribe to is so ifin there is this is so ifin there is this new Delhi ex showroom in this manner of this example new Delhi ex showroom in this manner of this example my vice president and eggs subscribe to improve time to improve time that he nautical tricks and determination and that he nautical tricks and determination and defeat at this point - 6 subscribe sunna hai Re Written Complaint Police Complaint At Re Written Complaint Police Complaint At Re Written Complaint Police Complaint At Last Way Subscribe To Channel Just Stop Subscribe Subscribe Suggest Hai Se Mix Itne Dot Size Were British 1221 Divya Ko Return Se Mix Itra Dots Hai Pimple Last Present Distic Institute Of Medical Research Root Element Paun inch this liquid Subscribe 0 [Music] A look on hua tha so let's Ramdev was not arrested ok so running dir with submit picture ki this distance id ki and teaching staff nurses and This election na This election na This election na tomorrow morning get fat solution 9th class and tomorrow morning get fat solution 9th class and share with your prescription share with your prescription torch start winning torch start winning MP3 money loot | 2024-03-25 15:52:01 | 1,046 | Leetcode: 1046 , Last Stone Weight |
|
y3I5apfwoKo | So Frog Jump So this is Lead Quote's 403 challenge so come on guys let's see what the problem is A frog crossing a river The river is divided into some number of units and at each unit there may not exist a The frog can jump on a stone but it The frog can jump on a stone but it The frog can jump on a stone but it must not jump into the water. It means that suppose must not jump into the water. It means that suppose we have given a river and somewhere in the river we have we have given a river and somewhere in the river we have placed stones at some position, placed stones at some position, okay and whatever those stones are there is random. okay and whatever those stones are there is random. okay and whatever those stones are there is random. in ascending order but the stones will be placed one after the other. This is not necessary. It is not necessary. The distance between them can be varied. It is okay. Given a list of stones positions means the positions of each stone are Ascending Ascending Ascending Order Determine If the Frog Can Cross the River by Order Determine If the Frog Can Cross the River by Landing on the Last Stone Landing on the Last Stone Initially the frog is on the first stone Initially the frog is on the first stone and assume the first jump must be one unit. What this and assume the first jump must be one unit. What this means is that our frog will means is that our frog will initially be sitting on the first stone and assume the first jump must be one unit. initially be sitting on the first stone and assume the first jump must be one unit. initially be sitting on the first stone and assume the first jump must be one unit. initial jump that the stone can take is one unit. This is given to us. Okay, if the frog jump was k units, its next jump must be between k -1 k and k + 1 units. Frog can only jump in the forward direction. So come on friend, let us understand this well through a diagram. The Google's position is Google's position is actually given in the form of an array and its indices are given. Let us actually given in the form of an array and its indices are given. Let us understand this through a diagram understand this through a diagram like this. like this. like this. first stone, looks like this, the second stone looks like this, and the third stone, there is water there, okay, and the position of our fourth stone is this, and the position of our stones is something like this. What we have been given initially is that our frog is sitting on the first stone and from here he can take a jump of one unit. Okay, so we have assumed that the frog jumped from here and came here. Now how far can he jump from here? Can take jumps, if our frog had reached this stone on the second stone in the last jump, then from here he can take a jump of K, can take a jump of K, and can take a jump of K, okay, so here What was its last jump? k = 1 ok, it was reached in one jump, now from here 1 pv that is two, it can take two jumps, it is right here, it is here, from here one, two, it And what is And what is And what is one? If he jumps only one, he will one? If he jumps only one, he will reach this stone and that is 1 minus zero. Okay, so is there reach this stone and that is 1 minus zero. Okay, so is there any benefit in going back, so if any benefit in going back, so if that value is coming to zero or less than zero, that value is coming to zero or less than zero, then we will ignore it. then we will ignore it. then we will ignore it. in this case, let us assume that he had reached this eye stone in some cath jump. Okay, so at this position, we will explore all the possibilities as to where else he is able to go from here. Okay, if at the end, our Frog is, out of all the possibilities, if it comes to the end stone in any one of the possibilities, then we will assume that we will return Tr. Okay, in this case, because we want to return Tr, we have to We have to We have to We have to deliver the last stone or the last index deliver the last stone or the last index which is our 17th last stone. If our frog comes which is our 17th last stone. If our frog comes here, then brother here, then brother bye bye, if it doesn't come then return false to us. bye bye, if it doesn't come then return false to us. Okay, so come friend, let's see Okay, so come friend, let's see how we will approach this. how we will approach this. how we will approach this. How will we solve this? So on the other hand we can use SAP in the sense. We use the concept of Yup. What we do is we put all our stocks in the map. What was their What was their What was their position, what was it, it was okay, position, what was it, it was okay, zero and zero and 3, 6, 8, 12 and 17, let's just write down these, we will 3, 6, 8, 12 and 17, let's just write down these, we will not store them, tooth not store them, tooth 4, 4, 5, sorry, 5, sorry, tooth four, 5, 6, tooth four, 5, 6, these are these are our cusp, we will store a set. our cusp, we will store a set. our cusp, we will store a set. store it, let's see, okay, pay attention, okay, now initially what we have been given is that our frog is sitting at the zero position, okay, from here it can jump to the first position, so Take the first stone Take the first stone Take the first stone cadence and store its cusp one, what is this one, cadence and store its cusp one, what is this one, this one is ours, which is this one is ours, which is our first stone in the jump, I mean, our first stone in the jump, I mean, our frog which is our frog which is in the forest can jump from the first stone, it is okay, so we in the forest can jump from the first stone, it is okay, so we Here, we will take out the number corresponding to zero and from that we will see to which position our frock can go. Okay, suppose we have taken out one from it. On the cusp of the corresponding stone of the first stone, we will store that jump. cusp of the corresponding stone of the first stone, we will store that jump. Okay, here in which jump did he Okay, here in which jump did he come, we have made 1 psv, that means two, come, we have made 1 psv, that means two, in the second jump, that means two units of jump, in the in the second jump, that means two units of jump, in the third jump, our cusp has come, so here we third jump, our cusp has come, so here we store two, okay here we have paid store two, okay here we have paid two. two. two. possibilities, either just what did he do? He took a jump of 1 pv. If he had taken a jump of only one i.e. if he had taken a jump of only k then he would have been able to reach here near our first stone. If it If it If it comes close, here we will store one comes close, here we will store one that it came here in one unit of jumps that it came here in one unit of jumps and what is the possibility 1 - 1 0 friend, if and what is the possibility 1 - 1 0 friend, if zero value comes, we will stay there, if zero value comes, we will stay there, if negative value comes, we will ignore it negative value comes, we will ignore it because we because we because we either, we don't want to get stuck there, okay, we have explored this, we have explored the corresponding values of this stone, okay, now we come to our second stone, Value store Value store Value store is one. One is value store. What does one mean? This is is one. One is value store. What does one mean? This is its Keith jump. Okay, here it its Keith jump. Okay, here it came in Keith jump. Unit of jump came in it. came in Keith jump. Unit of jump came in it. Now let's explore it. Okay, Now let's explore it. Okay, we took out one. Okay, now where from one to where? we took out one. Okay, now where from one to where? we took out one. Okay, now where from one to where? can go 1 pv ok 1 2 On our fifth index pe I mean on the fifth stone it can come in how many units of jumps it came in two units of jumps ok and what is a possibility this is only one unit Take, if it takes a jump of only one unit, Take, if it takes a jump of only one unit, Take, if it takes a jump of only one unit, then it will come to its third stone, third then it will come to its third stone, third means second stone, so here we will store one, means second stone, so here we will store one, okay and 1 -1 0, again the same thing, so okay and 1 -1 0, again the same thing, so we will ignore it, okay this too. we will ignore it, okay this too. We have explored it, now let's come to this, We have explored it, now let's come to this, first of all we will take out two and from two we will first of all we will take out two and from two we will see what are all the possibilities. see what are all the possibilities. If we do 2 then we If we do 2 then we can take three units of jump. What will be the jump of three units from here? can take three units of jump. What will be the jump of three units from here? One or two is fine. One or two is fine. One or two is fine. stone I mean one two three on the cusp of our eighth stone we will store it by taking a jump of three units, it is okay if we take a jump of only one unit from here i.e. a jump of only two units then If we take If we take If we take one, then it one, then it is okay only here. We have explored one. is okay only here. We have explored one. If we take 1, then If we take 1, then who will come here, in how many jams, two who will come here, in how many jams, two jams are fine, so there is no benefit in storing duplicates here. jams are fine, so there is no benefit in storing duplicates here. No, so we will use set, it will No, so we will use set, it will automatically ignore the duplicate, automatically ignore the duplicate, okay, we have two already stores, if we okay, we have two already stores, if we jump one unit, we will come here, there is one already jump one unit, we will come here, there is one already store, 1 mine, if it is of no use, store, 1 mine, if it is of no use, then we will ignore it, we also then we will ignore it, we also explored it. explored it. explored it. we will take two, now two is okay, we can take a jump of three units from here, one, two, three, okay, then we will come to the 12th stone, it is okay if we take a Meaning if we take only two Meaning if we take only two Meaning if we take only two then one or two will come here only and then one or two will come here only and if we take only k -1 jump then if we take only k -1 jump then only one will come here so we only one will come here so we correspond to this 1 + 1 2 two are already stored if Already stored is 1 -1 zero Already stored is 1 -1 zero Already stored is 1 -1 zero so there is no use of it, now so there is no use of it, now let's explore it. Okay, from the extract we let's explore it. Okay, from the extract we can write a can write a couplet. The catch here is that if couplet. The catch here is that if our stone is at any position, I mean, which is our frog our stone is at any position, I mean, which is our frog and the last one. and the last one. and the last one. what will we do at the same position, will we make it it is done, okay, this is our it is done, okay, this is our question, if suppose in the end, at some question, if suppose in the end, at some time, our frog is not time, our frog is not able to reach here, okay here? able to reach here, okay here? able to reach here, okay here? were different positions, then how would one become such that it is not able to reach here. If it is not able to reach here, then we will come out of the loop and we will return false there. Okay, so this is our That friend, let's code this and go That friend, let's code this and go That friend, let's code this and go ahead, friend, let's come and code, ahead, friend, let's come and code, what will we do, will we create a name, what will we do, store all the stones in the map, It is given to us It is given to us It is given to us that we can take the first jump and neither that we can take the first jump and neither can we take the first jump of the unit, so what do we do after can we take the first jump of the unit, so what do we do after storing that, okay, then storing that, okay, then M of stone of now let's explore all of them, let's keep it in our current stone. Let's take a set. What are we going to store in the set? Its cusp set is S is equal S is equal to a of. We're going to explore this. Okay, we're going to take a look at it. Now, what we want to see is what we want to see If we are jumping at a position, does the If we are jumping at a position, does the If we are jumping at a position, does the stone exist in our array stone exist in our array or not? If it exists, then only we will or not? If it exists, then only we will go to it. If it does not exist, then go to it. If it does not exist, then we will not go, only then we have to do some work, otherwise we do not have to do it We have three possibilities of yours, K, We have three possibilities of yours, K, We have three possibilities of yours, K, P, K and K. Let's explore it. It is human, it is greater than zero. Okay, if we are doing minus then it should be greater than zero, only then we will explore that point, otherwise we will not do it. What will we do? M is off Let's do errt aa possibility let's possibility let's do i mean insert ya how do we know that our frog has reached the end so we put a not condition here if If the If the If the stock of stock of stock is equal to size mini, it means that the frock has stock is equal to size mini, it means that the frock has reached the end, so we will return it and if our return is not true anywhere, then and if our return is not true anywhere, then we will return it. If it is false then the answer is correct. then the answer is correct. then the answer is correct. then it has been submitted, ok, then it has been submitted, ok, that's all in this video, thank you for watching and see you that's all in this video, thank you for watching and see you next time. | 2024-03-21 18:44:22 | 403 | Frog Jump Leetcode - 403 || easy explanation || dynamic programming || C++ Code |
|
VpSPRN5BWIo | everyone welcome back to my channel so today we will solve one medium level so today we will solve one medium level question so till now we are solving easy question so till now we are solving easy level questions today we'll go with one level questions today we'll go with one medium question medium question it's called rotate image it's called rotate image let's understand the problem statement let's understand the problem statement and try to solve it so it's very and try to solve it so it's very interesting question and interesting question and let's see how let's see how uh it proceeds uh it proceeds so you are given an n by n 2d matrix so you are given an n by n 2d matrix representing an image representing an image rotate the image by 90 degrees clockwise rotate the image by 90 degrees clockwise so so a matrix image will be given it can be n a matrix image will be given it can be n by n by n okay okay 3 by 3 or 4 by 4 matrix will be given 3 by 3 or 4 by 4 matrix will be given we have to rotate it by 90 degrees so we have to rotate it by 90 degrees so this matrix if you see one two three this matrix if you see one two three four five six seven eight nine if you four five six seven eight nine if you rotate clockwise rotate clockwise so so in the clockwise direction if you're in the clockwise direction if you're rotated by 90 degrees what will happen whatever uh this row will there be the first row will be there right it will become the last column second row will become the last second column third row will become first call so similarly if you take this example four by four matrix same thing if you rotate by 90 degrees so this first row will become last column similarly second row last but uh last but second this third row will become second column this third row will become second column and fourth row will come first column and fourth row will come first column so constraints also we have to see and one more condition you have to see you have to rotate the image in place so this thing he is for he has focused here so you should not take another array and you should and copy that so here you have to rotate without taking extra space okay time complete space complexity should be should be of one and we should not use any other matrix let us understand how will solve this let us understand how will solve this the logic will be right what we will do the logic will be right what we will do first first we will take the transpose of this we will take the transpose of this matrix matrix and after that and after that we will we will reverse this reverse this row row so so ah one two three four five six seven ah one two three four five six seven eight nine for this example if you take eight nine for this example if you take transpose transpose it will be like it will be like one two one two three these values will come here and these values will go here and after that if you swap the rows right then we'll get the out resultant output so let's try to solve this first step transpose of a matrix transpose of a matrix and in the second step reverse so transpose of a matrix let us see how we can do so let's try to write the code for that what i'll do first i'll i trade through the rows current i equal to 0 i less than matrix dot length i plus plus so this loop is used for iterating each row okay now we'll take another nested loop here for and j equal to i j less than column length so what is a column length if you take the length of one row that will be the column length j plus plus so why i have taken i here if you take the first row by rotating first row will start from this first value and if you take the second row will start from the second value so here if we are only flipping the diagonal uh above and below the diagonal elements we are swapping here so we'll have to write one condition if it is a diagonal element will not do anything if i not equal to j then only we have to swap in temp equal to matrix in temp equal to matrix of next next matrix of i comma j equal to matrix of and and matrix of j i equal to 10 matrix of j i equal to 10 so here we are swapping those elements so let's take a let's do some dry run here we'll understand first row i equal to 0 and j equal to zero okay i less than matrix short length matrix dot length what is that in three okay and j less than matrix of zero dot line that is also three i equal to i not equal to j no this condition will fail again i will increment i equal to 1 sorry j will increment j equal to 1 i equal to 0 j equal to 1 now i not equal to j yes inside come inside temp matrix of i zero j is one zero comma one zero comma one is two temp will have two value next in place of two what will we will add in place of two will add matrix of one comma zero one comma zero is four so four will come here and matrix of one comma zero in place of that temp value will come some value what we had two so here two and four will get spam similarly j will increment j will be 2 down i equal to 0 j equal to 2 and it if this condition also will satisfy less than uh 3 so not equal to j satisfied temp matrix of 0 comma 2 0 comma 2 3 temp will have 3 now and in place of 3 what will add matrix of 2 comma 0 2 comma 0 is 7 so 7 will come here and in this place what will have matrix of two comma zero temp temp what we had three three will come here next if you take j increment three so condition fails it will go above i increment i equal to one no and j will be one now so both are equal so it it will come out of this if condition again increment j j is 2 now i equal to 1 j equal to 2 10 what will have matrix of 1 comma 2 1 comma 2 okay 6 6. so temp will have 6 in place of 6 what will have 2 comma 1 2 8 so 8 so 8 8 will be placed here and 8 8 will be placed here and in place of 8 what we'll have well we'll in place of 8 what we'll have well we'll add this 6 so here 6 and 8 will get swap add this 6 so here 6 and 8 will get swap similarly similarly if you go for other iterations if you go for other iterations uh uh you will see that this this value gets you will see that this this value gets transpose of a matrix transpose of a matrix now now we have got the transpose now we have to we have got the transpose now we have to reverse each row reverse each row if we have to reverse each row if we have to reverse each row uh let's write the code for that as well uh let's write the code for that as well what we'll do what we'll do for int i equal to 0 for int i equal to 0 same i less than i plus plus i plus plus next we'll iterate through the column for in j equal to 0 j less than matrix of 0 dot length now for reverse what we'll do same we'll now for reverse what we'll do same we'll do swapping and do swapping and let's take new variable let's take temp reverse equal to what we will do we will take the first element matrix of i and j will take in temp now matrix of i j with what will assign will assign with matrix of i and last column will need right so uh here we'll take one variable column length and call length equal to this value will so here will iterate through half of the columns because we are swapping so no need to wait till the end only half is enough so here call length minus j minus 1 okay next what what we'll do in this place we'll assign temp so what we'll do matrix of i and colon finish j minus 1 equal to okay okay i think i think we should be good we should be good let's let's we are not returning anything because we we are not returning anything because we have to do it in place have to do it in place so let's try to run here so let's try to run here and see the output and see the output it is accepted it is accepted let's try to submit yeah successfully we have uh solve this problem it takes 0 milliseconds and it's faster than 100 of solutions so this is the first medium level question we have solved and it sounds pretty good here so if if it is asked right to do it anti-clockwise direction and you can you can practice that as well let me see if i can do that in the next video that's it in this video from my side | 2024-03-20 09:45:42 | 48 | Coding Interview Questions | Medium | LeetCode 48 | Rotate Image |
|
ZI17bgz07EE | Hello hello guys welcome back to take devotion in this video you will see the question in this video you will see the question problem which is the way reaction of the problem which is the way reaction of the bond website problem and destroyed bond website problem and destroyed number-22 latest see the problem statement number-22 latest see the problem statement in this problem of different denominations in this problem of different denominations and total amount of money to and total amount of money to and total amount of money to of Units to Make Money Ca n't Make Any Information You Need to Know That You Have a Number Subscribe Nomination Form for the Number of Subscribe Nomination Form for the Number of the Time the Time That Nav in This Case Which Caused His Unlimited That Nav in This Case Which Caused His Unlimited Number of Sentences and Also Number of Sentences and Also Number of Sentences and Also select the same in and which bag to give for the giver 910 problems very similar to 1000 problems one instance of each item item in the city which you want to send me the number of Subscribe now to medium possibilities which Subscribe now to medium possibilities which they can they can they can Do For This Amount Like They Can Take Your Veins And Still Get This 11212 For This Amount Minimum Number Of The Number Three And Distribution Will Be Number One Number Nine Two The Number Of Units Veer Veer Veer Veer Veer The Sentence Of Number Two But Still Not Possible To Be And Will Return - One Who Can Never Give Information Center Problem And IF You Are Able To Understand That No Letter cnn-ibn Solve This Problem Will Need To Include Request Denomination The Mission Saw It Can The Mission Saw It Can The Mission Saw It Can Be Easy and Quick Reaction 151 Be Easy and Quick Reaction 151 Lips Were Taking Lessons From Left To Right Lips Were Taking Lessons From Left To Right 10000 You Can Tell All The Possible Numbers Of Which You Want To You 10000 You Can Tell All The Possible Numbers Of Which You Want To You To You Can Come To You Can Come Back To Give It's Not Possible 100 To 125 Left to Right in Adhishta Left to Right in Adhishta Left to Right in Adhishta Pro Pro Dushman Ban We can take this one in number of times but they should Dushman Ban We can take this one in number of times but they should not exceed this amount not exceed this amount so they can take 111 number of times and they can do so they can take 111 number of times and they can do that and they can improve 2050 that and they can improve 2050 number of times and still can make number of times and still can make number of times and still can make but in this case was possible to the number of which we can give very latest time number to two to two years were making of the possibility of which will improve 102 numbers subscribe problem will be moving from good night while making and decision Software at this point which can take any number of intensive viewers welcome back to solving all winners will be sent to avoid solving all winners will be sent to avoid a number of times when will the example withdraw share this post on reddit 9f of these posts 9f of these posts 9f of these posts include this one R Rahman two fonts include this one R Rahman two fonts for improved this 123 Life Again for improved this 123 Life Again Introduce 1.2342 Baitho Agni Friend Introduce 1.2342 Baitho Agni Friend Lotus 1.251 Again Follow Dushman Hamar 1200 Lotus 1.251 Again Follow Dushman Hamar 1200 Total Number of the Year Will Be Effective 1.251 Total Number of the Year Will Be Effective 1.251 Will Be The Mission 272 Will Not Be Possible For Will Be The Mission 272 Will Not Be Possible For You mid day meal doordesi to in order to get or required amount because someone to be formed into which included in the subscribe like it will pass through the subscribe like it will pass through the internet and the number of the nomination form. 151 subscribe this one Subscribe to this channel During the current item which is element is set I will be decreased in this value amount recognition relieving amount sincer including The relieving amount sincer including The Page if you liked Page if you liked The Video then subscribe to the Video The Video then subscribe to the Video then subscribe to the detention not then subscribe to the detention not Increase and will remain the same and will be the Increase and will remain the same and will be the next Navy Chief next Navy Chief plus one the designation This is Vivek plus one the designation This is Vivek Android Code IF YOU WANT TO KNOW THE CASES Android Code IF YOU WANT TO KNOW THE CASES IN THIS PROBLEM NO NOT POSSIBLE TO INFINITY OTHERWISE NO MATTER WHAT WILL ALWAYS In In In quantum number 90 dissolves possible to make sure quantum number 90 dissolves possible to make sure no problem no problem subscribe pimples ok so only very many friends pimples ok so only very many friends properties wikinews dynamic properties wikinews dynamic programming in this that is show latest see programming in this that is show latest see the population dp and status understand how to the population dp and status understand how to used in order to solve this problem used in order to solve this problem in wearing lips in wearing lips in wearing lips Wave 205 And 206 Taking The Volume To Table Number One Plus One Plus One Plus One Plus One Who Want To Consider Sharing It Will Not Be Possible For This Will Be Doing So Will Be Having No Comments Bones And Bones And Bones And Mod 108 Not Possible For The Amazing 10 12v Mod 108 Not Possible For The Amazing 10 12v Possible To Form 2018 Subscribe To Possible To Form 2018 Subscribe To 9V Feeling The Video then subscribe to set alarm up two and three What is the set alarm up two and three What is the Meaning of This Is Not Fair Have Meaning of This Is Not Fair Have Meaning of This Is Not Fair Have points 1243 minimum nine to three use one plus one will one plus one will form the total number of birth subscribe like this is form the total number of birth subscribe like this is the subscribe subscribe the subscribe subscribe akbar to formed a smartphone gas eighth Using one point not fearing Using one point not fearing Using one point not fearing amount to will be possible to from December amount to will be possible to from December 1872 this point and subscribe will basically 1872 this point and subscribe will basically Singh Divya nomination in tally solved they will be Singh Divya nomination in tally solved they will be the year - 1615 one number one instance of the year - 1615 one number one instance of nomination for the number one and all the value nomination for the number one and all the value of of printed will printed will printed will Amount To Be Formed Which To Will Know Now Be Discriminated Welcome To - The Missions Youth - 108 Persons 125 What Is The Meaning Of The Name Of The One Who Will B Coming B Coming B Coming Lord Of Improved Coma Explorer Source Pair Including This Dandruff Lord Of Improved Coma Explorer Source Pair Including This Dandruff Exactly 2051 Exactly 2051 Affair Acidity Minimum Way Latest From This Affair Acidity Minimum Way Latest From This Is The Worst Journalists - - - 151 Minimum Of This Is The Giver Subscribe 9 Latest Improve The First Denominations Of To both day what will be To both day what will be To both day what will be the number of birthday celebrate the current the number of birthday celebrate the current situation which is the current date and so will have to situation which is the current date and so will have to only if you liked The Video only if you liked The Video then subscribe to The Amazing Welcome to the to to to to then subscribe to The Amazing Welcome to the to to to to to - to - Who is the current wali special Who is the current wali special Who is the current wali special Roll Number of Mines 2051 Minimum of 12121 This is Not for This is the Invention Co 12321 Plus One Two Two Two Two Two Two Two Two Two 12321 Plus One Two Two Two Two Two Two Two Two Two Two The Number 90 Two The Number 90 Bittu Plus One No Fear Having All This Bittu Plus One No Fear Having All This Reading Subscribe Button 123 123 Four Will Not Be Subscribe Button 123 123 Four Will Not Be Doing So Will Just Shopping subscribe The Doing So Will Just Shopping subscribe The Video then subscribe to the Page if you Video then subscribe to the Page if you liked The Video then subscribe to the world will be Minimize Yourself Amnesty Exclude Country Global One two three will be One two three will be One two three will be equal to two one in the morning one not for this is equal to two one in the morning one not for this is a will be making a choice between 10 and a will be making a choice between 10 and improved the current coin the volume to the improved the current coin the volume to the karate kid from lbm1 total number of oneplus karate kid from lbm1 total number of oneplus one to know the total number of cases 310 one to know the total number of cases 310 one to know the total number of cases 310 to two to two the number of which we can do subscribe nothing but a 200 this is the answer this last sale will be actually given all examinations available and examination can have infinite number of points and the given two for this dynasty Give the meaning of this thank Give the meaning of this thank Give the meaning of this thank you are able to understand nothing which is the you are able to understand nothing which is the problem share the problem subscribe to the Page if you these directions 1200 number of but not improved in these directions 1200 number of but not improved in these works advice if these works advice if these works advice if Possible To Inform And They Will Be Writing In Adheen 9999 Coins Is The Present To You Will Not Be Able To Join And Subscribe Our Channel Otherwise Wise They Will Be The Meaning Of The Number One Vikas Bhi Vikas Bhi Vikas Bhi Arvind SIM number for once again but the amount which Arvind SIM number for once again but the amount which they want to know what is not they want to know what is not visible DJ - Festivals etc. Total amount visible DJ - Festivals etc. Total amount for which will be created nor will just for which will be created nor will just doing so will give the number of the center for doing so will give the number of the center for solving problems and finally subscribe subscribe the Not Possible for the Giver subscribe the Not Possible for the Giver subscribe the Not Possible for the Giver - 110 - 110 Jhaloo Stored in the Last Salute OK Suvidha Jhaloo Stored in the Last Salute OK Suvidha Center Solution Receiver C Plus Plus Center Solution Receiver C Plus Plus Code in Java Code Will Also Be Provided Code in Java Code Will Also Be Provided With At This Time You Are Able To Understand If You Have Any Problem And With At This Time You Are Able To Understand If You Have Any Problem And Comment Comment Subscribe Like Share | 2024-03-24 10:27:51 | 322 | Coin Change Problem | Dynamic Programming | Leetcode #322 | Unbounded Knapsack |
|
vJM-_NlaNBA | uh hey everybody this is larry this is day 26 of the august eco daily challenge day 26 of the august eco daily challenge uh hit the like button hit the subscribe uh hit the like button hit the subscribe button join me on discord and let me button join me on discord and let me know what you think about today's know what you think about today's problem fizzbuzz problem fizzbuzz uh given one two and three and five is uh given one two and three and five is frizz and buzz this is silly uh frizz and buzz this is silly uh okay um if you're watching this i don't okay um if you're watching this i don't know why you're watching this know why you're watching this uh but you know i don't know i don't uh but you know i don't know i don't even know how to go even know how to go into this really well i think the only into this really well i think the only weirdness is that um weirdness is that um you know uh usually you you you get to you know uh usually you you you get to print it print it so you can do some fancy trick you read so you can do some fancy trick you read there but there but uh but yeah this is just a little bit uh but yeah this is just a little bit silly so i'm gonna go right into the silly so i'm gonna go right into the code code um you could do it a number of ways it um you could do it a number of ways it doesn't really matter doesn't really matter maybe practice for comprehension in maybe practice for comprehension in python or whatever it is python or whatever it is but i'm just going to do it as silly as but i'm just going to do it as silly as possible because i don't know it's not really worth my time to think about optimizing it uh and also i did this wrong so so maybe i shouldn't uh but and i know that you could do some stuff so that you could uh it does both of them but i i don't know it's okay for me oh it's a string of x oops uh i mean it's just i don't know but yeah i hope you enjoyed this problem uh it's a little bit silly it seems like i'm just gonna test a big ish number should be okay either way uh is there a difference i wish they just told us oh i did have an off by one i knew that when i was typing it but i forgot so okay so i was a little bit too arrogant there but that's why you won tests um that's okay uh looks okay and then i just submit uh don't worry unless there's like some weird thing like negative numbers or something uh yeah uh how what is the complexity of this this is technically uh two to the n uh you want to call it that because um you take you know it's linear number there's o of n uh number of bits um there's o of n uh number of bits um and for each bit you have to go for and for each bit you have to go for every number so there's every number so there's two to the end possible numbers this is two to the end possible numbers this is a different end than the input n a different end than the input n uh it's so it's a little bit confusing uh it's so it's a little bit confusing uh but uh but if you say let's say the the input is uh if you say let's say the the input is uh just say just say k um and and as you go to the k um and and as you go to the number of bits uh then this is o of two number of bits uh then this is o of two to the n to the n uh though this is a convention that is uh though this is a convention that is usually talked about when you talk about usually talked about when you talk about complexity freely complexity freely uh but on interview people probably uh but on interview people probably usually know what you're talking about usually know what you're talking about so you so you just may have to talk about it a little just may have to talk about it a little bit but it's not a big deal right away bit but it's not a big deal right away uh and of course in terms of space you uh and of course in terms of space you can really do better than can really do better than um the output sensitive because you have um the output sensitive because you have to generate every number anyway to generate every number anyway um but yeah but for example if n is this um but yeah but for example if n is this n is or k as you go to 15 n is or k as you go to 15 uh requires like at least uh requires like at least uh where is it four bits five bits to uh where is it four bits five bits to represent sixteen represent sixteen on uh four bits five bits uh and on uh four bits five bits uh and that's two to the fourth uh complexity that's two to the fourth uh complexity right right but anyway it's not a big deal that's but anyway it's not a big deal that's all i have with this problem i'm at it all i have with this problem i'm at it maybe i'm a little lazy let me know if maybe i'm a little lazy let me know if you have any questions for this problem you have any questions for this problem because it just because it just seems very straightforward right and i seems very straightforward right and i yeah i don't know how to explain this yeah i don't know how to explain this one other than just one other than just writing if statements so yeah let me writing if statements so yeah let me know what you think hit the like button know what you think hit the like button to subscribe button and i'll see y'all to subscribe button and i'll see y'all tomorrow bye | 2024-03-22 10:50:42 | 412 | 412. Fizz Buzz - Day 26/31 Leetcode August Challenge |
|
d4D7LUuyTH0 | what's going on guys it's your boy Chuck here we have another leak code problem I here we have another leak code problem I actually solved it already actually solved it already and I got it right surprisingly on the and I got it right surprisingly on the first try first try I figured my solution was to some degree I figured my solution was to some degree unique unique so I wanted to go over it right now I'm so I wanted to go over it right now I'm very new to the leak code scene I've very new to the leak code scene I've solved 84 problems to date so I'm still solved 84 problems to date so I'm still getting a lot of practice getting a lot of practice but the fact that I was able to solve but the fact that I was able to solve this one problem made me feel really good I guess I guess I would say so uh because I at least for me it's not very often that I'm able to see a problem and solve it just right off the bat without looking up some sort of hints on Geeks for geeks or something of that nature right so that I mean that probably happens at this point at my skill level maybe 25 of the time where I'm able to just solve a medium or hard problem just off rip um now for easy problems a lot more successful but that's neither here nor there I came to talk about my solution so let's go ahead and go over this solution okay so I have my notes by my side just in case we're gonna have to or just in case I forget something in particular I don't want any bugs um but the essential idea that I had was I was going to iterate through every element that existed in this Matrix right The Matrix says given an M by n integer Matrix if an if an element is zero we want to set its entire row and column to zeros so I find a zero here I want to set these to zero in its row and in its column I want to set these to zero right but if we have a case like this I want to set this to zero I want to set this to zero all right and then I want to set these to zero these are already zero I don't have to set them to zero but these numbers I'm gonna have to set them to zero I'm gonna have to set these to zero and these to zero here's my Approach right knowing this I'm essentially iterating through every element in the Matrix and I use some sort of a a special placeholder right so in in the case of what I did before I used an asterisk because we know that in terms of what these values are actually going to be they're going to be integers right it says it right here these are the constraints are going to be integers so if I use an asterisk it can become easy to identify the asterisks later on and just change those those numbers that have been asterisks to zero if that's even a word so you can change those to zero right so the way that I did it is and the way that I do a lot of just standard Matrix problems is I go ahead and get my constraints my my role length right so we know that we can calculate the row length by essentially taking just the length of the Matrix you know that the Matrix has uh you know three rows inside of there so we know that is going to be our maximum length we can the central idea is that each row is the central idea is that each row is going to have the same number of columns going to have the same number of columns it's an M by n right so this is going to it's an M by n right so this is going to have three elements is three columns we have three elements is three columns we know this is also going to have three know this is also going to have three elements three columns and and the same elements three columns and and the same thing with the with the last one right thing with the with the last one right with the last row so we have that with the last row so we have that information right information right so what I like to do with these problems so what I like to do with these problems is the same thing I did with the spiral is the same thing I did with the spiral Matrix problem is I actually I have Matrix problem is I actually I have pointers that sort of go through and do pointers that sort of go through and do the dirty work for me this is why I say the dirty work for me this is why I say this is a mostly unique solution because this is a mostly unique solution because I don't see people doing this very often I don't see people doing this very often so I can identify what my top and bottom so I can identify what my top and bottom is what this is going to do for me is if is what this is going to do for me is if I find a zero I know that iterating from I find a zero I know that iterating from top to bottom I wanna if those are not top to bottom I wanna if those are not uh original zeros like like this this uh original zeros like like this this light purple one's an original zero if light purple one's an original zero if those are not original zeros you say we those are not original zeros you say we have one here we have one here from top have one here we have one here from top to bottom I want to set them all equal to bottom I want to set them all equal to my asterisks not to my zero to an to my asterisks not to my zero to an asterisk and at the end I'm going to asterisk and at the end I'm going to send it uh I'm going to change it to send it uh I'm going to change it to zero so you you'll see what I mean in a zero so you you'll see what I mean in a second here our bottom is going to be second here our bottom is going to be the row length same thing with the left to right we're going to look in this Matrix and see okay so we found this zero here we need to start from this side all the way to the end and set those all equals zero as long as they are not um the the original zero or an original zero and in this case there's two and the reason why I want to set it to an asterisk first is because if I set this to if I set maybe not this one if I set this to zero right you can imagine a scenario while I'm iterating through the Matrix okay I've seen this okay I set this to zero okay so now the next element that I see is this right here if this is a zero and my functionality is supposed to do some particular action on every zero that it's going to do and repeat that action on this zero as well so I'm going to actually have duplicate or I'm gonna have a incorrect solution because then I see this 0 here and then it's also going to set this this this entire column to zero that's not what we want remember we only want this to be a zero we don't want this entire column to be a zero this is why it's important to set it to an asterisk because if I set it to an ass Asterix then it's not going to run that particular functionality when it sees this again it's just going to ignore because it's not an original zero this is why I make a distinction between original zeros regular numbers and special characters this is these are the three things that we have to keep in mind okay so we have our left we know our right is going to be the column length okay so this is essentially I mean you can consider this o of one space right because this this uh variable right here these are these are constants and this is also a constant as well it's not like an array it's not going to grow with any particular inputs not a string it's not going to grow with any particular input it's not a hash set it's not a stack not a cue not a linked list nothing just a so I'm going to start so I'm going to start at zero so what we're doing here is at zero so what we're doing here is we're just going to iterate through we're just going to iterate through every single element that exists in The every single element that exists in The Matrix okay and now we gotta check if the particular Matrix if that element is equal to zero this is where we're gonna have the bulk of our functionality right here so it's important right it's particularly in this case if I see a zero right here again I don't want to override this zero I want to keep it so that any zero that you see is a is it is an original zero this is what I think of in my head I'm like okay these zeros are original zeros and these other zeros are formed from these zeros okay but we need to have these original zeros in order to be able to properly form every other zero correct so I'm going to say we want to skip a particular index now in JavaScript you can't really compare objects like you might be able to in in different languages so we know in JavaScript we have primitive types and we have uh essentially objects uh and these are passed by reference and primitive types like like uh booleans and and and numbers and things of that nature are passed by value so what I'm going to do here is I'm going to take this I'm going to join it because I want to be able to compare this with every other row column right if if I just had this right here say we say we had 0 0 and I tried to see okay well is are we currently at zero zero I wouldn't be able to do this because what what's actually being compared is is is the memory location I want to compare the actual Index right or or the the pair of indexes right or indices so I'm going to set top equal to zero I'm going to set bottom equal to row length this is to just reset after everything I can actually have this at the bottom it doesn't really matter is less than bottom so this is the case is less than bottom so this is the case when we find a zero while top is less when we find a zero while top is less than bottom we're going to than bottom we're going to change all these to zeros so we know we have our top this is zero and our column is at one so we're gonna do zero one one two one right for the row right now the only thing is we have to make sure and we have to make sure and we have to make sure that this is not an original zero then what we can do with this we can top top and column as our index or indices so we can manipulate each of these so so we're manipulating this right here set it equal to an asterisk this we're going to skip it it's an original zero we're going to set this equal to an asterisk this is the same sort of functionality we're going to have from left to right okay all we have to do here is increment top then in this case we're going to do the foreign you can sort of see what's going on we start from left if it's not an original zero only in this case we're moving within the constraints of a particular row so we're in row one okay at this point we should have a matrix if as a particular set of characteristics and hopefully I did not make a mistake what happens if we return Matrix I just want to see what it looks like I guess we're supposed to do this in I guess we're supposed to do this in place that's correct place that's correct so nothing really is going to happen oh I forgot to change this we are that particular value that we're at okay every time we see not a number we know every time we see not a number we know that's our asterisks that's our asterisks and all we have to do at the end and and all we have to do at the end and let's make sure this works with let's make sure this works with every test case all we have to do at the every test case all we have to do at the end is loop again see it works right here these are original zeros works right here looks right here all we and if we see the asterisks just set it and if we see the asterisks just set it equal to zero and there's our solution and there's our solution it says eight percent here it says eight percent here I promise it was a lot better than that I promise it was a lot better than that before before okay 35 it was just that what was this okay 35 it was just that what was this at maybe it was 60 something 68 I mean I I'm not claiming it's the most efficient solution but it definitely should be a lot better than eight percent but uh you can't tell from from that eight percent but I think it's a decent solution now there's probably better ways to do it actually I know I can guarantee there are better ways to do it but this was my first idea and it worked out on the first try so I just wanted to show you guys my thought process and that was | 2024-03-20 11:35:17 | 73 | LeetCode #73 | Set Matrix Zeroes. JavaScript Solution! |
|
ySrinuKlHP4 | hey guys how's everything going this is Jay sir who is not good at algorithms in Jay sir who is not good at algorithms in this video I'm going to take a look at 3 this video I'm going to take a look at 3 9 8 a random picking next we're given an 9 8 a random picking next we're given an array of integers with possible array of integers with possible duplicates mm-hmm it is not sorted duplicates mm-hmm it is not sorted random leap up with the index of a given random leap up with the index of a given target number we can assume that the target number we can assume that the given target number must be exist okay given target number must be exist okay the array size can be very large the array size can be very large solution that uses too much extra space solution that uses too much extra space will not pass the chart like this uh-huh will not pass the chart like this uh-huh we need for every cup pick 3 we need to we need for every cup pick 3 we need to return either 2 3 or 4 randomly well return either 2 3 or 4 randomly well because the integers are not sorted and because the integers are not sorted and they may be disjoint right like 3 there they may be disjoint right like 3 there might be 3 3 4 and then 3 while the the might be 3 3 4 and then 3 while the the the naive solution would be naive the naive solution would be naive solution would be keep index map right solution would be keep index map right so cast index map map we look through so cast index map map we look through the nouns and if index map has I if it's not there we set it to empty array right yeah and then we we push the index in to the map so the map actually will become map of index index 1 thanks to something like this so we're a pick first we get in the indices Nexus this is equals this okay add this index map and get target and then being the cost random index you should be something like this right and then we just return this is Brendan I it I'm so sorry that's right cool I submit we are accepted but very slow very very slow it's maybe because we're using too much using too much space mm-hmm so the risk is not that bad let's try to analyze our solution with the first this is actually uh this is just a constant here so the problem is becomes here recent map actually for the word we actually will keep the index for all right keep number and yes actually we cost a linear here for space and here we traversed we yeah the time actually for this solution constructor it's a linear time Oh and and a big boat for pick it's constant so is there any better solution I'm not sure let's try to look at the discussed yep a bright future yachts shuffle what is this reserve Bois sampling what javascript constant space and single want linear time solution Wow thumbs then huh pic if this length say the counts 0 and then we pick say the counts 0 and then we pick something we will look through it says when we are looking through the it says when we are looking through the numbers and we actually max random I'm numbers and we actually max random I'm getting the account get the previous one getting the account get the previous one I can it and while we're looking into it I can it and while we're looking into it and we get a random index if it's zero and we get a random index if it's zero we return the root we set the result to we return the root we set the result to 2 to the I I see so actually this is an idea that says suppose there are three suppose there are three indexes looping looping through the first one and the second one and the third one so for each then like for the index of a for the length of one if you pick one or there are two or pick one or three we pick one it should be it should be actually ah yeah yeah yes wow this is clever so I come in here it says for if we're the three index the first one is i1 i2 and i3 right when we meet that I 1 we run this method random if it equals to 1 0 it means if it falls into i1 why right of course it's because it's only 1 so it must be returned one possibility but for I 2 if we're running two we into because now we get two numbers right so now the possibility the there is the possibility was 1 and the there is the possibility was 1 and the possibility here for each was a 0.5 0.5 possibility here for each was a 0.5 0.5 now I've 1 2 3 now I've 1 2 3 we run it mmm-hmm why we why we will set the mmm-hmm why we why we will set the result in every time we check because we result in every time we check because we don't know how many numbers are there don't know how many numbers are there right so we check every time if we know right so we check every time if we know the length before and we could just run the length before and we could just run the last time for the last time but we the last time for the last time but we don't know how many a time I saw it don't know how many a time I saw it there this is the problem so we will there this is the problem so we will just see we were just to run it and we just see we were just to run it and we don't know even though the previous one don't know even though the previous one right we don't know the previous number right we don't know the previous number or the last time previous index or the or the last time previous index or the the rest second index or the third index the rest second index or the third index so we just run it again and over over so we just run it again and over over and again every time we get the target so how would the possibilities the possibility be distributed here for you see because for the first index it's you see because for the first index it's actually out of three rounds right the actually out of three rounds right the first index we're out first index we're out so suppose there are n index and I 1 is so suppose there are n index and I 1 is 1 so actually it 1 times 1 out of 10 and 1 so actually it 1 times 1 out of 10 and round right and if you are 2 so it's 2 round right and if you are 2 so it's 2 [Music] [Music] the 0.2 out of 1 out of 2 times how many the 0.2 out of 1 out of 2 times how many this is another how many how many this this is another how many how many this one so gives B and index yeah this would one so gives B and index yeah this would be 2 what's the possibility I'm making what's the possibility I'm making enemies right so for three index we will enemies right so for three index we will pick three times for the first time must be itself okay we set it to 1 and the second time it is no possibility of half of the half of the chance right and this must be must use be used to we to to remove the result here so that the check here is if the math.random is the previous one if it is by one we said it I to but this actually means if it is one of one of the chance of this is the this means and minus 1 right okay so oh yeah oh yeah so this actually is a n minus a 1 out of n so for I 1 it will be I find out of 1 1 yeah so it's 1 and for two for two okay so there will be for two for two okay so there will be one on up to the chance we said it on I one on up to the chance we said it on I - right - right you see so that's what I want is of you see so that's what I want is of course - so so I won course - so so I won it's also one out of two when they are it's also one out of two when they are three you see it was a one of three we three you see it was a one of three we set into our three right right for the set into our three right right for the rest for the three for the for the but a rest for the three for the for the but a two out of three chance that we don't two out of three chance that we don't touch it will fall on to the previous touch it will fall on to the previous one which means it's half of a chance one which means it's half of a chance all right so it's one eye one eye - wow all right so it's one eye one eye - wow this is clever so so I got this idea this is clever so so I got this idea it's at 4 i1 i2 i3 until I end to random it's at 4 i1 i2 i3 until I end to random pick one one number we could actually pick one one number we could actually [Music] [Music] pick I won for the chance chance of one pick I won for the chance chance of one out of one pick i to fortunes of one up out of one pick i to fortunes of one up to pick by three or chance out of one up to pick by three or chance out of one up three pick by n for a chance of one these channels for a nice right so that previous one is the we will have the chance of an N minus one out of n as we yeah yeah yeah wow this is clever yeah yeah yeah wow this is clever learning something cool this is very learning something cool this is very cool I'd like to clip up upload is there cool I'd like to clip up upload is there any theory for this one so if we think another way is that suppose there is n minus 1 I will already pick the number we already set 1 now we have an N minus a new number so what we care is that - is that when we only care is that if I n is not in a final result it's already picked randomly right if you want to add int n it must be in my 1 out of n chance so we only care for that chance to update the result i n for the other ones it will be already done in a previous loops Wow collabora and is yes of course the time and space complicit I'm would be the construction will be very nothing but the pic will actually for worst case will be in linear time for time right or for space its cost constant I think wow this is very cool for our solution actually we're using both linear time and space yeah ok so that's all for these problem see | 2024-03-24 12:17:11 | 398 | LeetCode 398.Random Pick Index | JSer - JavaScript & Algorithm |
|
vZkutwUrPgE | all right let's talk about today's laconian challenge question so it's a it laconian challenge question so it's a it was end of number range or bitwise end was end of number range or bitwise end of range of numbers we have a wrench end of range of numbers we have a wrench end to end it's positive and so it's a bit to end it's positive and so it's a bit large we've got the end that's a large we've got the end that's a slightly larger larger than and and we slightly larger larger than and and we need to return the bitwise and of all need to return the bitwise and of all the numbers in this range inclusive so the numbers in this range inclusive so just pretty much it would just be so if just pretty much it would just be so if we if we just translate what the we if we just translate what the question is asking into code it will be question is asking into code it will be something like this but I guess it will something like this but I guess it will be you will be the correct all set but be you will be the correct all set but it will be slow because we doing an it will be slow because we doing an operation a mom how many numbers we have operation a mom how many numbers we have in this range so I think it will be you in this range so I think it will be you will probably exceed the run time limit will probably exceed the run time limit we are looking at something that's a we are looking at something that's a smarter that probably only looking at smarter that probably only looking at the two boundaries to figure out things the two boundaries to figure out things so let's take a look at that so M is so let's take a look at that so M is equal to 5 which will be a 4 and a 1 so equal to 5 which will be a 4 and a 1 so it's 1 1 and a 7 so it's a it's a 2 a 4 it's 1 1 and a 7 so it's a it's a 2 a 4 and one add together this one we have a and one add together this one we have a sandwich the number in between which is sandwich the number in between which is 6 is 1 1 0 and if we do bitwise and for 6 is 1 1 0 and if we do bitwise and for all the numbers it's basically checking all the numbers it's basically checking for the bit that every number has a 1 in for the bit that every number has a 1 in there so it's at this bit here we return there so it's at this bit here we return 1 0 0 which is 4 so it appears that we 1 0 0 which is 4 so it appears that we can basically just shifting these two can basically just shifting these two numbers towards right for for for the numbers towards right for for for the same amount until the two numbers become same amount until the two numbers become equal that that bit should be the bit to equal that that bit should be the bit to that we have all those numbers in the that we have all those numbers in the meeting meeting all those numbers or or should have that all those numbers or or should have that bit to be one so if we ship the fight bit to be one so if we ship the fight was right by two positions shipped was right by two positions shipped everything here what's right we get out everything here what's right we get out one that's the one and that's a one if one that's the one and that's a one if we just shifted by one we just shifted by one it's not equal let me actually do this it's not equal let me actually do this in stay stay just look at a one zero in stay stay just look at a one zero [Music] [Music] this is a one line and this is one yes this is a one line and this is one yes yes so this is what I'm talking about if yes so this is what I'm talking about if I shifted the numbers towards right by I shifted the numbers towards right by by the same amount and what we carry is by the same amount and what we carry is actually the M and hang whether they are actually the M and hang whether they are the same or not when they are the same the same or not when they are the same it's pretty much we we can guarantee it's pretty much we we can guarantee that everything in between should have that everything in between should have that bit at least that bit to be the that bit at least that bit to be the same so we need to show something else same so we need to show something else before we can actually perceive as this before we can actually perceive as this this this this procedure in the code is this this this procedure in the code is that would there be case that when the N that would there be case that when the N has one extra at least one extra one has one extra at least one extra one towards the left and there could that be towards the left and there could that be some kind of violation there let's say some kind of violation there let's say that M is 0 1 0 and n is 1 1 1 0 that M is 0 1 0 and n is 1 1 1 0 something like that so if we shifted to something like that so if we shifted to semi bond and just only checking for semi bond and just only checking for that particular bit the first a bit that that particular bit the first a bit that this to become the same what this cost this to become the same what this cost problems what we have in between this is problems what we have in between this is 2 2 this is six so we have a couple of this is six so we have a couple of number in between three four five so for number in between three four five so for three it should be 0 1 4 is 1 0 0 5 is 1 three it should be 0 1 4 is 1 0 0 5 is 1 0 1 okay so we don't need to worry about 0 1 okay so we don't need to worry about I think that the approaches should work I think that the approaches should work once we moved we shifted the to number once we moved we shifted the to number the two boundaries towards the right for the two boundaries towards the right for the same amount and we see that the the same amount and we see that the other cell should guarantee I was other cell should guarantee I was previously worried about if we have this previously worried about if we have this this one location and this one location this one location and this one location here yeah so we should check for we here yeah so we should check for we should check for the whole number after should check for the whole number after shifting it's it's not the only that shifting it's it's not the only that digit if we check for the whole number digit if we check for the whole number you should work in this case by one it's you should work in this case by one it's 0 1 and this is 1 so they're not the 0 1 and this is 1 so they're not the same they are not the same meaning that same they are not the same meaning that it's it's guaranteed that they are in it's it's guaranteed that they are in order for this to become 1 1 it has to order for this to become 1 1 it has to be 1 0 first so even so even though that be 1 0 first so even so even though that after the same amount of shifted they after the same amount of shifted they the first the rightmost appeared to the first the rightmost appeared to become the same for this two boundaries become the same for this two boundaries as long as these two numbers are not as long as these two numbers are not equal there has to be some numbers in equal there has to be some numbers in between however 0 in that column in that between however 0 in that column in that in that bit so we need a shift of the in that bit so we need a shift of the two numbers for the same amount until two numbers for the same amount until they eventually become equal either it's they eventually become equal either it's all one or or zero and if it's all one all one or or zero and if it's all one we just shift it back by two by the by we just shift it back by two by the by the amount to get the amount to get the limo we wanted for this case two and the limo we wanted for this case two and six the we need to shift for this one six the we need to shift for this one more time two more time actually more more time two more time actually more time together them to be equal and when time together them to be equal and when they are equal they are all 0 so it's 3 they are equal they are all 0 so it's 3 times shifted to cause them to become times shifted to cause them to become equal and we shifted the 0 back by 3 equal and we shifted the 0 back by 3 times we get the 0 and it's indeed that times we get the 0 and it's indeed that there is no column among this range 2 & there is no column among this range 2 & 6 so that's a 1 across the board so 6 so that's a 1 across the board so there's 0 make sense alright so yeah so there's 0 make sense alright so yeah so this will be just a shifting bit this will be just a shifting bit shifting question and the Cystic that we shifting question and the Cystic that we are working with silly two bit integers are working with silly two bit integers the running time is order of silly - so the running time is order of silly - so it's a it's very much constant so we're it's a it's very much constant so we're going to keep track of how many times we going to keep track of how many times we do the shift while just two numbers are do the shift while just two numbers are not equal we need to shift it imposed to not equal we need to shift it imposed to us right in the end we just require the us right in the end we just require the the M the lower number the ship shifted the M the lower number the ship shifted back by the same amount so this should back by the same amount so this should work let's see okay so that's that's a work let's see okay so that's that's a quick question today | 2024-03-22 09:39:07 | 201 | Leetcode 201 Bitwise AND of Numbers Range |
|
_NSc3b5BIXc | hey what's up guys Nick white here I detect encoding stuff on twitch and detect encoding stuff on twitch and YouTube check the description for all my YouTube check the description for all my information just explaining the code information just explaining the code that goes into these algorithms data that goes into these algorithms data structures problem for people that don't structures problem for people that don't understand them or just explaining the understand them or just explaining the problems in general please like and problems in general please like and subscribe to the channel gross thank you subscribe to the channel gross thank you very much very much this is 12 22 newer problem on lis code this is 12 22 newer problem on lis code Queens that can attack the King like in Queens that can attack the King like in chess hopefully you guys have played chess hopefully you guys have played chess before this is a medium problem on chess before this is a medium problem on an 8x8 chess board there can be multiple an 8x8 chess board there can be multiple black queens and one white King so black queens and one white King so multiple Queens that can attack a king multiple Queens that can attack a king right the the one board has a bunch of right the the one board has a bunch of Queens and the one just as a king left Queens and the one just as a king left is what we're dealing with here giving is what we're dealing with here giving it given an array of integer coordinates it given an array of integer coordinates for the Queens so we're giving the for the Queens so we're giving the coordinates of every Queen that is left coordinates of every Queen that is left on the board that represent the on the board that represent the positions of black Queens and then we positions of black Queens and then we have also the coordinates of the King so have also the coordinates of the King so this is the coordinates of all the this is the coordinates of all the Queens so it's gonna be like a giant Queens so it's gonna be like a giant array a 2d array where each sub array is array a 2d array where each sub array is a pair of coordinates for one particular a pair of coordinates for one particular Queen right so this is a queen this is a Queen right so this is a queen this is a queen this is a queen we get the queen this is a queen we get the coordinates for every Queen right so coordinates for every Queen right so zero one would look like this one zero zero one would look like this one zero would look like this and then the rest would look like this and then the rest of the Queens right and then we also the of the Queens right and then we also the King is just a one-one array and just King is just a one-one array and just you know x and y values for where the you know x and y values for where the king is right so we know where the king king is right so we know where the king is and we know where all the queens are is and we know where all the queens are on the chessboard so what we're trying on the chessboard so what we're trying to figure out is we want to return a to figure out is we want to return a list of the list of integer we just want list of the list of integer we just want to return a list of the coordinates of to return a list of the coordinates of the Queens that can attack the King the Queens that can attack the King right so these three can attack the King right so these three can attack the King if you know anything about chess the if you know anything about chess the Queen can attack in any direction and it Queen can attack in any direction and it can go as far as it can on the can go as far as it can on the chessboard right so this Queen can go chessboard right so this Queen can go diagonally this one can go up this one diagonally this one can go up this one can go left the only thing is the Queen can go left the only thing is the Queen can just go through another Queen to can just go through another Queen to attack the King right this can't and attack the King right this can't and this isn't a perfect die like this can't this isn't a perfect die like this can't just go you can't just do that it has to just go you can't just do that it has to either be diagonal up right left down either be diagonal up right left down any of any of eight directions you can go in I can go eight directions you can go in I can go one of those directions to you know one of those directions to you know stretch as far as the board to attack stretch as far as the board to attack the king okay so how do we do this the king okay so how do we do this my intuition for this problem was some my intuition for this problem was some kind of like DFS thing the seams number kind of like DFS thing the seams number of islands like where you start at this of islands like where you start at this certain point where the king is and you certain point where the king is and you expand in all possible directions right expand in all possible directions right so you start here and then you start so you start here and then you start expanding in those directions that the expanding in those directions that the Queen can attack from and look for the Queen can attack from and look for the Queen's coordinates and then put those Queen's coordinates and then put those onto the list and that's similar to what onto the list and that's similar to what we're gonna do here but the the thing we're gonna do here but the the thing here is we have to handle this case the here is we have to handle this case the only special case where the Queen can't only special case where the Queen can't attack through other Queens right so how attack through other Queens right so how are we gonna do that we have to break are we gonna do that we have to break basically while we're looking for the basically while we're looking for the Queen's we basically have to break once Queen's we basically have to break once we find a queen when we're expanding in we find a queen when we're expanding in these directions right so to do that these directions right so to do that we're actually gonna see we're gonna we're actually gonna see we're gonna make a scene or ret we're gonna make a make a scene or ret we're gonna make a scene or a basically a clone of the scene or a basically a clone of the board and we're just gonna loop through board and we're just gonna loop through all the Queen's coordinates and put in all the Queen's coordinates and put in the scene array where we've seen a queen the scene array where we've seen a queen right so let's just do that really quick right so let's just do that really quick first thing we could actually do is just first thing we could actually do is just initialize our output that's always what initialize our output that's always what you should do in a question if you have you should do in a question if you have an output type just set it up right just an output type just set it up right just get it done that's an easy move forward get it done that's an easy move forward and a problem so just make it I always and a problem so just make it I always call it result pretty much it's an call it result pretty much it's an ArrayList there we go boom we got our ArrayList there we go boom we got our result set up so at the end you know result set up so at the end you know return results right of course now first return results right of course now first thing we're gonna do is like I said make thing we're gonna do is like I said make this scene arise so the scene array is this scene arise so the scene array is going to be a boolean array and it's going to be a boolean array and it's going to be of size eight by eight going to be of size eight by eight because that's the size of the chess because that's the size of the chess board and this is gonna be all the board and this is gonna be all the coordinates of the scenes of the Queen's coordinates of the scenes of the Queen's not the scenes that you know are on the not the scenes that you know are on the board so there we go it's an eight by board so there we go it's an eight by eight array same size of the chess board eight array same size of the chess board you can just loop through the Queens you can just loop through the Queens using this shorthand int array or using this shorthand int array or interact queen in Queens interact queen in Queens so Queen and Queens bad time typing so Queen and Queens bad time typing right now then you can just do scene of right now then you can just do scene of queen of zero this is the x coordinates queen of zero this is the x coordinates of the Queen the Queen current Queen of the Queen the Queen current Queen that we're looping through sort of that we're looping through sort of living there each Queens coordinates living there each Queens coordinates right so I've seen this Queen and then right so I've seen this Queen and then we put the x coordinate and then the y we put the x coordinate and then the y coordinate this is basically the board coordinate this is basically the board this is the 8x8 board and then we're this is the 8x8 board and then we're just using boolean to say which position just using boolean to say which position which index indices were are gonna which index indices were are gonna they're gonna be true if we see a queen they're gonna be true if we see a queen there right okay and this gonna come in there right okay and this gonna come in handy later so there we go we get the x handy later so there we go we get the x and y values of the queen so we set it and y values of the queen so we set it to true okay great so what do we do now to true okay great so what do we do now basically we're gonna have a directions basically we're gonna have a directions array so we're gonna just say okay array so we're gonna just say okay directions is equal to negative 1 0 & 1 directions is equal to negative 1 0 & 1 and this is because in any certain and this is because in any certain direction if you're going forward if direction if you're going forward if you're going diagonal you can either go you're going diagonal you can either go forward or backwards if you're gonna forward or backwards if you're gonna up-down left-right diagonal you know up-down left-right diagonal you know whatever you can only go forward or whatever you can only go forward or backwards so one is going you know backwards so one is going you know forward in the direction what negative forward in the direction what negative ones go backwards zero is just going you ones go backwards zero is just going you know you're not moving anywhere right so know you're not moving anywhere right so we can loop through all we can increment we can loop through all we can increment basically our x and y's you know if basically our x and y's you know if you're if your king is here right you're you're if your king is here right you're gonna want to increment your x and y's gonna want to increment your x and y's in all directions right so we're gonna in all directions right so we're gonna do all possible directions so we just do all possible directions so we just loop through you know into DX in loop through you know into DX in directions four-inch dy in directions directions four-inch dy in directions then what this is do is doing is its then what this is do is doing is its looping through um you know negative 1 0 looping through um you know negative 1 0 1 for all the X values so it's could 1 for all the X values so it's could either stay in the same X position you either stay in the same X position you can go negative 1 or it can go it can go can go negative 1 or it can go it can go negative 1 or could go positive 1 but negative 1 or could go positive 1 but it's also moving through all the it's also moving through all the positive the y direction so you go you positive the y direction so you go you know negative negative 1 and Y it could know negative negative 1 and Y it could get a positive 1 or it can just stay in get a positive 1 or it can just stay in the same spot and then we'll also do the same spot and then we'll also do them them simultaneously so it covers the simultaneously so it covers the diagonals right it can go you know diagonals right it can go you know negative 1x and negative negative 1y or negative 1x and negative negative 1y or if you go negative 1 x + 1 Y so go up if you go negative 1 x + 1 Y so go up and to the left or you go 1 X and you and to the left or you go 1 X and you know this this double for loop will know this this double for loop will cover all possible directions diagonal cover all possible directions diagonal diagonal diagonal diagonal left-right diagonal diagonal diagonal left-right up-down and that's what we're gonna do up-down and that's what we're gonna do and basically within here we're gonna and basically within here we're gonna get the dimension the well first of all get the dimension the well first of all if it's if they're both equal to 0 we're if it's if they're both equal to 0 we're not going to do anything so we'll just not going to do anything so we'll just continue through the loop so if GX is continue through the loop so if GX is equal to 0 and D Y is equal to 0 then we equal to 0 and D Y is equal to 0 then we will just continue otherwise we'll get will just continue otherwise we'll get the position of the king so we'll say the position of the king so we'll say king is x value is equal to king of 0 king is x value is equal to king of 0 and then king of Y value is equal that and then king of Y value is equal that with the Y value of the King is equal to with the Y value of the King is equal to king of 1 right so that's just how it is king of 1 right so that's just how it is we have the x and y the king right we have the x and y the king right that's what we get is the input so 3 3 that's what we get is the input so 3 3 it's gonna be a 3 3 so we just give it's gonna be a 3 3 so we just give those x and y values right and now we those x and y values right and now we want to take those x and y values that's want to take those x and y values that's where we start our expansion from and where we start our expansion from and start going in all of these Direction start going in all of these Direction combinations we were just talking about combinations we were just talking about looking for the Queen and to do that looking for the Queen and to do that we're just gonna have a while loop where we're just gonna have a while loop where we expand our boundaries based on so we expand our boundaries based on so it's doing all these possible it's doing all these possible combinations like I said in those four combinations like I said in those four loops so now we're gonna do okay if x + loops so now we're gonna do okay if x + DX is less than or greater than or equal DX is less than or greater than or equal to 0 because that's the boundary of the to 0 because that's the boundary of the indices right the first index you can go indices right the first index you can go on is 0 and X plus DX is less than 8 on is 0 and X plus DX is less than 8 because 7 is the farthest you can go so because 7 is the farthest you can go so these are this boundary checks and y these are this boundary checks and y plus dy it is greater than or equals 0 plus dy it is greater than or equals 0 and y plus dy is less than 8 then in and y plus dy is less than 8 then in this case we cheese do is y plus dy is this case we cheese do is y plus dy is less than 8 in this case we can start less than 8 in this case we can start expanding in that in those directions expanding in that in those directions because we're not going to go out of because we're not going to go out of bounds so boundary checks so you just do bounds so boundary checks so you just do expo expo you know this is what we check 4x plus you know this is what we check 4x plus equals DX y plus equals dy and then down equals DX y plus equals dy and then down here we'll check the seen array for here we'll check the seen array for these coordinates because you're these coordinates because you're expanding you're changing the X and Y's expanding you're changing the X and Y's to find those you're you're looking in to find those you're you're looking in every direction to find if there's a every direction to find if there's a queen around and if we do find the Queen queen around and if we do find the Queen in those coordinates because we know in those coordinates because we know where the Queen's are in our seen array where the Queen's are in our seen array that's why we filled it up so if seen X that's why we filled it up so if seen X of Y is true then down here what we'll of Y is true then down here what we'll do is we will do results dot add a do is we will do results dot add a raised dot as list of X&Y basically what raised dot as list of X&Y basically what this does is it adds the coordinates of this does is it adds the coordinates of the queen that we found to our result the queen that we found to our result because that's what we're looking for because that's what we're looking for because it can attack right because it's because it can attack right because it's in one of those directions one of those in one of those directions one of those eight valid directions that we're eight valid directions that we're expanding to we found a queen and now so expanding to we found a queen and now so that we don't find these extra Queens in that we don't find these extra Queens in the same direction we will now break out the same direction we will now break out of this loop and it will stop continuing of this loop and it will stop continuing in the same direction so this is only in the same direction so this is only going in one certain direction once we going in one certain direction once we break it'll not it won't go in that break it'll not it won't go in that direction anymore so we will not direction anymore so we will not continue searching in that direction so continue searching in that direction so we add the first queen we find in the we add the first queen we find in the direction and then we break so that we direction and then we break so that we don't keep going in that it handles that don't keep going in that it handles that one weird case where there's already one weird case where there's already Queens in the way so that's pretty much Queens in the way so that's pretty much it and then you can just return your it and then you can just return your result that's pretty much it for this result that's pretty much it for this problem it's a pretty elegant solution problem it's a pretty elegant solution hopefully I explained it well my main hopefully I explained it well my main problem with these solutions right now problem with these solutions right now is my typing speed this keyboard I need is my typing speed this keyboard I need to get a new keyboard but yeah that's to get a new keyboard but yeah that's that's basically it I mean what do you that's basically it I mean what do you put it's just expanding a direction put it's just expanding a direction you're looking for the Queen's we're you're looking for the Queen's we're putting the coordinates in this scene putting the coordinates in this scene array tells us where they are so it's array tells us where they are so it's just useful to clone it so we know the just useful to clone it so we know the array coordinates of the Queen's so that array coordinates of the Queen's so that this is like a nice little elegant loop this is like a nice little elegant loop through all directions like I said you through all directions like I said you know negative 1 negative 1 it goes know negative 1 negative 1 it goes through this twice you know it does all through this twice you know it does all the combinations of these three things the combinations of these three things and yeah I mean that's pretty much it I and yeah I mean that's pretty much it I mean I don't know what else to say you mean I don't know what else to say you know hopefully understand let me know if know hopefully understand let me know if you guys have any questions you guys have any questions it's pretty straightforward let me know it's pretty straightforward let me know if you have any other solutions down if you have any other solutions down here but I really like the solution I here but I really like the solution I tried to do it in a little bit different tried to do it in a little bit different way than looping through these way than looping through these directions like this but I think this is directions like this but I think this is the best way and I like this little the best way and I like this little scenery so thank you guys for watching scenery so thank you guys for watching let me know if you have any questions let me know if you have any questions please like and subscribe alright I'll please like and subscribe alright I'll see you in the next video alright peace | 2024-03-18 12:33:02 | 1,222 | LeetCode 1222. Queens That Can Attack the King (Algorithm Explained) |
|
W3OSNlSIJJM | Hey everyone Spencer, I hope people are well, today I will solve the problem Partition Equals today I will solve the problem Partition Equals Upset, everything is fine, this question must be Upset, everything is fine, this question must be scary to see, on top of that you are thinking, scary to see, on top of that you are thinking, DP question is, I don't know how it will happen, I will DP question is, I don't know how it will happen, I will please tell you very lovingly that you please tell you very lovingly that you Till now, whenever you watch my videos, Till now, whenever you watch my videos, I always tell you, please watch this playlist from the beginning. If I am telling you the truth, you will be asking this question watch this playlist from the beginning. If I am telling you the truth, you will be asking this question yourself, it may not be so, if yourself, it may not be so, if I tell you now, then it will help. I tell you now, then it will help. I tell you now, then it will help. see, most of the concepts were from Zero One Up, which we have solved. It is most important to ask this question that I did not see its pistol in the lecture and if you have directly come to the question, then please do not come to this stage You will not be able to solve You will not be able to solve You will not be able to solve such questions and start reading directly such questions and start reading directly or start solving them. or start solving them. If you do not know the concept of DP If you do not know the concept of DP then I am telling you the truth, you will not be able to solve it then I am telling you the truth, you will not be able to solve it and will become frustrated and separated and by doing and will become frustrated and separated and by doing all this we made you fear DP. all this we made you fear DP. I go after that, that's why my playlist I go after that, that's why my playlist is relief, it always has all the relief in it, is relief, it always has all the relief in it, how to burn your confidence from the beginning how to burn your confidence from the beginning so that you start asking questions, okay and I am so that you start asking questions, okay and I am telling the truth, this question is like this, telling the truth, this question is like this, before that I would recommend that before that I would recommend that given in the description box. Please given in the description box. Please open it and attempt it once. open it and attempt it once. What is the input given in it and what is the output What is the input given in it and what is the output given in it? Brother has also impressed us as much as given in it? Brother has also impressed us as much as we can by rating it. we can by rating it. Can you find a solution sir, this thing Can you find a solution sir, this thing will help you a lot, I am telling you the truth, it will will help you a lot, I am telling you the truth, it will help you a lot in enhancing the concept of DP, help you a lot in enhancing the concept of DP, now I will talk about this now I will talk about this lecture, the lecture is going to be very short lecture, the lecture is going to be very short because I read its basic thing sir. because I read its basic thing sir. Now I have to show you the game of Now I have to show you the game of how people play in DP, how people play in DP, how each question which is a template, which is how each question which is a template, which is zero, which has become a template on its own, zero, which has become a template on its own, how many how many questions can be solved on the continuation of the question, okay. questions can be solved on the continuation of the question, okay. questions can be solved on the continuation of the question, okay. you must have seen the last lecture. I hope you have been in the playlist since the beginning. You will get a lot of friends in the trust. Now those who were there since the beginning felt like recension. In this way, those who are They will be made of DC, they will get DC They will be made of DC, they will get DC They will be made of DC, they will get DC online. Do you understand carefully what is the partition problem? online. Do you understand carefully what is the partition problem? I will tell you this 01, its proposal is just like the problem. you this 01, its proposal is just like the problem. Partition Equals. What does the problem Partition Equals. What does the problem say that you have a set of integers. say that you have a set of integers. say that you have a set of integers. tell you that basically you have to divide this set of India into two partitions p1 and p2 and divide it in such a way that what is in both the partitions is equal, it is okay like if I If there is 11 in this then If there is 11 in this then If there is 11 in this then how much is the sum of 11 and how much is the sum of this how much is the sum of 11 and how much is the sum of this 11 then was it possible that in this 11 then was it possible that in this life integers come you have equal subset equal life integers come you have equal subset equal all basically equal in all now divide and all basically equal in all now divide and make two such subsets then yes true possible make two such subsets then yes true possible ok ok ok fine, then is it possible? No, if you take any partition like you are three and you are here and five is here, then still we will have one back, five is here, But one will go back. Okay, But one will go back. Okay, But one will go back. Okay, so here it will burn. We basically have to find out whether it is possible to do partition in two equal subs or not. Before that, possible to do partition in two equal subs or not. Before that, I understand a small concept and understanding this concept I understand a small concept and understanding this concept is very important. is very important. Hey, let's suppose input. Hey, let's suppose input. Hey, let's suppose input. again I have told that this will be solved like 01 up ok next one there is something or the other brother understand what basically you have to do with this is that you have to divide it into two parts And p2 is fine and And p2 is fine and And p2 is fine and its sum, this sum and this sum both should be equal. its sum, this sum and this sum both should be equal. Basically, whatever is the sum of integers in p1 Basically, whatever is the sum of integers in p1 and whatever is the sum of integers in p2, and whatever is the sum of integers in p2, both should be equal. This is both should be equal. This is given in the question, then what can happen? given in the question, then what can happen? given in the question, then what can happen? t1 + p2 = should be equal to even. Okay and if both are equal then tu p one it should be equal to tu even and the first partition should be equal to sum by I I I mean, the sum of one partition mean, the sum of one partition should be 2. But off friend, we are should be 2. But off friend, we are dividing equally and we also keep this constant that dividing equally and we also keep this constant that none of the integers should be dropped, that is, I should none of the integers should be dropped, that is, I should make two partitions in such a way make two partitions in such a way that the sum of both is equal. that the sum of both is equal. that the sum of both is equal. interiors also. Okay no interiors child and let's suppose sub is equal to both of them and both are equal okay if we are doing one more divide then the p1 which will be the first partition What will be the What will be the What will be the interior supposition in it? If this is p1 then whatever interior supposition in it? If this is p1 then whatever integers it contains will be the sum, okay what will it be integers it contains will be the sum, okay what will it be equal to, that equal to, that means you understand one thing here, if let means you understand one thing here, if let us sum up all the integers, whatever us sum up all the integers, whatever interiors we have, keep it okay. interiors we have, keep it okay. interiors we have, keep it okay. i = 0 till i = n - 1, we have total sum. It should be even and only then we can divide into two parts equal partition. If this sum is odd then let us suppose that all this is How if you How if you How if you divide two equal participants, then p1 and divide two equal participants, then p1 and p2, how can you not do 5.5 and 5.5, p2, how can you not do 5.5 and 5.5, or here there will be six, or here there will be or here there will be six, or here there will be five, only then it is possible which is not equal, five, only then it is possible which is not equal, okay, so this is what it means, so I will tell you okay, so this is what it means, so I will tell you this. this. this. all the integers, if and only then it is possible that we can divide p1 and p2 by one, if this thing comes odd then you can do anything, how to make partition, you can do You cannot divide equally. You cannot divide equally. You cannot divide equally. You can see the example. Lately, You can see the example. Lately, take your example. How much did you take? If you take 15, then take your example. How much did you take? If you take 15, then how will you divide 15 into two equally? Tell how will you divide 15 into two equally? Tell me, or else you will have to do exercise 7 and me, or else you will have to do exercise 7 and do it on one side. Okay, only then it is do it on one side. Okay, only then it is possible, that is. possible, that is. possible, that is. you can never divide, so we will first take out our check here that if the value of the sum is odd then it is okay then we will return it Jal Ki Bhaiya, It is not possible to do so. Let us assume the It is not possible to do so. Let us assume the It is not possible to do so. Let us assume the value of the sum. The value of the sum is value of the sum. The value of the sum is and then we will check and then we will check whether such a partition is being formed. There is such a whether such a partition is being formed. There is such a subset being formed whose value is equal to A. Let us subset being formed whose value is equal to A. Let us assume that we have got a set of assume that we have got a set of integers whose value is integers whose value is integers whose value is toh but second which will go back the remaining integers, let me explain its value automatically let us suppose what is the example we have 15 11 5 this is what we have set off wait ok we have it saying to find the sum here what is its sum. Its time here is 11 22 ok if I halve it then how much will be the submit 11 So can we find such a set of integers whose sum is 11 A then yes yes how in this one five and five if we pick this So how much is the sum of 11, then what is the remainder, what is the remainder, but its sum will not be there, so in the remainder, here only 11 is understood, we have taken out such a set of intersections whose sum So but these are the number of So but these are the number of So but these are the number of remaining integers children, what will be its sum, it will be remaining integers children, what will be its sum, it will be half of the total, but off is half of the total, but off is because we know what is even, because we know what is even, what is and is and what we have to do is what is and is and what we have to do is divide it into two partitions and we have divide it into two partitions and we have taken this mother. taken this mother. taken this mother. Subbaitu, if it is possible, will the second one ever be possible, what will be its value, it must be clear by now, if I explain you the conclusion here, then IF is equal to and then it is okay, let it be not In these you will return equal subsets, In these you will return equal subsets, if the value of sum is and i is like this then how will we divide p1 and p2. This set of p1 and p2. This set of integers p2 is a set of integers then integers p2 is a set of integers then what will be the value of p1. If you are ok then what will be the value of p1. If you are ok then you need one thing. you need one thing. you need one thing. reduced to what? The question has been transferred to whether it is possible to find a subset whose sum is the sum of the total. If we Total ka sabe Total ka sabe Total ka sabe tu a raha hai to but obviously the second one which tu a raha hai to but obviously the second one which went back with the remaining integer went back with the remaining integer will also have its sum. We did it. We found will also have its sum. We did it. We found out that yes brother, such a subset would be out that yes brother, such a subset would be possible that we possible that we can divide into two equal partitions. can divide into two equal partitions. can divide into two equal partitions. what was the previous question? The previous question was that you have been given the set of interior, you have given the sum and you have to find that it is possible to There There There is nothing in the question, friend, is nothing in the question, friend, things have been done with you, things have been written in this question, you have just been given a set of integers, you have found out the sum by yourself, what is the total, you have just been given a set of integers, you have found out the sum by yourself, what is the total, you are right, it is you are right, it is possible, it is such a subset. possible, it is such a subset. possible, it is such a subset. possible to find out whose sum, what is the total? Yes, it is possible, but off your sir, the remaining subset child, its sum will also be the total by you, so if we divide it into two equal partitions, then we will return true, so the You just had to find You just had to find You just had to find out the value of the pay sum here yourself, out the value of the pay sum here yourself, this was the trick here and there was this was the trick here and there was no trick at all, I hope you must have understood this thing, there was nothing rocket science in the question, just give you the ready sum here. was nothing rocket science in the question, just give you the ready sum here. And you found out the sum here, And you found out the sum here, how did you do it with the help of the question? What is the point of the how did you do it with the help of the question? What is the point of the question? The question was question? The question was asked again and again and if nothing was asked again and again and if nothing was done then the question got reduced and done then the question got reduced and we found out everything by ourselves. we found out everything by ourselves. we found out everything by ourselves. you calculate the total brother, if I do it with you tomorrow, you will literally enjoy it a lot, just stay with me in the code, okay, what did I do here, find it, nas dot size, namas dot size, what else did I do Did you find one and equal sum? Did you find one and equal sum? Did you find one and equal sum? Now basically we have to check Now basically we have to check that whatever integer we have given, if its that whatever integer we have given, if its time is odd then but now it is time is odd then but now it is not possible to partition both of them like this, not possible to partition both of them like this, but auto x sum is fine and but auto x sum is fine and What did I do here, let's make it a little bigger What did I do here, let's make it a little bigger in size. What did I do here, sum in size. What did I do here, sum plus equal Then I will tell you the solution of DP. Now look, now we have to find such a subset whose sum is what is the total. What did Sanvere, you did it. Okay, now we have the Sanvere, you did it. Okay, now we have the actual sum, which actual sum, which we will play by taking it here. we will play by taking it here. we will play by taking it here. here which I had last run just copy it here return date seat subset sub name one we are creating crop from the record in it we will pass n passed and sampar ki sam kya aayega sam bai Here I have done some problem, now let's Here I have done some problem, now let's Here I have done some problem, now let's define this function A function and it will be easy, define this function A function and it will be easy, for us this is the vector of for us this is the vector of vein, okay and we have passed and and the vein, okay and we have passed and and the base condition of the pass will be from everything, base condition of the pass will be from everything, we copy it completely. we copy it completely. we copy it completely. complete copy has been done from the base condition, there will be no problem till this point, there will be no problem, the editor will remain even, your name will be added here also, Namas will be added here also, the total will be added y2. We just checked a little bit here a little bit first, one more condition, total will be added y2. We just checked a little bit here a little bit first, one more condition, if even. if even. if even. value and IIT will be returned, let's run it and accept it. If we submit it, then someone will come on some test and find DLP, which one we have to convert, on which DP code and how will we do it in the best way? Now I change the code here in the coming questions. Okay, what has to be done for code change, nothing. Let us create a vector which we had created in the last lecture. So we Now see, Now see, Now see, in this question we just had to find the value of the sum, in this question we just had to find the value of the sum, what will be the value of the sum, what will be the value of the sum, made the total vector, copied and pasted it here, passed the DP here, passed the reference here, okay and by okay, you will not check here. okay, you will not check here. okay, you will not check here. more check will be removed and it will look like basically here is this and you have to pass the value of DP in all. Successfully submit. I always say Successfully submit. I always say that there is no rocket science in such questions, that there is no rocket science in such questions, you just have to you just have to understand the question well. understand the question well. understand the question well. and I am telling you the truth, look at the playlist from the beginning, you too could not even imagine how much terrible looking code you can do by yourself and I did it in front of you and explained it to you. Your question is done, your task again will remain the same, give this code top code and show it after processing, okay again, after some fear, that is, after two-three seconds, you will see its top solution on the screen and I hope that you will solve it. For your confidence, Aldo, this is the best of the day, first we have to write the code in the recess, then after that we ice it, this is the best approach for us, we can never call the court in this, we do You have to You have to You have to write the conditions yourself, along with this, write the conditions yourself, along with this, why did not you write everything in the best condition, why did not you write everything in the best condition, because this problem has its own problem, because this problem has its own problem, I had explained it to you easily, that is why I had explained it to you easily, that is why I did not do anything like this in this condition, this problem, I did not do anything like this in this condition, this problem, because there was a similar problem, because there was a similar problem, please. commenting, no matter how it feels like a lecture, commenting, no matter how it feels like a lecture, thanks and see you friends | 2024-03-22 10:58:26 | 416 | Partition Equal Subset Sum Dynamic Programming Hindi Explained | DP series Hello world #princebhai |
|
rAztd-UzAjU | so today my problem is distribute points in a binary tree uh distribute points in a binary tree uh each turn of that binary tree will have each turn of that binary tree will have a certain number associated with this a certain number associated with this and that number denotes how much coin and that number denotes how much coin that particular node has that particular node has so my job is to return the number of so my job is to return the number of moves that is required to make every moves that is required to make every node node have exactly one coin and it is given have exactly one coin and it is given that if you want to move one coin it that if you want to move one coin it will take exactly will take exactly one move so if we take a look at the one move so if we take a look at the example one example one uh one move will be required to to move uh one move will be required to to move that coin from that coin from from the root node three to its left from the root node three to its left child and another move will be required child and another move will be required to move that to move that uh a coin from its root node to a side uh a coin from its root node to a side sub right side sub right side so that everyone has exactly one coin so so that everyone has exactly one coin so the answer will be two here the answer will be two here so uh how will we actually upload this so uh how will we actually upload this question is question is firstly i will try to solve the the very firstly i will try to solve the the very sub problem of this sub problem of this uh we'll solve and i will solve this uh we'll solve and i will solve this problem on the node that has the problem on the node that has the minimum dependency and that will be the minimum dependency and that will be the leaf node because it does not have any leaf node because it does not have any any sort of issue of style so first any sort of issue of style so first let's let's uh see how we'll solve it on let's let's uh see how we'll solve it on its left its left and after that we'll move on to the and after that we'll move on to the parent itself so for better parent itself so for better understanding let's take a look at this understanding let's take a look at this example example example one this is the same example one example one this is the same example one okay so if i want to talk about this okay so if i want to talk about this node i'm just talking about this node node i'm just talking about this node right now okay right now okay so there are only three possibilities so there are only three possibilities here either the number of coins that it here either the number of coins that it may have is equal to one may have is equal to one either it is greater than one or either either it is greater than one or either this or either it is less than one this or either it is less than one so if it has if it is if it has already so if it has if it is if it has already if it already has exactly one coin if it already has exactly one coin then how many number of moves do we then how many number of moves do we require we don't uh we only require zero require we don't uh we only require zero number of moves because since it's a number of moves because since it's a leaf node and it already has one coin we leaf node and it already has one coin we don't need to do anything further right don't need to do anything further right so if it has exactly one coin with the so if it has exactly one coin with the number of moves that required is zero number of moves that required is zero what if it has less number of coins than what if it has less number of coins than one then it can only have zero number one then it can only have zero number coins it's not possible for coins it's not possible for it to have negative number of coins so it to have negative number of coins so if it has zero number of coins if it has zero number of coins how many moves do you think it will how many moves do you think it will require so that it gets one coin require so that it gets one coin it will only it will only require one it will only it will only require one one coin right it will always require one coin right it will always require one coin one coin so that it can get one one coin from its so that it can get one one coin from its parent that will exactly parent that will exactly uh you know calculate uh counter as one uh you know calculate uh counter as one move so that is the answer if move so that is the answer if it has uh less value than one now what it has uh less value than one now what if it has if it has you know more value than one so let's uh you know more value than one so let's uh if i take the example of this image you if i take the example of this image you know know if i take example of this image here it if i take example of this image here it has more than one point so how many has more than one point so how many steps do you think it will take me so steps do you think it will take me so that this this that this this this leaf node has exactly one coin so this leaf node has exactly one coin so the answer is it will the answer is it will take two moves because it has two take two moves because it has two additional coins right so it will take additional coins right so it will take me exactly two more so that me exactly two more so that it only has one coin so if we just you it only has one coin so if we just you know know if we try to formulate a for uh try to if we try to formulate a for uh try to you know form a formula you know form a formula we will find that uh there's a certain we will find that uh there's a certain pattern and i'm just talking about a pattern and i'm just talking about a leaf node here so leaf node here so the number of steps that a leaf node the number of steps that a leaf node will will require so that it will will require so that it it gets exactly one coin will always be it gets exactly one coin will always be equal to the mod of equal to the mod of sorry n minus one uh where n is the sorry n minus one uh where n is the number of coins that it has number of coins that it has so let's take a look let's try to for so let's take a look let's try to for fit this formula fit this formula so here it has zero points right so zero so here it has zero points right so zero minus one give me minus one minus one give me minus one if i take a mod it will give me a value if i take a mod it will give me a value of one which means that uh of one which means that uh i need one move so that it gets one coin i need one move so that it gets one coin and yeah that is exactly correct and yeah that is exactly correct so if i put the formula in this image it so if i put the formula in this image it has three coins three minus one will has three coins three minus one will give me two give me two and i only require two moves so that you and i only require two moves so that you know this particular node has exactly know this particular node has exactly one point one point so yeah that is the you know that is the so yeah that is the you know that is the formula that we that we will use for formula that we that we will use for a leaf node so we are done with the leaf a leaf node so we are done with the leaf node part now how node part now how are we going to solve the parent node so are we going to solve the parent node so solving the period is pretty simple solving the period is pretty simple because you know once we are done with because you know once we are done with the leaf node we have already already the leaf node we have already already solved half of the question solved half of the question so the the the number of steps that a so the the the number of steps that a parent will require will depend on the parent will require will depend on the number of uh number of uh the number of steps that it's uh left in the number of steps that it's uh left in the slide shall require the slide shall require so how many how many uh you know how so how many how many uh you know how many many uh steps does this this left child will uh steps does this this left child will require it will require two steps right require it will require two steps right so that it gets one coin so that it gets one coin now what about this child it will now what about this child it will require it will require exactly one coin require it will require exactly one coin uh it will require exactly one step so uh it will require exactly one step so that it can get that it can get one step uh it will get uh and can uh one step uh it will get uh and can uh sorry so that it can get exactly one sorry so that it can get exactly one point point so if i just add both of them two plus so if i just add both of them two plus one i'll get an answer of three and one i'll get an answer of three and that will that shows me how many number that will that shows me how many number of moves i require so that everyone get of moves i require so that everyone get exactly one coin exactly one coin now uh let's see suppose uh it has three now uh let's see suppose uh it has three three coins right so three coins right so it will take me two moves so that this it will take me two moves so that this this particular note can get two points this particular note can get two points okay okay so right right now i have two as my so right right now i have two as my answer after that answer after that i'll add one because you know uh this i'll add one because you know uh this this this this parent node will need to give one this parent node will need to give one coin here so after that i'll add one and coin here so after that i'll add one and i'll get my answer as three i'll get my answer as three so that is how we are going to solve the so that is how we are going to solve the answer for the parent node itself now answer for the parent node itself now uh let's take a look at for this example uh let's take a look at for this example also also how many how many coins does uh sorry how many how many coins does uh sorry how many coins this how many coins this uh this has it has two so how many steps uh this has it has two so how many steps is this uh this particular note required is this uh this particular note required only one step what about this note it only one step what about this note it has also it also requires one step so has also it also requires one step so that it can get bitcoin that it can get bitcoin or it can get one coin so the total or it can get one coin so the total answer will be one plus one that will be answer will be one plus one that will be two two and we only need two moves so that and we only need two moves so that everyone can get one coin so everyone can get one coin so yes one coin will move from here to here yes one coin will move from here to here and then one call will move from here to and then one call will move from here to here so that will only require here so that will only require two number of moves now as for the best two number of moves now as for the best example let's try to understand this example let's try to understand this okay so here we have okay so here we have uh three coins in the in the sorry we uh three coins in the in the sorry we have here we have three coins in the have here we have three coins in the leaf node leaf node so how many steps do you think uh will so how many steps do you think uh will require only two steps so that this require only two steps so that this particular node gets two coin right particular node gets two coin right i'll just move uh push off all the i'll just move uh push off all the overlord overall coins that i have overlord overall coins that i have so this will require you know it will so this will require you know it will get two points and i'll i'll move two get two points and i'll i'll move two steps done steps done now what about this coin i'll what about now what about this coin i'll what about uh uh now what about this i need exactly one now what about this i need exactly one move so that i can you know push off move so that i can you know push off one coin to here so after that it will one coin to here so after that it will get one coin and i'll get one coin and i'll i'll get one more wall but one extra i'll get one more wall but one extra move and after that this will move and after that this will you know this will uh push off the one you know this will uh push off the one coin to this part and i'll get one extra coin to this part and i'll get one extra move move so the answer that i'll get will uh that so the answer that i'll get will uh that i will get is four so my answer for this i will get is four so my answer for this question will be four question will be four and that is also correct uh we only need and that is also correct uh we only need four number of steps okay four number of steps okay so uh if you have already noticed this so uh if you have already noticed this then then you can you can see that the the number you can you can see that the the number of the number of steps that a parent of the number of steps that a parent will require the number of steps that a will require the number of steps that a parent will require parent will require will always be you know sum of how many will always be you know sum of how many steps its left child and its right child steps its left child and its right child will require will require and the number of you know the number of and the number of you know the number of value that the parent will return will value that the parent will return will always be equal to always be equal to uh you know the the sum of the left uh you know the the sum of the left steps plus the right steps plus steps plus the right steps plus how much value it has on its own minus how much value it has on its own minus one so one so here it's uh it's right child will uh here it's uh it's right child will uh will give him two steps right will give him two steps right here i'm just telling you how how are we here i'm just telling you how how are we going to calculate how many how much going to calculate how many how much value this this particular node will value this this particular node will return so it's right child will return return so it's right child will return it's a value of two okay so two it's a value of two okay so two plus how many coins it has on its own so plus how many coins it has on its own so he has zero coins he has zero coins okay and minus one minus one why because okay and minus one minus one why because you know he needs to have one coin for you know he needs to have one coin for himself himself so he will return exactly one coin uh he so he will return exactly one coin uh he will sorry he will will sorry he will return exactly one coin so it will take return exactly one coin so it will take exactly one number of move exactly one number of move so that is the formula that we'll be so that is the formula that we'll be using i'll just now show you the code using i'll just now show you the code for this for this sorry okay sorry okay so uh firstly i need to have a variable so uh firstly i need to have a variable that will store my answer that will be that will store my answer that will be self dot answer self dot answer after that since i am doing sort of a after that since i am doing sort of a dfs since i dfs since i i firstly need to reach the leaf node so i firstly need to reach the leaf node so from there i can you know i can from there i can you know i can start solving my solution so count steps start solving my solution so count steps here i'll pass a parameter that will be here i'll pass a parameter that will be root root and for the first thing that i need to and for the first thing that i need to check is if my if my root is check is if my if my root is empty or not so if my root is empty then empty or not so if my root is empty then i i simply return 0 because it means that i simply return 0 because it means that i have reached uh didn't so have reached uh didn't so from here i'll return zero otherwise from here i'll return zero otherwise otherwise what i'll do is i'll otherwise what i'll do is i'll i'll sorry base my cursor okay i'll sorry base my cursor okay otherwise i need to you know calculate otherwise i need to you know calculate the left steps the left steps the the amount of steps that it's left the the amount of steps that it's left child require and the child require and the right steps so for that i'll do a right steps so for that i'll do a recursive call count and recursive call count and root dot left done count steps count steps dot right okay and uh my dot right okay and uh my answer will be equal to uh so how many answer will be equal to uh so how many steps uh steps uh a particular node sorry how many you a particular node sorry how many you know uh a parent node will have that know uh a parent node will have that simple simple the left steps plus the left steps plus the right steps since the answer will the right steps since the answer will depend on how many steps its left depend on how many steps its left and its right child require as for the and its right child require as for the leaf node there is no need because you leaf node there is no need because you know know it does not have any left or right side it does not have any left or right side and the number of value and the number of value it returns how many number of you know it returns how many number of you know coins it will return i'm just returning coins it will return i'm just returning how many number of coin it returns so how many number of coin it returns so the formula is pretty simple the number the formula is pretty simple the number of coin that particular node has of coin that particular node has plus left steps plus plus left steps plus right sorry right steps right sorry right steps minus one so if you want you can just minus one so if you want you can just take a look at this uh as take a look at this uh as from the perspective of both of a parent from the perspective of both of a parent node and leaf node so if you take up node and leaf node so if you take up this from the perspective of a leaf node this from the perspective of a leaf node the left the left and the right side will be zero because and the right side will be zero because they don't have any left child or right they don't have any left child or right check check and the number of coin that it requires and the number of coin that it requires is uh root minus one i'm not i'm not is uh root minus one i'm not i'm not taking mod here i'm taking mod uh when taking mod here i'm taking mod uh when i'm calculating the value there i'm calculating the value there okay so now if you just look at the okay so now if you just look at the perspective from the root note perspective from the root note as we you know as we took it in this as we you know as we took it in this example the number of you know the example the number of you know the number of coins that it will return is number of coins that it will return is how many number of coins it's a uh sorry how many number of coins it's a uh sorry how many number of coins it has how many number of coins it has assimilated on its own assimilated on its own so that will depend on how many coins so that will depend on how many coins it's left inside it's left inside right child has given so here his right right child has given so here his right child has given him exactly two points child has given him exactly two points plus how many number of coins he has he plus how many number of coins he has he has on its own that will be zero right has on its own that will be zero right and minus one since he needs one coin and minus one since he needs one coin for himself so he will return exactly for himself so he will return exactly one coin and yeah that is correct one coin and yeah that is correct so that is the formula that we have used so that is the formula that we have used in here okay so firstly this will be in here okay so firstly this will be self answer plus equals to self answer plus equals to yeah okay so yes we are done with this yeah okay so yes we are done with this just i need to call this function count just i need to call this function count steps i'll pass through steps i'll pass through return sorry self dot answer return sorry self dot answer okay now let's run this code okay now let's run this code okay yeah so it works now it's submitted yeah so it works perfectly and uh this was my solution for what for this problem the distribution of coins in a binary tree | 2024-03-25 14:22:47 | 979 | Distribute Coins in a Binary Tree | Problem - 979 | Complete Algorithm | LeetCode | CoderJ |
|
9mf0-jFsvis | Had happened Agri Badi Today's Question Advanced 221 Adhere To The The Preview Ifre Have Exactly S Number Date Hai Vellu Christian And Equal To The The Ko A Super Example Another College Student Ko A Super Example Another College Student Will Have Two Digits element in total total number to two to two to two to two to two hua tha som water will have no desire his water will have no desire his life in the number dial us greater noida to the life in the number dial us greater noida to the number date - total number of number date - total number of number date - total number of Hai To Hai Lath Lekar Look Ahead In Binary Hai To Hai Lath Lekar Look Ahead In Binary Search Because Banner Research The Best Optimal Search Because Banner Research The Best Optimal Back To Find Any Valid Snow White And Back To Find Any Valid Snow White And Valuable Total Health With This Difficult Valuable Total Health With This Difficult Position Such Road Anar Width Regulation And Position Such Road Anar Width Regulation And Finally Will Return | 2024-03-22 12:35:52 | 275 | H-Index II | Leetcode Day 18 | June Challenge | Binary Search | Question #275 |
|
zmzhUq5oUec | so hey everyone today i am going to discuss the second question of the easy discuss the second question of the easy category category under this dsa bootcamp so here the uh the question is guess number higher or lower the question says that we are playing a guess game the game is as follows i pick a number from one to end you have to guess which number i picked so it's very clear that i have to apply binary search from 1 to n let's write let's write 1 1 2 2 3 3 in in let's take an example it is given here let's take an example it is given here n equals to n equals to 10 10 right right n equals to 10 n equals to 10 and he has picked number six right so one two 3 4 5 6 7 8 9 and 10 so here my starting variable will be from 1 10 right 10 right then they say that then they say that every time you guess wrong i will tell every time you guess wrong i will tell you whether i have picked is the number you whether i have picked is the number is higher or lower than your guess is higher or lower than your guess so they have done so they have done like they have given a function like they have given a function which is which is present on their system only means uh present on their system only means uh i don't have to write this function here i don't have to write this function here they have written predi predefined that they have written predi predefined that function and function and i will pass uh the number which i will i will pass uh the number which i will like to choose choose from start to end like to choose choose from start to end like at first from the middle and i will like at first from the middle and i will pass pass that number from the to the guess that number from the to the guess function and function and it will return it will return us minus 1 1 or 0 and us minus 1 1 or 0 and and and after that we will apply the condition after that we will apply the condition of the binary search like if it comes of the binary search like if it comes minus 1 then minus 1 then the peak number will be less than num the peak number will be less than num means the middle element and if it is 1 means the middle element and if it is 1 then the picked number will be greater then the picked number will be greater than the middle element and if it is 0 than the middle element and if it is 0 that that is the that that is the number that which number that which they have picked they have picked so i will return that number right so so i will return that number right so let's suppose uh they have given six and let's suppose uh they have given six and my mid mid element is five and if i my mid mid element is five and if i uh write this guess function uh write this guess function then uh i it will return me it will then uh i it will return me it will return me five ah they have picked six return me five ah they have picked six right right i have given five so five is less than i have given five so five is less than six so this condition six so this condition uh this condition uh this condition peaked element is greater than num means peaked element is greater than num means six is greater than five so it will six is greater than five so it will return us one return us one that means that the peaked element is that means that the peaked element is greater than my middle element so my greater than my middle element so my start will be start will be pointing over here pointing over here start will be ah pointing to mid plus start will be ah pointing to mid plus one one if my condition if my condition gives gives one one right if my condition guess condition right if my condition guess condition guess then the middle element if i give guess then the middle element if i give then it if it comes one then my starting then it if it comes one then my starting pointer will move to mid plus one pointer will move to mid plus one else if it is less else if it is less that means it will give minus one that means it will give minus one ah as it is written in the question that ah as it is written in the question that it will ah return minus 1 the predefined it will ah return minus 1 the predefined function uh if the peak number is function uh if the peak number is less than num less than num means the number which i will give if it means the number which i will give if it returns minus 1 then i will nothing i returns minus 1 then i will nothing i will do will do end pointer to i will move my end end pointer to i will move my end pointer to mid minus 1 yeah then it will be good to go then it will be good to go so let's start let's give our start equals to one and end is again and we will start our binary right right so at first i have to take the middle so at first i have to take the middle element and start plus start plus in minus start in minus start so i so i doesn't get doesn't get the overflow condition the overflow condition of the integer and then i will uh put my of the integer and then i will uh put my condition then i will at first let's condition then i will at first let's let's create our answer variable where i let's create our answer variable where i will will take my take my guess function they have given a guess function they have given a predefined guess g predefined guess g e double s and uh yeah e double s and uh yeah i will probably i will uh give i will probably i will uh give mid as my mid as my argument and uh it will return answer argument and uh it will return answer will be either minus 1 1 or 0 right will be either minus 1 1 or 0 right so i will give my condition that if so i will give my condition that if if if my answer becomes my answer becomes zero then i will return my middle zero then i will return my middle element if the answer becomes zero then the if the answer becomes zero then the middle element will be equal to equals middle element will be equal to equals to their peaked element to their peaked element so so i have to return the peaked element i have to return the peaked element right right if if if the answer becomes if the answer becomes minus 1 minus 1 then what i have to do i have to then what i have to do i have to move my end pointer to mid minus one move my end pointer to mid minus one if answer becomes minus one that means if answer becomes minus one that means the middle element which i have given is the middle element which i have given is greater than the peak element greater than the peak element so if the middle element is so if the middle element is let's suppose here is the middle element let's suppose here is the middle element and the picked element is 6 if the and the picked element is 6 if the middle element is greater than 6 i will middle element is greater than 6 i will definitely move my end pointer to here definitely move my end pointer to here to check our ah this range 1 to 6 to check our ah this range 1 to 6 so so here it will be like it is and here it will be like it is and else else means answer will be one if else else means answer will be one if answer equals equals to one then i will answer equals equals to one then i will move my move my start pointer start pointer to mid plus to mid plus one one right right so it will be okay and if it doesn't uh so it will be okay and if it doesn't uh found found the number then it will return minus one the number then it will return minus one right right this is the code and this is the code and yeah and yeah it will run fine [Music] yep yep it's accepting and it is also submitted [Music] right so this is the code if you have any problem | 2024-03-24 11:40:47 | 374 | Binary Search || Guess Number Higher or Lower || LeetCode-374||DSA BOOTCAMP ass--Easy|| Question-2 |
|
aEVGMb7KlQ4 | hey hey everybody this is Larry this is day 16 of the Leo day challenge hit the day 16 of the Leo day challenge hit the like button hit the Subscribe Buton join like button hit the Subscribe Buton join me on Discord let me know what you uh me on Discord let me know what you uh what you think about this cont oh this what you think about this cont oh this man I am man I am uh I mean you know I've said this like uh I mean you know I've said this like about a few thousand times now or at about a few thousand times now or at least a thousand times I guess CU my least a thousand times I guess CU my streak is a thousand days and I still streak is a thousand days and I still don't know what I'm saying you know uh don't know what I'm saying you know uh which tells you sometimes practice makes which tells you sometimes practice makes perfect but sometimes practice makes you perfect but sometimes practice makes you a little bit dumb uh anyway uh no the a little bit dumb uh anyway uh no the the reason why is is because today I the reason why is is because today I wanted to talk a little bit about wanted to talk a little bit about um uh there are a couple things I man I um uh there are a couple things I man I feel like these uh videos have kind of feel like these uh videos have kind of been little over the place I mean been little over the place I mean they're still wearing the lead code and they're still wearing the lead code and programming and stuff like that so let programming and stuff like that so let me know in the comments you know whether me know in the comments you know whether you find it interesting um this is very you find it interesting um this is very topical of course it is February 15 on topical of course it is February 15 on um 2024 I don't remember the year but uh um 2024 I don't remember the year but uh anyway so yeah there's a lot of debate anyway so yeah there's a lot of debate now on my Discord um definitely come now on my Discord um definitely come check that out about just um about all check that out about just um about all these things where basically the idea these things where basically the idea here is on on leite code contest um here is on on leite code contest um they've been adding this thing I mean I they've been adding this thing I mean I guess it's been a couple of years now guess it's been a couple of years now but they recently they've been kind of but they recently they've been kind of upping it a lot where um there's this upping it a lot where um there's this idea of system testing which is idea of system testing which is basically after you get you submit your basically after you get you submit your problem or you submit your solution for problem or you submit your solution for a problem for the contest and then it a problem for the contest and then it kind of um and if you haven't been fing kind of um and if you haven't been fing up and The Saga I've been kind of up and The Saga I've been kind of talking about it in the beginning of a talking about it in the beginning of a couple of these videos so if you're couple of these videos so if you're joining in here new my apologies you can joining in here new my apologies you can skip a little bit ahead to my fault but skip a little bit ahead to my fault but but yeah um there's this fail System but yeah um there's this fail System test um that kind of comes up like a few test um that kind of comes up like a few days afterwards and it's because I don't days afterwards and it's because I don't know uh and I don't know my personal know uh and I don't know my personal opinion is that it's kind of just lazy opinion is that it's kind of just lazy it's a little bit um I mean look once in it's a little bit um I mean look once in a while it's going to happen you know a while it's going to happen you know people make mistakes PR Setters are people make mistakes PR Setters are human and you know um you could lower human and you know um you could lower the probability of a mistake but the probability of a mistake but mistakes will happen right um of course mistakes will happen right um of course but the the um and as a senior engineer but the the um and as a senior engineer as a staff engineer um this is something as a staff engineer um this is something that comes up as a in a team as well that comes up as a in a team as well right like um when when if if someone right like um when when if if someone Junior on your team is able to take down Junior on your team is able to take down the service or system or create a level the service or system or create a level five or Level One Outage depending on I five or Level One Outage depending on I don't know some companies have level one don't know some companies have level one is the highest some some PE some is the highest some some PE some companies have level five I don't know companies have level five I don't know what what the highest priority right what what the highest priority right when when that happens uh it is not the when when that happens uh it is not the Junior's fault it is probably the senior Junior's fault it is probably the senior fault and the staff Engineers fault uh fault and the staff Engineers fault uh or at least the team lead's fault for or at least the team lead's fault for having a system in a way such that that having a system in a way such that that could happen of course sometimes that could happen of course sometimes that just happens just happens because um the team lead acknowledges because um the team lead acknowledges that there are tradeoffs between that there are tradeoffs between different um it's just a trade-off different um it's just a trade-off between uh this idea of like you know between uh this idea of like you know robustness and security and all these robustness and security and all these things security is maybe not good but I things security is maybe not good but I just mean like um reliability um you just mean like um reliability um you know you you take a trade-off in those know you you take a trade-off in those things knowing that you know for things knowing that you know for trade-offs and others right for example trade-offs and others right for example um just getting your product out maybe um just getting your product out maybe like you know you're trying to get it like you know you're trying to get it out by Christmas so out by Christmas so that so that like certain things can that so that like certain things can happen by Christmas or something like happen by Christmas or something like this right um or like getting things out this right um or like getting things out by super bow so that you can have a by super bow so that you can have a super bow ad or something I don't know super bow ad or something I don't know right and of course in those cases it's right and of course in those cases it's a very deliberate choice to trade um a very deliberate choice to trade um some one thing for another right I mean some one thing for another right I mean that said not everyone makes those that said not everyone makes those choices deliberately of course and you choices deliberately of course and you know uh that's the ideal case is that know uh that's the ideal case is that everyone kind of like you know make all everyone kind of like you know make all these value judgment and figure out what these value judgment and figure out what is the best thing to do for the product is the best thing to do for the product for the company for ETC right um so yeah for the company for ETC right um so yeah so definitely when the so definitely when the some fail you you don't blame the person some fail you you don't blame the person who accidentally press the wrong button who accidentally press the wrong button or whatever you blame the system you or whatever you blame the system you blame the tech lead who is basically the blame the tech lead who is basically the head of the the subsystem that you have head of the the subsystem that you have right whether that is you know your your right whether that is you know your your your fun uh L6 or your L7 I don't know your fun uh L6 or your L7 I don't know right depend your staff your senior right depend your staff your senior staff depending on your company depend staff depending on your company depend on what you're working on depend on the on what you're working on depend on the domain depend on all these things but domain depend on all these things but yeah right yeah what I thought thought about that is that you know I think uh I mean that was just like a general uh system thing and so as a as a mentor to engineers in the past um I actually have this sometimes as longer sometimes it's shorter but the variation of the speech basically say um telling my junior Engineers like hey look this is how it is you know um everything that goes down or whatever stops of me it's my fault if you're able to break it right and of course I mean you shouldn't try to break it you know obviously we're all assuming good intents and all these things of like you know uh everyone's trying relatively their hardest trying their best and and being in a coachable place so that you know we're in a place to learn we're all learning even me as at that time senior or staff or whatever it is depending on the situation right like we're all learning it's okay as long as we're all growing and it's okay as long as we don't make the same mistakes too many times I want to say not even twice really um but sometimes you know things happen and there you know especially when you're dealing with big system there's just a lot of interaction and the the thing about building um a robust system um versus you know coding as we have here is not just that you build the system in a way such that it is hard or I mean obviously you try but that's not a system thing right that's just a coding thing you have to build in with these errors right um and it's about you know having uh either process on a technology level or like something that's automated level or something on a manual process level like maybe it's a checklist of um to kind of being able to recover from from the failure state right whether it is the system being down or maybe you plan for it so that it know the system degrades but in a way that still works um you know and these are the kind of things that people think about and things that are you know um I think I mean I think maybe I'll split this up to a different video at some point to be honest so if you're watching this now thank you and I hope you appreciate just the kind of insight that I'm having now if not then you know fast forward as well I don't know it it is uh it's fine but but the idea there right is that you know you you try to make the best you try to figure out what is the most important to you your system and stuff like that and try to you know balance all these concerns in a way that you know it um self we themselveses right and there you know in terms of processes you know this is what makes a staff engineer a staff engineer um I know that there's a lot of uh title inflation and uh and all these things going on uh I feel like what what and I've been in industry for two decades which is kind of oh makes me old saying it but um but you know like what people would call a staff engineer now is probably a senior engineer like I don't know 10 years ago right give a tick um I don't know to me 10 years ago is like 1990 so I have to like think about the math man this is what happens when you um no but um no but but seriously though um but yeah but but seriously though um but yeah but these are the things that you know when these are the things that you know when um and what mix a senior engineer and sa um and what mix a senior engineer and sa Engineers that like I think what I and Engineers that like I think what I and don't get me wrong to be honest when I don't get me wrong to be honest when I was young and when I was that age and was young and when I was that age and when I was a junior I was you know I when I was a junior I was you know I thought I was uh a hot shot say without thought I was uh a hot shot say without cursing and I thought I was you know I cursing and I thought I was you know I was arrogant I thought I knew everything was arrogant I thought I knew everything I thought I I'm really smart I could do I thought I I'm really smart I could do anything I could do you know anything I could do you know but and you know and it's true that you but and you know and it's true that you probably you know as a junior if you're probably you know as a junior if you're a very good Junior um and you learn the a very good Junior um and you learn the right things I mean obviously you still right things I mean obviously you still have to do some learning and progression have to do some learning and progression um you learn the right things you Pro um you learn the right things you Pro you probably say I don't know 90% as you probably say I don't know 90% as good as a as you can be as when you good as a as you can be as when you become senior right or staff or whatever become senior right or staff or whatever it is now I don't know when you get more it is now I don't know when you get more senior not just the senior position I senior not just the senior position I suppose right and the the difference suppose right and the the difference and I mean there also Al obviously other and I mean there also Al obviously other dimensions I'm just talking about the dimensions I'm just talking about the tech um there are different you know tech um there are different you know kind of job descriptions to a senior and kind of job descriptions to a senior and a staff meaning um you know there are a staff meaning um you know there are some other responsibilities that you're some other responsibilities that you're you know like you know some some stuff you know like you know some some stuff is like project management depends on is like project management depends on Company by company and some stuff about Company by company and some stuff about mentorship making people around you mentorship making people around you better the a force multiplier or you better the a force multiplier or you know skill multiplier as you kind of know skill multiplier as you kind of read in somewhere I'm kind of hand read in somewhere I'm kind of hand waving a little bit because I don't want waving a little bit because I don't want to make this a 2hour video uh and you to make this a 2hour video uh and you want to listen to that 2our video maybe want to listen to that 2our video maybe one day you know let me know in the one day you know let me know in the comments and maybe one day I I'll post comments and maybe one day I I'll post something up something up um but yeah it 90 you'll probably be as um but yeah it 90 you'll probably be as a in terms of a programmer in terms of a a in terms of a programmer in terms of a coder um you're probably 90% as good as coder um you're probably 90% as good as a senior engineer right um in theory a senior engineer right um in theory like but you know um maybe it's a little like but you know um maybe it's a little bit of a scam but you know your title is bit of a scam but you know your title is not a programmer your title or you know not a programmer your title or you know you want your title to be software you want your title to be software engineer and what that means is okay engineer and what that means is okay engineer uh maybe that doesn't mean engineer uh maybe that doesn't mean anything but what it what it actually anything but what it what it actually means though is that you know you're means though is that you know you're hired hired to cynically one or two things two ways to cynically one or two things two ways to put it maybe one is to sell problems to put it maybe one is to sell problems for the company or maybe even more for the company or maybe even more directly make money for the company directly make money for the company right right um um [Music] and yeah and programming is one of the tools that you can and you know the reason why you get paid a lot as an engineer is that coding is one of those quotequote unique-ish skills that you are bringing to the job however however um that is a a skill it is in your tool set but it is not the only thing in your tool set and it is not you know the only thing that you're trying to do for the company right um and what I would say is that you know in the it is in those 10% in those 1% of the times that differentiates you know how how you handle these situations right meaning that you know people get PA that multiplier because of that 1% of the time because they know what to do when I guess you can say when everything Breaks Loose say or when a lot of things hit the fans say right I don't know why I R on a r on a rent like this a 10-minute ret uh but anyway going back to why I talked about this is that my point is that you know these these contests have been kind of a little bit silly contentious lately on lead code and I would necessarily bring on the testers I think some people bring on testers in this sense that like they should have found edge cases that maybe they should be but that that you know you don't blame on them uh maybe not even the problem set though you know I have some questions about the the part one part two thing as we talked about couple of days not a fan part if if your part one is a for Loop you can write other problems that are for Loops it's uh it's not impossible I believe you I believe in you um but but I I think that uh it's just yeah now but I think like having these lazy uh system testing kind of puts the incentive in the wrong place in that like hey we can't be lazy uh I think the biggest thing that hits you know is that well two things one is that I think Le Co has to figure out who they want to be and what they want to be especially in terms of the contest scoup and with that North Star they can figure out how do we solve things when they come up right like is it a contest platform or is it an interview platform that where the contest kind of eminates as much as it can roughly in an interview I mean obviously nothing's been perfect PRS get harder because you know you you know you want to be overprepared then underprepared I don't know there are some arguments there but like you know and I think one thing that I would that I loved about leadco contest to be honest and I'm just saying this as a nerd um is that I could be done when I'm done like I don't have like there was a time like it's been a few years now I suppose there was a time when you just submit it you get accepted you're like okay I'm done right like I don't want to spend the next hour like not trusting the lead coach test cases and you know thinking that maybe there's some weird thing and then come come to find that you know I'm wrong right and maybe I'm WR but I don't know like I feel like I don't know I feel like there is definitely in Fox of people during the contest and they bring from competitive uh programming and they bring into the the these contests their background of competitive programming contest and other things and and their ideas of what they should be which is like every other Contest out there look there's uh you look at you know C list right there's like I don't know I I I don't remember what it is but like there's like 20 30 competitions a week why are we doing Le code if it's exactly the same as all the other ones and now you know right like I don't know it would be very weird if like you know I don't know I I think that's my R for um I don't know system testing is never um I don't know system testing is never a happy surprise and now they kind of a happy surprise and now they kind of especially the past week um they have especially the past week um they have been adding system testing for for um been adding system testing for for um for Robin for Robin C and Robin C is uh a randomized C and Robin C is uh a randomized algorithm which I loved a lot uh it is algorithm which I loved a lot uh it is one of my first string algorithms that I one of my first string algorithms that I learned when I was in undergrad and I learned when I was in undergrad and I guarantee you that um well maybe I would guarantee you that um well maybe I would say guarantee but I would say that if say guarantee but I would say that if you use Robin C in an interview you use Robin C in an interview um you will get it you know your um you will get it you know your interviewer will be impressed you would interviewer will be impressed you would do well on the the prom maybe they'll do well on the the prom maybe they'll ask you something about Force positives ask you something about Force positives and you just give like a one line like and you just give like a one line like hey this is what happened to force hey this is what happened to force positive like there is some chance but positive like there is some chance but you know there are things you can do to you know there are things you can do to improve it with double hashing add improve it with double hashing add randomization Etc right um but you know the the current way that it is projecting uh TRC and the way that it is set up it is just not um it just means basically no Robin cop or at least you know I mean it's kind of already a little bit sad to be honest um because because you know for me um one thing that I was a purist about with respect to Leo contest in the last couple you know for for as long as I could is that I was really against copy and pasting like temporate code like um Union fine or whatever you know or segment Tre I guess is the other big one like I was very against I I like to do everything off my head off my brain somebody say that you know it affects my rating negatively and you know it's a little bit of a uh trickery and whatever um and you know yeah it's fine like I like other people do it I don't have to do it right but nowadays I feel like and and this goes back to where I think and and this goes back to where I think like Theo is not quite sure what it like Theo is not quite sure what it wants to be right because no one on an wants to be right because no one on an interview will allow you to P paste in a interview will allow you to P paste in a segment tree code because if they expect segment tree code because if they expect you to do that they just wouldn't ask you to do that they just wouldn't ask you a segmentary problem right um I mean you a segmentary problem right um I mean okay look there always bad interviewers okay look there always bad interviewers so maybe I wouldn't say always but with so maybe I wouldn't say always but with any reasonable interviewers um you know any reasonable interviewers um you know where they're actually trying to do where they're actually trying to do something you know um or trying to learn something you know um or trying to learn something about the candidates that's something about the candidates that's what they should do right what they should do right like um and even the last Q4 on the last like um and even the last Q4 on the last contest it was just basically 90% like contest it was just basically 90% like okay there's a cute observation which is okay there's a cute observation which is fun and then the rest is just copy in a fun and then the rest is just copy in a code that everyone else has done and now code that everyone else has done and now you make it even more tricky for some you make it even more tricky for some people to do I don't know people to do I don't know I I'm not a big fan of things that are I I'm not a big fan of things that are Library BR I feel like that is just lazy Library BR I feel like that is just lazy on the prom Setter side right because I on the prom Setter side right because I think like maybe one time two time like think like maybe one time two time like okay look we're all learning it's okay look we're all learning it's fine but you know at a certain point no fine but you know at a certain point no one is surprised that half the people one is surprised that half the people that finish on top has a library code that finish on top has a library code copy paste in right and then at some copy paste in right and then at some point like what are you testing here point like what are you testing here what are you what are you trying to do what are you what are you trying to do here what I mean you know having the here what I mean you know having the library ready library ready and like and some of the comments I get and like and some of the comments I get in my videos are like hey you know are in my videos are like hey you know are we expect to no this on interview and we expect to no this on interview and I'm and I always have to keep saying no I'm and I always have to keep saying no not really but you not really but you know anyway all right sorry friends this know anyway all right sorry friends this has been a 20 minute rent I'll actually has been a 20 minute rent I'll actually start the pr today hope everyone having start the pr today hope everyone having a good day in the eyes of February a good day in the eyes of February February 15 uh on this February 15 uh on this Thursday Thursday um man it is very cold here in New yor um man it is very cold here in New yor and I'm having some sniffles for and I'm having some sniffles for whatever reason oh man my butt sugar is whatever reason oh man my butt sugar is very high huh and oh yeah I I've been a very high huh and oh yeah I I've been a random quick up there as I that is that random quick up there as I that is that I still have my uh but Sho Coast Monitor I still have my uh but Sho Coast Monitor and it keeps on pinging me every time it and it keeps on pinging me every time it goes a little high and every time I got goes a little high and every time I got I actually don't do it that much during I actually don't do it that much during lead code problems but during the lead lead code problems but during the lead code contest it actually spiked a lot so code contest it actually spiked a lot so it's kind of interesting to see um it's kind of interesting to see um because I think it's just like the because I think it's just like the body's response to quotequote stress or body's response to quotequote stress or like the the fight or fight response so like the the fight or fight response so it releases and um you know what happens it releases and um you know what happens is that your liver releases these is that your liver releases these glycogen into the butt Stream So that uh glycogen into the butt Stream So that uh your muscles your muscles can in a way take the take the glycogen can in a way take the take the glycogen and put it in so that you can kind of and put it in so that you can kind of you know use your atps as fast as POS you know use your atps as fast as POS use you know get energy into your use you know get energy into your muscles as soon as possible is what I'm muscles as soon as possible is what I'm trying to say except for that I'm trying to say except for that I'm sitting here and like just I'm just sitting here and like just I'm just doing this to get my muscles moving I doing this to get my muscles moving I suppose but yeah anyway all right now suppose but yeah anyway all right now let's get started on today's Farm 1481 let's get started on today's Farm 1481 least number of unique integers after K least number of unique integers after K removals okay given an way of integers R removals okay given an way of integers R and integer K find the least number of and integer K find the least number of unique integers after removing exactly K unique integers after removing exactly K elements okay I mean right off the bat elements okay I mean right off the bat it seems it seems greedy right because basically um we greedy right because basically um we moving K elements so we well there are a couple of things that you can say I mean I say greedy but there are a couple things that goes of greedy immediately right the first one is that um well I guess if K if K is more than one you want to remove um so basically you want to remove all of them being the same number or as few numbers of elements as well the most ele how do I say this basically you want to remove all copies of one number whenever possible right because otherwise it doesn't it doesn't change the answer for example let's just take even here if you remove five you still have a five so so it still has two unique numbers right so you definitely want to remove anything that you you can remove to um all the numbers up for example if K is equal to two then in this case you can remove both fives or one four it doesn't matter you only have one number left and yeah and then after that then so that's the first observation and that observation allows you to group them together into a frequency table say right and then after that it just becomes well if you have two choices in a greedy kind of way would you remove the N if you have K moves would you remove the number that we appears more often or less often well less often so that you have more k for use to for later right so in that sense both you have two you have two points of greedy and I think that's good enough to get started and in terms of implementation you could do it in a couple of ways but uh but yeah oops let's get started I'll put them in a frequency table right so now F contains uh the value and the values the uh well the values in Array and then the count of them the frequency of them and of course you actually don't need the number itself like here we can actually store this as two and one we don't care about if it's five or four so then we can do something like f do values and and then we could sort based on it and now we move the Min first right so maybe we can have removed is equal to zero for v in this number right if K is greater than V then we subtract V and then we move um goes to one and then so the number that are left is just be F uh the length of f minus we moved right uh I mean then you can obviously count this in a little bit differently but that's what the I would say and yeah uh that's pretty much it this is n log in can I do better I don't know that you could do better well I mean the only way that it could be better is if is linear time and um yeah I guess you can say something um yeah I guess you can say something about like linear um uh linear sorting or something like this because they only I don't know by the way I'm just going to go with n l and time or of n space because the numbers can be all over the place and that's all I have for this one a really quick one uh surrounded by a 20 minute rent uh but yeah yeah I did basically the same way but I did in a funky way time huh weird but that was like also 4 time huh weird but that was like also 4 years ago now and I think four years ago years ago now and I think four years ago I I've a few things in four years so I I've a few things in four years so anyway uh that's all I have for this one anyway uh that's all I have for this one let me know what you think stay good let me know what you think stay good stay healthy to good mental health I'll stay healthy to good mental health I'll see yall later and take care byebye | 2024-03-21 10:13:53 | 1,481 | 1481. Least Number of Unique Integers after K Removals - Day 16/29 Leetcode February Challenge |
|
CERGNJDbqSU | this is a classic dynamic programming problem where we're given a set of problem where we're given a set of distinct integers and we want to find distinct integers and we want to find the total number of different ways that the total number of different ways that we can use the set of integers to add up we can use the set of integers to add up to our Target number so in example one to our Target number so in example one you can see that with the set of one two you can see that with the set of one two and three there's seven different ways and three there's seven different ways that we can reach our Target number four that we can reach our Target number four in example two with only the number nine in example two with only the number nine there's zero ways that we can reach our there's zero ways that we can reach our Target of three now imagine if we had a Target of three now imagine if we had a fairly large Target like the number 100 fairly large Target like the number 100 but the set of numbers we had were but the set of numbers we had were pretty small like only one two and three pretty small like only one two and three now it'd be really tedious to find all now it'd be really tedious to find all the different ways to add up one two and the different ways to add up one two and three to get to a hundred but imagine if three to get to a hundred but imagine if we already knew the number of ways to we already knew the number of ways to get to 98 and let's say it was this get to 98 and let's say it was this number X number X now the difference between 98 and 100 is now the difference between 98 and 100 is only two so all we have to do is find only two so all we have to do is find the number of ways to get two in this the number of ways to get two in this case we could have one plus one or just case we could have one plus one or just two which is two different ways so the two which is two different ways so the number of ways to get to a hundred would number of ways to get to a hundred would just be X which is the number of ways to just be X which is the number of ways to get to 98 plus 2 which is the number of get to 98 plus 2 which is the number of ways to get two so that's exactly what ways to get two so that's exactly what we're going to do we're going to create we're going to do we're going to create a list where there's an index for each a list where there's an index for each number from 0 up to the Target number from 0 up to the Target so basically we're only finding the so basically we're only finding the number of combinations to get to each number of combinations to get to each difference and then we're adding all difference and then we're adding all those up to get to Target those up to get to Target the start is a little bit weird at index the start is a little bit weird at index 0 we're going to put the number one 0 we're going to put the number one because we know that for any number in because we know that for any number in our set there's at least one way to get our set there's at least one way to get to itself and that would be a difference to itself and that would be a difference of zero now the difference is that we of zero now the difference is that we can have are one two or three because can have are one two or three because those are the numbers in our set so for those are the numbers in our set so for one since only positive numbers we can one since only positive numbers we can only have a difference of one only have a difference of one but for two we could have a difference but for two we could have a difference of one or two so we add up zero and one of one or two so we add up zero and one and we get two for three we can have a and we get two for three we can have a difference of one two or three so we add difference of one two or three so we add up one one and two to get four now for up one one and two to get four now for four we can only have a difference of four we can only have a difference of one two or three so we don't get all the one two or three so we don't get all the way back to the zero index we only add way back to the zero index we only add up one two and four for a total of seven up one two and four for a total of seven and that's our answer there's seven and that's our answer there's seven different ways to get to the number four different ways to get to the number four with this set and this is what the code with this set and this is what the code looks like basically we're going to looks like basically we're going to start off by creating our dynamic start off by creating our dynamic programming list and then we're gonna programming list and then we're gonna work our way up it moving you know one work our way up it moving you know one two or three steps back whatever the two or three steps back whatever the numbers are in our set and then for that numbers are in our set and then for that index we're going to add up all the index we're going to add up all the indexes indexes or the values for the indexes one two or or the values for the indexes one two or three steps back and then at the end three steps back and then at the end we're just going to return the total we're just going to return the total number at the end | 2024-03-24 11:45:38 | 377 | LeetCode 377 - Medium - Combination Sum IV |
|
kBH9XnQQTSY | Hi gas welcome and welcome back to my channel so today our problem is minimum time so today our problem is minimum time you make the rope colorful so in this problem you make the rope colorful so in this problem statement what have we given here statement what have we given here live score and balloons are arranged here ek live score and balloons are arranged here ek ro pe ok hai colors of balloons ek aapka ro pe ok hai colors of balloons ek aapka Casting colors have been given, okay it has colors in it, the rectangle is Casting colors have been given, okay it has colors in it, the rectangle is representing the representing the color of the balloon, okay, what does Like have to do, he has to color of the balloon, okay, what does Like have to do, he has to make this rope colourful, that is, if he make this rope colourful, that is, if he gets the color from two consecutive balances, gets the color from two consecutive balances, then what he has to do is one. then what he has to do is one. then what he has to do is one. removed from there, so for this she asks Bob, so what does Bob have to do, what has to be done about this disease in minimum time, what has to be made colorful, okay, then what will he do, you have given him the needed time, okay, what is there in it? How much time will it take for you to remove the rectangle balloon? Okay, so what will he do according to that, he will remove the balloon, that is, you have to make his row colorful in minimum time. Okay, so let us first understand this problem through an example, is the problem exactly ours Then we will see how we can solve it. Then we will see how we can solve it. Then we will see how we can solve it. Okay, I have Okay, I have taken the first example here. What have I given you here? I have given you the colors of N and balance. Okay, given you the colors of N and balance. Okay, this is the color of your end balance. Whatever it is, it will be this is the color of your end balance. Whatever it is, it will be of color B. of color B. of color B. is of another color and C is of another color. Okay, so here A is presented in blue. Now you can take anything according to you, just see that whatever you have should be colourful, There should not be a There should not be a There should not be a balloon, it is right, this is this, this is A, this is B, this is balloon, it is right, this is this, this is A, this is B, this is B, B, these two are of different color, right, two consecutive different are of different color, right, so which of these two will you give, then It is given in the time that it is It is given in the time that it is It is given in the time that it is taking 3 units of your time to remove it. It is taking 3 units of your time to remove it. It is taking four units of your time to remove it, taking four units of your time to remove it, so now who will do it? You so now who will do it? You need minimum time to remove it, so it is obvious need minimum time to remove it, so it is obvious that you will do it because there are that you will do it because there are three units here. three units here. three units here. this will become your answer. How much time did it take, how much will be in the answer? 3 because we need to remove only one button. Okay, now let us understand through the second example how we will do it here. But what do we do so here is what we have to do, then at least how many of these three will be made n't want to do so, then we have to make two colors in a row, right, n't want to do so, then we have to make two colors in a row, right, so here is your so here is your 3 units to remove this. 5 units to remove this. If it 3 units to remove this. 5 units to remove this. If it takes 10 units to remove this, then takes 10 units to remove this, then who will care if you have two options, who will care if you have two options, so we will not remove it. Okay, now here we come, these three are from the If it is of the right color then If it is of the right color then If it is of the right color then how many of these three will you have to remove, how many of these three will you have to remove, two will have to be removed at least, what will you two will have to be removed at least, what will you do, do, now whom will you remove, then see how much does it take for now whom will you remove, then see how much does it take for you to take five, and you to take five, and how much does it take for three, so which of the three? how much does it take for three, so which of the three? Hataoge And this is the thing that now you will Hataoge And this is the thing that now you will hate this because you are hate this because you are taking less time in both of them, right here it will taking less time in both of them, right here it will take a unit to remove both, okay now this take a unit to remove both, okay now this is a single rate so there is no need to remove it, is a single rate so there is no need to remove it, now this scene is of group. now this scene is of group. now this scene is of group. four of this group, these four belong to this group, then which of these four will you tell, at least three will have to be removed, then what will happen is that it will become colourful, if you give the right to If you If you If you are not of color from the consecutive one then are not of color from the consecutive one then what are the options here to remove you? Five what are the options here to remove you? Five 4 8 1 Now if you are asked among these three then 4 8 1 Now if you are asked among these three then which one will you choose? Will you look at the lowest one? Will you choose this one? Will you choose this one? 5 + 499 5 + 499 plus one 10 so 108 plus 8 16 + 10 26 plus one 10 so 108 plus 8 16 + 10 26 Answer Apna 26 year right ok so Answer Apna 26 year right ok so how will we solve this problem here what we will do is how will we solve this problem here what we will do is 2.2 we will do that we will take income and k 2.2 we will do that we will take income and k okay what will we do from here to okay what will we do from here to here here here equal to I? So what will we actually do? What will we find the group of color from? Okay, if we find the group of color from then we will see here that it is from this color. Okay, go Is it Is it Is it equal to I? Is it equal to Han? Go ahead, is it equal to I? Is it equal to Han? Go ahead, is it equal to Kard? Is it equal to Han? Okay, equal to Kard? Is it equal to Han? Okay, so when you come till here, you will so when you come till here, you will get color from Se. Okay, now see how much is there in it, get color from Se. Okay, now see how much is there in it, we don't know, we don't know that much. we don't know, we don't know that much. we don't know, we don't know that much. is there, we just have to see that you will have to remove all of them except the maximum. Whatever be the number, you will have to remove all of them except the maximum. If there is four, then there will be three occurrences. If there is 5, then four will have to be removed. If there is six, then your punch. We know that this incident will happen, so we will have to remove all of them with one break. Right, you are leaving the maximum one, right, so what will we do in this, whatever is the maximum, we will record it in a variable, what is the maximum till now, it Ok and how much will our total unit Ok and how much will our total unit Ok and how much will our total unit become 3 + 5 + 10, this much will be ok, we will find the sam, become 3 + 5 + 10, this much will be ok, we will find the sam, so what will be this much of a group, it will be so what will be this much of a group, it will be 18 and 18 and what will we do in total timing, 18 - we will do maximum mines, what will we do in total timing, 18 - we will do maximum mines, ok ok ok left, we will add 8 here, ok, this will be done, then what will we do with I, we will update it here, it will be updated and it will start from here, then we will find a group here, it will come till here, we will find a group. What will we do here also? We will find these three in advance. Sam, it's okay in 12 plus. This is done. If you come here then you will move ahead. If you come here, if you don't find them, then we will go here and take them. We will get a group, We will get a group, We will get a group, it is ahead of badhaaoge, it is equal to I, it is it is ahead of badhaaoge, it is equal to I, it is equal to ja ke banaoge or it is equal to ja ke banaoge or it is equal to ahead of badhaaoge, okay, we have found this one group, equal to ahead of badhaaoge, okay, we have found this one group, what will we do in these groups, we will what will we do in these groups, we will sum everyone, we will sum everyone, fine sum everyone, we will sum everyone, fine 5 plus 499 This is what we saw here, this is the same right, we will This is what we saw here, this is the same right, we will return it here, now we come to the return it here, now we come to the cold part, I will cold part, I will tell you the parts with code, it is from both, tell you the parts with code, it is from both, we have to do it as I have told, it is we have to do it as I have told, it is ok. ok. ok. zero total time, okay and N taken, whatever size the color will be, its balance will be the same, what will we do now, I should be < N, K should be < N, okay, We will take zero, the We will take zero, the We will take zero, the maximum time of a group, you take the current total maximum time of a group, you take the current total in the procession initial, take zero, okay in the procession initial, take zero, okay now the current means what is the total now the current means what is the total of any group, it is not zero, then you will see, keep incrementing J< and What to do in the total? Keep adding, What to do in the total? Keep adding, What to do in the total? Keep adding, what will happen with this? 10 In the total, what will happen with this? 10 In the total, you will get the total. In the maximum time, you will you will get the total. In the maximum time, you will get the maximum among them. get the maximum among them. Okay, then what will you do to I? Okay, Okay, then what will you do to I? Okay, then what to do in the total time? The current is then what to do in the total time? The current is as much as the current i.e. Sam total. as much as the current i.e. Sam total. as much as the current i.e. Sam total. it, min the maximum time from it and can add it to the total time, add it and what will you do with the total time in the last, dem it, right, I hope you have understood. If you liked my video, please like, please do thank you | 2024-03-21 14:34:30 | 1,578 | 1578. Minimum Time to Make Rope Colorful |
|
bprDe2jWgJs | hey what's up guys this is chung here so let's take a look at this week's so let's take a look at this week's weekly contest problem number 1643 weekly contest problem number 1643 case smallest instructions case smallest instructions so this problem you know it's a hard so this problem you know it's a hard problem but it's kind of tricky because problem but it's kind of tricky because this one is more like this one is more like a math problem rather than a a math problem rather than a regular like or either either like a dp regular like or either either like a dp or like like other problems or like like other problems so basically you're given like so basically you're given like uh i'll just skip the uh those kind of uh descriptions here i'll just use these examples here basically you're given like a destination which is the basically the coordinates of a of a 2d here right a 2d plane here and another k here so the process is you need to from zero so the process is you need to from zero zero zero and you're starting from the zero zero and you're starting from the zero zero and then and then you end with this destination in this you end with this destination in this case which is the two and three case which is the two and three and then as you guys can see there are and then as you guys can see there are like like many ways you can get you can get to many ways you can get you can get to this to this location this to this location right and every time you can either go right and every time you can either go to right or or you can go down you to right or or you can go down you you only have those two options and if you only have those two options and if you go to right you go to right as if you're going like uh adding a h as if you're going like uh adding a h instruction which means the horizontal instruction which means the horizontal and if you're going down it means that and if you're going down it means that you are adding like a you are adding like a a v instruction which is the other a v instruction which is the other vertical vertically vertical vertically and based on based on your your choice and based on based on your your choice either you go either you go you go to the you go to the crease go to you go to the you go to the crease go to right or you go down right or you go down you end up with a with a unique path you end up with a with a unique path okay with h and v as you as you guys okay with h and v as you as you guys can see here so h is smaller than v can see here so h is smaller than v okay and here is a this is the tricky okay and here is a this is the tricky part basically part basically you need to find the case smallest you need to find the case smallest the case smallest the case smallest instructions among all those instructions among all those instructions instructions as you guys can see here we have as you guys can see here we have we have 10 instructions in in total we have 10 instructions in in total because we have because we have we need to make a 3 h we need to make a 3 h move and the two v moves that's why we move and the two v moves that's why we have 10 in total have 10 in total and we need to find the first one so the and we need to find the first one so the first one is hha to vv first one is hha to vv that's why we have this this one and that's why we have this this one and some other examples here same thing here some other examples here same thing here same same same destinations but this time we need same destinations but this time we need to find the k equals number two to find the k equals number two which is the hh v h v which is the hh v h v right so right so i mean the intuition is like this i mean the intuition is like this basically actually it already gave us basically actually it already gave us some some some some hints here you know so the hint is this hints here you know so the hint is this is this one i mean the total is this one i mean the total combinations is the what combinations is the what it's a it's a and like so ncr means the it's a it's a and like so ncr means the the combination the combination of this the combination the combination of this row plus column so here we have we have three h and and so here we have we have three h and and the two v's right and the total the two v's right and the total combinations of this combinations of this of this five letter is what is three of this five letter is what is three plus two right basically we need to have plus two right basically we need to have like the combination like the combination the combination of three plus two uh the combination of three plus two uh out of two basically we are we're out of two basically we are we're selecting two values out of five selecting two values out of five so how are we going to calculate this so how are we going to calculate this right we have like what three right we have like what three times no we have a sorry five two times and then divided by two times times one and then divided by two times times one sorry i think it's the 5 factorial right sorry i think it's the 5 factorial right divided by 3 divided by 3 factorial times 2 factorial right that's factorial times 2 factorial right that's the the the combination which is 10. that's how the combination which is 10. that's how we get 10 here right so actually this so this problem it's more like a math plus the dp plus a greedy you know i'll give you some examples here since we have a k here right so let's say we have a h v and then we have a x x x x x x here right and let's say we have already uh fixed h v here now we're at this location here and 4 vs left in this range here and 4 vs left in this range here at this location right at this place at this location right at this place we we basically we only have two options we we basically we only have two options right right with the current k here with the current with the current k here with the current case case smallest number we need to match here we smallest number we need to match here we either either we can either put an h here or we can we can either put an h here or we can put v here put v here okay it depends on what so depending on okay it depends on what so depending on how many how many how many letters i mean how many can we how many letters i mean how many can we afford afford can we afford putting v here so why is can we afford putting v here so why is that because if we put that because if we put h here let's see we have a we have a h here let's see we have a we have a like case remaining here like case remaining here if we put h here it's basic we're still if we put h here it's basic we're still using the using the the smallest the smallest possible the smallest the smallest possible options here right so it means that we options here right so it means that we still need to make still need to make like a case bigger like a case bigger case bigger number than the current case bigger number than the current options here options here right but if we're putting a v here right but if we're putting a v here okay if you're putting a v here it means okay if you're putting a v here it means that okay we are skipping that okay we are skipping all those numbers all those like uh all those numbers all those like uh the possible numbers who is starting the possible numbers who is starting with h with h from the current k basically we're from the current k basically we're skipping that so now the problem now it's easier to solve this problem because all we need to do is just that we we just need to see if we can afford putting a v here which means that by skipping this this man all the numbers that starting with h if we can do that then we'll basically we'll put a v here otherwise we'll put h and then the next problem is that how can we find all the numbers that's starting with h right so let's let's assume we have uh in total we have six here right how how about all the numbers starting with h it mean it means that you know we are we're removing this h and we have now we have five here right so we have a five we have c what c5 c54 right because that why is that because this is in total we we have six here right so we have six minus one since we have fixed this uh putting h here it means that we still have uh four v's within the remaining five numbers that's why the total combinations of here is like c five 4 which is exactly the same the same numbers right with who is starting with h yeah and after we have putting a v here yeah and after we have putting a v here we'll just we'll just uh subtract that number of uh subtract that number of that number of combinations starting that number of combinations starting with h from the k with h from the k and we'll keep doing it until we have and we'll keep doing it until we have finished finished uh constructing all those all those uh constructing all those all those instructions instructions and that's our basic solution here and that's our basic solution here so i'll try to explain a little bit more so i'll try to explain a little bit more here so here so basically we have destinations right basically we have destinations right destinations destinations so the m is the uh is it's v so the m is the uh is it's v right and h you know out put right and h you know out put like uh this is like the the v like uh this is like the the v the v count okay right so and this is the v count okay right so and this is that that that that the h count okay so and then we have a answer equals to empty okay and uh i'm going to have like this uh for i in range uh at the beginning uh since we have we have in total v count plus the h count and then here i'm going to have like and then here i'm going to have like start right start start right start with h so with h so all the numbers start with h how many do all the numbers start with h how many do we have we have so in python we have this combination so in python we have this combination built-in functions that built-in functions that can help us do that you know can help us do that you know so we have like this minus so we have like this minus i and the minus one because that's the i and the minus one because that's the current okay so first thing this is the current okay so first thing this is the current current the current load the uh the remaining the current load the uh the remaining the remaining numbers of the card the remaining numbers of the card numbers but since we are trying to numbers but since we are trying to get the the numbers all the combinations get the the numbers all the combinations starting with h so which means that starting with h so which means that after fixing h as a current after fixing h as a current i and then we will the remaining length i and then we will the remaining length is -1 is -1 okay and then okay and then we have like uh we have like uh the downs okay so i'm also going to the downs okay so i'm also going to define another here so like define another here so like remaining remaining v okay so at the beginning we have a v count right we have a remaining v here and this is the uh the starting with h the current the combinations that who is starting with h and now we simply just need to do a check here if the k so k means that we still have need to make this case uh the case numbers who is currently bigger than the current number because we are we're looking for this because we are we're looking for this case smallest number and we still have case smallest number and we still have this case remaining here this case remaining here basically if the k is smaller than the basically if the k is smaller than the target target than the startup is h here than the startup is h here it means so what does it mean it means it means so what does it mean it means that that we have this many we have this many we have this many we have this many uh this uh this uh numbers this combination uh numbers this combination who is starting with h and even this one who is starting with h and even this one is is is is greater than the remaining smallest greater than the remaining smallest number we're looking for number we're looking for so what does this tell us it tells us so what does this tell us it tells us you know let's say you know let's say uh for example we have xx right and here let's see we have a we're we're deciding what uh wait which number uh which instruction where we need to put it here right let's say in the at this moment k is okay and we have five we have five okay and we have five we have five numbers left numbers left right and the we only right and the we only and there are there are only four and there are there are only four numbers we where numbers we where we need to look for right so which means we need to look for right so which means that it has to be h here that it has to be h here because here it can be like h because here it can be like h h or v v h something like this but h or v v h something like this but if we're putting the v here even though if we're putting the v here even though we're putting we're putting h here right so we're we're way over h here right so we're we're way over than this than this like k uh fourth smallest number at this like k uh fourth smallest number at this moment at this location moment at this location so that's why we have to put h so that so that's why we have to put h so that we can we can make we can get we can we can make we can get after filling in all those kind of uh after filling in all those kind of uh instructions we can get the fourth instructions we can get the fourth smallest number smallest number right okay so that's why here right okay so that's why here then we have to do a then we have to do a uh in append h here elsewhat uh in append h here elsewhat out is pretty the other way right else out is pretty the other way right else we we do a v so this is the other uh we we do a v so this is the other uh the other way around basically if the the other way around basically if the current k current k is it's too big it's too big then the uh is it's too big it's too big then the uh then the the case is who is uh who is then the the case is who is uh who is starting with starting with h then we have to put v here because we h then we have to put v here because we have to have to cut we have to skip this this many cut we have to skip this this many numbers numbers okay and then after doing that right we okay and then after doing that right we have have since we have skipped all the numbers since we have skipped all the numbers that start with that start with h now we will basically move h now we will basically move subtract those numbers from the k and subtract those numbers from the k and now with now with the the updated k is the remaining the the updated k is the remaining remaining numbers we need to be uh remaining numbers we need to be uh looking for right and since we're looking for right and since we're putting a v putting a v here i'm going to also here i'm going to also decrease this remaining decrease this remaining v by one remain okay and here later on which okay okay yeah so let's run a call here yeah so let's run a call here okay cool submit okay cool submit all right cool so i mean all right cool so i mean as you guys can see here right so what as you guys can see here right so what what if the k what if the k is is so is very big okay is is so is very big okay so if case is so big you know so if case is so big you know and ideally we should have like uh oh we and ideally we should have like uh oh we we all know it's going to be vv v and we all know it's going to be vv v and hhh hhh right because that's the the biggest right because that's the the biggest number right number right so how how would this thing works here so how how would this thing works here right so that means you know right so that means you know k will always be greater than the start k will always be greater than the start of his h of his h here so it means that we'll always go to here so it means that we'll always go to the answer here the answer here right then we try to decrease the case right then we try to decrease the case by this by this and then but again the k is still bigger and then but again the k is still bigger than this so we have to put a than this so we have to put a v here and yeah until you know until what until this like remaining v equals to zero right so let's say the k is super big and and there will be a point right we have used all the other v's here and now we're at h here right so if we add h here you know the uh the combinations here right so the combination of here will be okay let's see okay let's see um i think that so it won't happen um i think that so it won't happen because i just because i just i just realized that you know there's a i just realized that you know there's a constraints here so constraints here so k will not be greater than th than the k will not be greater than th than the total combinations of the row and the total combinations of the row and the columns here columns here so yeah so basically it won't be that so yeah so basically it won't be that that case that case it won't happen so it will always it won't happen so it will always within the range here and this will within the range here and this will always work so how about time and space complexity right so i mean we have a let's say we have m and n here right so of course this is a o of m plus n right and how about this combination okay i mean this combination you know the uh so the way we're calculating the combinations will be uh a pre products from from this m a pre products from from this m from m plus n and here it's going to be o of one because because if we're trying to calculate this one we'll be having like a pre pre-products okay preproducts with the range of the uh from this is from zero to m plus n and here we'll the use of the values we have been we have previously calculated so here it should be like a o 1 here so the total time complexity it should be yeah okay so i think that's it for this yeah okay so i think that's it for this problem you know problem you know um i think it's a pretty tricky problem um i think it's a pretty tricky problem at least for me yes at least for me yes because i i'm i'm not that good at this because i i'm i'm not that good at this math kind of math problem math kind of math problem so this is something we all need to so this is something we all need to [Music] [Music] to keep to to keep learning you know to to keep to to keep learning you know to keep learning so yeah and again so the key point for this problem is that you know we just need to know this way of calculating all the basically all the combinations where all the remaining instructions who is starting with h and then with this number i'll given these numbers and we check if we can afford skipping right all those kind of h's if we can we go we go with v if we can't then we go with h right cool that's it thank you so much for watching this video guys stay tuned | 2024-03-19 15:59:58 | 1,643 | LeetCode 1643. Kth Smallest Instructions |