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
jILNXOXQiyU
Hello everybody welcome back to my channel in this video I be solving channel in this video I be solving another SQL problem problem number 1661 another SQL problem problem number 1661 average time of process per machine average time of process per machine let's take a look at the problem let's take a look at the problem statement we are given a table called statement we are given a table called activity is which is consisted of four activity is which is consisted of four columns machine ID process ID activity columns machine ID process ID activity type and time stamp the combination of type and time stamp the combination of columns machine ID process ID and columns machine ID process ID and activity type is the primary key machine activity type is the primary key machine ID is the ID of a machine process ID is ID is the ID of a machine process ID is the ID of a process running on the the ID of a process running on the machine activity type is of an enum data machine activity type is of an enum data type has the value of St in type has the value of St in end time stamp is a float representing end time stamp is a float representing the current time in seconds activity type start means the machine starts the process and means the process the start Tim stamp will always process the start Tim stamp will always be before the end time stamp for every be before the end time stamp for every machine ID and process ID pairer all machine ID and process ID pairer all right so our task is to find the average right so our task is to find the average time each machine takes to complete a time each machine takes to complete a process the time to complete a process process the time to complete a process is the end is the end time minus start time minus start time the average time is calculated by time the average time is calculated by the total time to complete every process the total time to complete every process on the machine divided by the number of on the machine divided by the number of processes that will processes that will run all right the result table should run all right the result table should have the machine ID along with average have the machine ID along with average time as processing time which should be time as processing time which should be rounded to three decimal places let's rounded to three decimal places let's take a look at the T take a look at the T example so here we have the activity example so here we have the activity table machine ID number zero has two table machine ID number zero has two process IDs and each process ID has its process IDs and each process ID has its own start and own start and end time end time stamp all right same with machine ID stamp all right same with machine ID number one this machine ID has two process IDs zero and one and each process ID has its own start start and end similarly with uh machine ID number two so the output we should see two columns machine ID and processing time processing time would be the average time the each machine ID takes to complete their process so let's read explanation so there are three machines running two processes each machine ID number zero one and two and running two processes each processes zero and one processes 0 and one 0 and one so machine number Zer are average time is of the process ID number zero n minus start plus process ID number one n minus start the sum of these two divided by two will be the average time for machine ID number zero and it's the same for other uh machine all right so this is a self jooin all right so this is a self jooin situation and if you're not familiar situation and if you're not familiar with self jooin in Sequel um I would with self jooin in Sequel um I would recommend you read some articles recommend you read some articles explaining self jooin concept uh so self explaining self jooin concept uh so self jooin is commonly used in the cases when jooin is commonly used in the cases when the there's a relationship hierarchical the there's a relationship hierarchical relationship or sequential relationship or sequential relationship um so in this case is the relationship um so in this case is the hierarchical relationship hierarchical relationship meaning there is a parent child meaning there is a parent child relationship in this um data relationship in this um data so for example this machine ID number so for example this machine ID number zero has two process IDs zero and one zero has two process IDs zero and one and each process ID has his own activity and each process ID has his own activity type start and end um so this is the type start and end um so this is the parent child uh parent child uh relationship that's why uh in for this relationship that's why uh in for this problem it's going to be a self-join problem it's going to be a self-join situation where you are going to join to situation where you are going to join to itself and to get the um start and end itself and to get the um start and end of each process ID and we'll get the of each process ID and we'll get the average uh processing time of the each average uh processing time of the each machine ID so my goal now is to get uh machine ID so my goal now is to get uh for each machine ID there will be two for each machine ID there will be two rows one for process ID zero and another rows one for process ID zero and another one is for process ID one with the for one is for process ID one with the for each row of machine ID zero process ID each row of machine ID zero process ID zero uh I will have the end zero uh I will have the end time start time and the processing time time start time and the processing time will be the end minus will be the end minus start uh same for machine ID number zero start uh same for machine ID number zero for process ID ID number one I will also for process ID ID number one I will also have End Time start time and processing have End Time start time and processing time which is the end minus time which is the end minus start so in the next step I want to start so in the next step I want to create this create this table this is the result of the self table this is the result of the self join of the activity table we'll be join of the activity table we'll be joining on machine ID process ID and we joining on machine ID process ID and we will get the column end uh time will get the column end uh time uh where the activity type equal to end uh where the activity type equal to end and start time where activity type equal and start time where activity type equal to start and the processing time will be to start and the processing time will be equal to end time minus start time so equal to end time minus start time so once we have this once we have this table we can get the average processing table we can get the average processing time for each machine ID by um getting time for each machine ID by um getting the sum of the processing time of the sum of the processing time of process ID number zero and processing process ID number zero and processing time of the process ID number one / by time of the process ID number one / by two all right so let's create the table two all right so let's create the table that I just show you this table all that I just show you this table all right so we're going to do select right so we're going to do select um we're going to we want to see the um we're going to we want to see the machine machine ID ID um process um process id veress id time but we want to see the uh the end time St so this end table start table start it time same and it time same and start so going to do from so in the self start so going to do from so in the self join the two table you always have to join the two table you always have to give an alist to to the table you so give an alist to to the table you so joining to itself so it's going to be joining to itself so it's going to be from from activity I will call it activity I will call it h join h join with with activity start call it activity start call it start on we're going to join start on we're going to join on on end um end um machine ID equal to start machine and and do process ID process ID equal and and do process ID process ID equal to start do to start do process process ID and I mentioned earlier we want to ID and I mentioned earlier we want to get the the end get the the end time um in the end table and end do time um in the end table and end do activity type equal to end and start do activity type equal to start so let's take a look now and see what we have our machine ID okay so we have to give this an alas because we have machine ID in both table just going to do okay all right as you can see now I'm okay all right as you can see now I'm having machine ID and process ID for for having machine ID and process ID for for each of them the end and start so now each of them the end and start so now we're going to add a processing time we're going to add a processing time where the um equal to end minus start so where the um equal to end minus start so in in order to do that we're going to in in order to do that we're going to add another column called processing add another column called processing time where um time where um n do times n do times St minus two start dot time St minus two start dot time stem as processing that right that right so we should see this is the table that so we should see this is the table that I um showed you earlier so this is we I um showed you earlier so this is we have machine ID process ID and start and have machine ID process ID and start and processing time so this is the table we processing time so this is the table we will be working with we'll get the will be working with we'll get the average um by getting the sum of this average um by getting the sum of this one and divided by two so in order to do one and divided by two so in order to do that we are going that we are going to um to um select so we need to have machine select so we need to have machine ID ID machine machine ID ID um so to get the average it's going to um so to get the average it's going to be average be average function is uh and we call this select function is uh and we call this select this this from from we will call this table um time for example you can name it whatever you want go time so it's going to be time you can either do this way and then time you can either do this way and then Group by machine ID or you can just do Group by machine ID or you can just do the um uh sum the the sum of uh these the um uh sum the the sum of uh these two and divided by two and divided by two but I figure we can do average and two but I figure we can do average and group by machine ID this way we don't group by machine ID this way we don't have to write a long um code so average have to write a long um code so average uh time processing time and we want to uh time processing time and we want to get uh the result get uh the result round it to three decimal place so I'm round it to three decimal place so I'm going to do going to do round well let's run this first and see round well let's run this first and see what it looks like is uh what it looks like is uh processing time and I'm going to group processing time and I'm going to group I machine uhy uhy time machine ID all right so you can see here we have uh we this is the average processing time of each machine ID and we need to um get the we have to round it to three round uh three decimal places going to round uh three decimal places going to be three be three let's run this all right run time 349 milliseconds this all right run time 349 milliseconds beats 94. 32% of users with my beats 94. 32% of users with my SQL uh so that is it for today thank you SQL uh so that is it for today thank you for watching I see you in another video for watching I see you in another video y
2024-03-20 10:19:11
1,661
https://i.ytimg.com/vi/j…axresdefault.jpg
Leetcode SQL 50 | 1661. Average Time of Process per Machine Solution
xtaeBq94YhQ
There are six things to do, look, there are a lot of questions, there is nothing to stress you, what do you have to keep in mind here, here you have to mind here, here you have to keep two most important things in mind, keep two most important things in mind, first of all, make yourself first of all, make yourself clear here. clear here. clear here. islands, exactly how many islands are there in our grate, okay, so what can we do in this, the simplest thing is that we will start it once, you can start it, you said, okay, as soon as Encounter happened on one story also, one way Encounter happened on one story also, one way Encounter happened on one story also, one way present student present student like he will encounter himself there, he will do it like he will encounter himself there, he will do it here, from there he will run one of his DFS here, from there he will run one of his DFS that yes, which lenses are connected to this one, that yes, which lenses are connected to this one, all the lenses are absolutely correct, all the lenses are absolutely correct, now you can do that. now you can do that. now you can do that. exercise date means you have to make it like how to make it, forgive him and keep it, it's okay, after that what do you have to find, after that you have to find the step of the nearest land, you have started, A little bit friends, now A little bit friends, now A little bit friends, now where will the most romantic night start that where will the most romantic night start that as soon as you got one and as soon as you got one and once up connect, all the lunches you were getting, once up connect, all the lunches you were getting, what did you do with all of them, you what did you do with all of them, you stored their pointers and then you moved their pointers. stored their pointers and then you moved their pointers. stored their pointers and then you moved their pointers. okay, think a little about it, but it will become a very easy question. Okay, those of you who have not understood this problem, there is no need to take tension. First of all, you are going to understand this Tell me what was the six, after that we will Tell me what was the six, after that we will Tell me what was the six, after that we will approach it and give the approach it and give the final bill set implementation. Look, there was final bill set implementation. Look, there was six to understand. Look, I six to understand. Look, I said my question, okay now example one and what you are is said my question, okay now example one and what you are is very simple, I am not understanding anything in it. very simple, I am not understanding anything in it. That's why we are not doing it, I That's why we are not doing it, I said in an attempt to understand, okay, said in an attempt to understand, okay, here is a matrix of life, here is a matrix of life, what should we do in this matrix, what should we do in this matrix, try to understand carefully, the try to understand carefully, the one in this matrix is ​​representing it. one in this matrix is ​​representing it. one in this matrix is ​​representing it. you say land, then what is this, what should you say? If this land is in its four directions, that means it is the land, its upset side, left side, right side, if there is any other land in its four directions, That they are connected to each other, That they are connected to each other, That they are connected to each other, so it was to the right of this, okay, so so it was to the right of this, okay, so what has become of this saree of sarees, as what has become of this saree of sarees, as well as this is also connected to this, said well as this is also connected to this, said yes, whenever you are absolutely right, along yes, whenever you are absolutely right, along with that, this is also connected to this. with that, this is also connected to this. with that, this is also connected to this. matter of Jabal itself and it is also connected to it. JB, it is absolutely correct, it is correct, yes, now this entire land is connected to each other, which means that the land is made like this and what is the water in it in between? Okay, there should not be any doubt in this, now there is water in the middle, in the middle of that there is one more land built here, this land here is another one built here, now it was not necessary here that you It is possible that it is made up of only one line, if it is It is possible that it is made up of only one line, if it is It is possible that it is made up of only one line, if it is like this, then actually it must like this, then actually it must be connected. If there is one line here also, be connected. If there is one line here also, suggest what happens to this land, if it is suggest what happens to this land, if it is connected, then this land will connected, then this land will become something like this. absolutely correct, now absolutely correct, now what was given to Apna in the question that what was given to Apna in the question that whatever matrix life Apna will have, there will always be two whatever matrix life Apna will have, there will always be two different land lives along with the hobby Apna different land lives along with the hobby Apna has, this much was already given in the question that has, this much was already given in the question that in this in this in this okay, these are separate lands of ours, life will always be there, so one line is this and one land is ours, okay, and there will always be only two, sometimes we will be more than friends, and Now Now Now what you have to do is you have to make a simple form, you have to turn that what you have to do is you have to make a simple form, you have to turn that this land and this this land and this land, if you land, if you want to connect these two, then want to connect these two, then what is the minimum number of lands? what is the minimum number of lands? what is the minimum number of lands? insert in the middle. Now what does it mean for the lands to come in the middle of all these, what will you have to do by flipping the 0, like if you flip this zero and make your band, then what happened is that these are also connected together, even Do this to zero or do it to zero or do it to Do this to zero or do it to zero or do it to Do this to zero or do it to zero or do it to zero, read it to anyone, what will happen in zero, read it to anyone, what will happen in this way, I used to have answers from every side, there was this way, I used to have answers from every side, there was only one A, then that one of mine is gone, only one A, then that one of mine is gone, now let's just accept this now let's just accept this land of ours. land of ours. land of ours. happens here and yes, just join it like this, this is your last one, it is zero and this is also yours, propose it, it zero and this is also yours, propose it, it is okay and this is also your zero, is okay and this is also your zero, one line. one line. one line. said that he has got one land here, it is absolutely correct, he has two lands How many flips will have to be done, how many flips will have to be done, he said, How many flips will have to be done, how many flips will have to be done, he said, okay, it is absolutely correct, so let's see, to okay, it is absolutely correct, so let's see, to reach here, you reach here, you may have a method that if you may have a method that if you reach from here, then to reach from here, you will reach from here, then to reach from here, you will only have to do one and one or two. only have to do one and one or two. only have to do one and one or two. one, you have option A, and one, if you go from here, you will have to flip your three, one, three and two, everything is tight, it is absolutely If you If you If you feel like it, then you will have to do this also, give me this, then tell me to you, feel like it, then you will have to do this also, give me this, then tell me to you, now there is now there is no less story than that, what is happening at this no less story than that, what is happening at this point of time pass, you are understanding that we were giving point of time pass, you are understanding that we were giving different answers from here, we different answers from here, we saw it from here. saw it from here. saw it from here. here, we have seen three A's. Then what will we do? Two means the minimum answer, whatever is our answer, we will always return it. A simple thing should be clear now the Understanding of the question becomes clear here Understanding of the question becomes clear here Understanding of the question becomes clear here below and still there is any diet then the below and still there is any diet then the answer is given by watching the one minute video once. answer is given by watching the one minute video once. Understanding of the question is very Understanding of the question is very important and still I have doubt important and still I have doubt then the version which is written in the comment box is ok then the version which is written in the comment box is ok now. now. now. no doubt in the question, so how will you approach it, now you will have to do it simply, here you have a grid, it is matrix form, that is, you have 2d It's a matter, there is It's a matter, there is It's a matter, there is nothing else, okay, now I nothing else, okay, now I can do what is found in today's matrix, I can do what is found in today's matrix, I said, yes, I put a loop, said, yes, I put a loop, put another four's look inside it, you put another four's look inside it, you can travel on the entire matrix, it is can travel on the entire matrix, it is not a matter of phone, okay not a matter of phone, okay not a matter of phone, okay started Matrix and I got the land on the story once, I got the line on the story once, I said, it is a simple thing, there should be no doubt in it, it is a simple thing, there is This is the place where I will This is the place where I will This is the place where I will get my first time line, I am there, the tower is here, get my first time line, I am there, the tower is here, now as if I got the land, I now as if I got the land, I did five here, now how can I forgive this, am I did five here, now how can I forgive this, am I marking it as minus one marking it as minus one because I have this line now What I'm going to do is I'm going to go to all the lands on the connector and I'll talk to you guys. Okay, so I marked mine here, mine one here, -1 here, -1 here and y7, I marked mine It is said that wherever there is It is said that wherever there is It is said that wherever there is one connection, it is okay, wherever the one connection, it is okay, wherever the direction is coming, direct connection has been given, direction is coming, direct connection has been given, we have marked all of us as minus one - we have marked all of us as minus one - What is the reason for marking 1 - What is the reason for marking 1 - Some reasons for marking 1, this is a simple reason that our Some reasons for marking 1, this is a simple reason that our Some reasons for marking 1, this is a simple reason that our install here that Apna has already been visited, now there could have been many methods for this, either what Apna does is that Apna creates another matrix, okay and any other Why can't you do anything in this, just keep in mind that you have already been visited, so apart from zero and one, you will have to make some marks there or if you do not want markers then what else will you do? Make a matrix and store inside it that you have visited this position, what did you do, wherever you visited, were you completing one line, were you completing all your places, what will you do at this point of Now it is very simple, Now it is very simple, Now it is very simple, what will we do that this one is minus one, what will we do that this one is minus one, okay, first we will see from here that okay, first we will see from here that if our one step story if our one step story goes in any direction from here, okay then goes in any direction from here, okay then what should be the direction, Shakti is upset what should be the direction, Shakti is upset left. left. left. one direction from all four directions, Shakti said, it is absolutely correct, it was not possible to go to its website, so please check yourself, it is not possible to go to your side, it is not possible to go to the left No, there is a bunny on the right side, so No, there is a bunny on the right side, so No, there is a bunny on the right side, so leave the right one too. leave the right one too. What is there on the right side? This one is okay, What is there on the right side? This one is okay, leave this one too, so you leave this one too, so you can't even go to this point, leave this one, then I was making The line was that they all do The line was that they all do The line was that they all do n't know what all has been given now because they were n't know what all has been given now because they were not going to tell their story from this position so not going to tell their story from this position so why will they remove it from it then why will they remove it from it then because this position is of high quality, because this position is of high quality, what happened in this position, what happened in this position, you saw it. you saw it. you saw it. Vanita is not there. This is not possible on the right side. Vanita will not go. There is zero on the Dr side. Here, Apna can, what will we do? From here, we are trying to reach Apna second line. He said, it is absolutely correct, so you could have He said, it is absolutely correct, so you could have He said, it is absolutely correct, so you could have reached on the second line and now you have reached here in the first step. Also first step Also first step here you were coming, I am fine then here here you were coming, I am fine then here you have done mines one, in this also here you were you have done mines one, in this also here you were coming, you will take out from every condition that coming, you will take out from every condition that if you move forward one step in every condition, if you move forward one step in every condition, then how far will you reach. then how far will you reach. then how far will you reach. reached among all the heroes, it is true that you will take one more step forward, as soon as you reach the second step, as soon as you reach the second step, now look, you have got 1. He said, yes brother, you reach the second step, if you have got one, then your number is How big do you have, what will you do, you will make the mines one, it means that it is absolutely right, it will become your answer, once you have tried it a little, what you do is that you remove these minds, where you get one. where you get one. where you get one. do? From there, I took out all the connections of the land. Okay, I took out all these connections. I stored all the positions of these connections, there Said, yes brother, it is clear, then Said, yes brother, it is clear, then Said, yes brother, it is clear, then what did you do after that, from this forest, you what did you do after that, from this forest, you saw that there is no present on the left, now there saw that there is no present on the left, now there is no present on the side, you will is no present on the side, you will not take the right side, then you came to this forest, not take the right side, then you came to this forest, ahead of this forest, you made yourself in this position. ahead of this forest, you made yourself in this position. ahead of this forest, you made yourself in this position. forgiven all these settings, then what did you do, go back one more step, now one more like this, when you move ahead from here, you turned around when you reach here, if you If we If we If we move forward from here, we will reach here. If we move forward from here, we will reach here. But if we move forward from here, if we move we move forward from here, we will reach here. But if we move forward from here, if we move forward from here, if we read this, then we are forward from here, if we read this, then we are reaching straight. If we move forward from here, we will reach straight. reaching straight. If we move forward from here, we will reach straight. This one is correct. This one is correct. This one is correct. now just tell your total number of steps, no matter how many steps, three steps too, what will we say out of three steps, one step - do it, because in that you have already done 5. Said, it is absolutely correct, then how many steps back has the number of steps You also had to do your turn. It's a You also had to do your turn. It's a You also had to do your turn. It's a simple thing. It's very simple thing. It's very easy in MP. Look, come here, this was easy in MP. Look, come here, this was my function which had to be built. I have come my function which had to be built. I have come here, what have I made, here, what have I made, why have I made mine? why have I made mine? why have I made mine? but what all should I list? Firstly, restore your weight, that is, you had said that on the point of time, you will store it, you will you will solve all the positions of Arun Saare, you will solve all the positions of Arun Saare, absolutely correct. absolutely correct. absolutely correct. made it a variable, what will you store in the open middle, the punishment in this is the total number of Stephanie in the stored it, okay once more, what is stored it, okay once more, what is important here is that the important here is that the grid you have is always there. grid you have is always there. grid you have is always there. meaning N will be found in cross N only. Okay, her number of days and number of following are sufficient. She is that girl. Okay, tell me, if the numbers of days and columns are different, would you have changed your approach? Did you There is There is There is no video friends in hoti approach, ok, it is a no video friends in hoti approach, ok, it is a simple thing, then what have you simple thing, then what have you made, ok, true, what is true, what is this, what should I made, ok, true, what is true, what is this, what should I tell you here, tell you here, understand this carefully, what did you say, I did Apna Apna Apna Supose Variety, then Apun will come to the other. Apna Supose Variety, then Apun will come to the other. Apna wants this, he trades on Puri Matrix, it wants this, he trades on Puri Matrix, it is absolutely right, now is absolutely right, now what will happen here, as if Apna got it, okay propose, Apna will come what will happen here, as if Apna got it, okay propose, Apna will come here, then let's meet, then here, then let's meet, then what would Apna wish that you ever do? what would Apna wish that you ever do? what would Apna wish that you ever do? said that it is absolutely correct, how will you know from the look of this phone that if you do not do any research on it then have you made cake woolen true there then have you taken it as true that you have not found it yet then right You are giving him till then, he said, okay, You are giving him till then, he said, okay, You are giving him till then, he said, okay, so let's so let's go, what did you say that right now go, what did you say that right now what is your number of followers, keep attracting them, what is your number of followers, keep attracting them, within that, how much number of followers within that, how much number of followers keep retrieving on them and you also keep retrieving on them and you also check yourself whether the great one. check yourself whether the great one. check yourself whether the great one. connect all the lenses and once the point condition like condition like land once, okay yes brother, do this, it is land once, okay yes brother, do this, it is clear in this. clear in this. clear in this. now let's understand what we are doing in this VFX function. It was our quality affairs function. The first thing in this is the pen. What did you say that just now our pen and pen have come and And what is the position of the one who has come? Is his And what is the position of the one who has come? Is his And what is the position of the one who has come? Is his position completely correct? Yes, on the position, Apna position completely correct? Yes, on the position, Apna told him it is okay, so I have come and sent the position to his told him it is okay, so I have come and sent the position to his position, why did he send it? What is the what are you doing in the position, that Apna Jo is crying, what are you doing in the position, that Apna Jo is crying, 10 scope. 10 scope. 10 scope. not work out of scope or it is not ready because what you said is that it is already connected, how will we do both of these, what will we is already connected, how will we do both of these, what will we do and will we return it, it is absolutely correct that do and will we return it, it is absolutely correct that you have considered this condition here. you have considered this condition here. you have considered this condition here. could have written also, I have written below, not that one, it is fine, what happened after that, I came to know that now I am not at zero, I am out of my scope, I am guested, what would mean that it is So, if he is land connected then So, if he is land connected then So, if he is land connected then what will you say that why would I what will you say that why would I push him? They had already discussed his position with this cheese, they are push him? They had already discussed his position with this cheese, they are talking to him talking to him and what have you done, marked him as guest, made him minus one, tell me. him minus one, tell me. him minus one, tell me. absolutely correct, then what did you do with the DFS function, meaning, with this, you changed the function back to yesterday, now once you have minus one from your, that means R is representing, wait -1, what does it mean, you have I told you that you I told you that you I told you that you can go in this direction. I went to check the upper direction. I went to check the can go in this direction. I went to check the upper direction. I went to check the lower direction. Once I went to check what happened to me, I went to the left to check check what happened to me, I went to the left to check what I did. I went to check what I did to the right. I wrote what I did. I went to check what I did to the right. I wrote plus one in the pen and said. plus one in the pen and said. plus one in the pen and said. so now I am understanding the condition here that I had to put myself because as soon as I had automatically got 1 on the first position, I said, it is absolutely correct and now will you go to check above It is possible to go above D, so if it is not that then it will go It is possible to go above D, so if it is not that then it will go It is possible to go above D, so if it is not that then it will go out of D of the matrix. It is out of D of the matrix. It is not going much, isn't it? Okay, not going much, isn't it? Okay, if this phone is going out of D, then if this phone is going out of D, then what will we do with it? The entire connection of one land has been taken out. Now what you have to do is you have to move one step forward from all the connections you have in the line and first of all check yourself, whatever you Well, Well, Well, now one more thing is important, now one more thing is important, why are the elders looking at the steps, look at the steps, you why are the elders looking at the steps, look at the steps, you will do everything as your own, will do everything as your own, then it is not necessary, is there a minimum then it is not necessary, is there a minimum in this, can there be a minimum from this, in this, can there be a minimum from this, can there be a minimum, what will everyone do? can there be a minimum, what will everyone do? First of all we will teach each step one by one and then we will First of all we will teach each step one by one and then we will see if the fan has reached there and if it has see if the fan has reached there and if it has not reached then we will give one more step to all the steps, then as the not reached then we will give one more step to all the steps, then as the total increases to four steps, it is total increases to four steps, it is absolutely correct, then on the third step we will absolutely correct, then on the third step we will bring this type till bring this type till What will we do till we reach our mother, we will What will we do till we reach our mother, we will move one step at a time, but everyone said yes, when move one step at a time, but everyone said yes, when it is clear, then you come to your place, it is clear, then you come to your place, till whatever is yours becomes empty, till whatever is yours becomes empty, then keep moving, he said, ok. then keep moving, he said, ok. then keep moving, he said, ok. then what did Apna say because perhaps Apna has taken it and made the answer plus plus. What does it mean to make the answer plus that the one who took one step forward said this is absolutely correct, meaning Apna Why did he know that all his people were going to run Why did he know that all his people were going to run Why did he know that all his people were going to run low, there should be no problem, low, there should be no problem, then what did he do so that he would take the up and when his own third position up and when his own third position and his also in third position? and his also in third position? and his also in third position? what will you do, you will move to the side but there should not be any doubt, then what did you do to become, on top of this, on top of S, S means all of them, as many as possible, from there on all the steps. What did you say to run it? I said it's okay so whatever it is, first of all take the ITM because it is in the front and pop it. First of all it is absolutely correct. It has two values and what is there in the second part of the ID. So your What did you do to represent him from the current foreign, it is absolutely right, now your tax condition is possible from there, you side dr side website right will not work then what did you do, inside him there are not work then what did you do, inside him there are two interiors - NC and Nar said ok two interiors - NC and Nar said ok what in Nar what in Nar What will happen in the e-mail of your new robot? If there will be a new pen, then the new What will happen in the e-mail of your new robot? If there will be a new pen, then the new Nokia Current Plus will automatically check all the conditions Nokia Current Plus will automatically check all the conditions which I which I told you about the UPSIDC Dr. Set i.e. told you about the UPSIDC Dr. Set i.e. conditions, then I checked the story of conditions, then I checked the story of this. this. this. spoke or she has not gone, if she has not gone out from now on, then what did you say that if yours is zero, then what will yours do? If zero comes, when will you Will do this and will also Will do this and will also Will do this and will also mark 0. One of the mines means that its own has been mark 0. One of the mines means that its own has been selected, that is fine. There selected, that is fine. There five will mark only one. Now what will we do five will mark only one. Now what will we do here, we will talk about zero. This here, we will talk about zero. This is absolutely correct and if our is absolutely correct and if our zero is zero is zero is what condition can it come in, either it is -1 or it will become, he said, okay, when will -1 come, then I checked whether the minus is one or it is one, then checked the specification here. said, it is absolutely correct, then said, it is absolutely correct, then Apna started one, so here Apna time Apna started one, so here Apna time blaksiti talk, Apna first blaksiti talk, Apna first look at the space, is it six or Paneer total, look at the space, is it six or Paneer total, how many spaces do it have, then how many spaces do it have, then see Apna space. see Apna space. see Apna space. was no space of our own in it, everything is constant over there, it is happening here, why in making our items, worship is also the power, oh, so what will we say, how much of our space has become, If you are If you are If you are running and v2, then it is correct that N* is smaller than N because even if the number of columns is A, there cannot be any more. Said, it is absolutely correct, then it would understood it. Thank you, thank you [
2024-03-25 11:42:44
934
https://i.ytimg.com/vi/x…axresdefault.jpg
934 || Shortest Bridge || C++ || Leetcode Daily Challenge
n2NKKu-o7AM
welcome to september's leco challenge the last question of the month the last question of the month today's problem is first missing today's problem is first missing positive given an positive given an unsorted integer array find the smallest unsorted integer array find the smallest missing positive integer missing positive integer example one two zero the smallest example one two zero the smallest positive integer would be three positive integer would be three example three four minus one one the example three four minus one one the smallest positive integer would be two smallest positive integer would be two and the example seven eight nine eleven and the example seven eight nine eleven twelve the smallest positive integer twelve the smallest positive integer would be one would be one now they want our algorithm to run in now they want our algorithm to run in oven time and use oven time and use constant space so that's going to be constant space so that's going to be tricky but let's initially start with tricky but let's initially start with how we might just solve this brute force how we might just solve this brute force well we might think well we can sort well we might think well we can sort this array and this array and check to see which is going to be the check to see which is going to be the not not the increasing by one positive integer the increasing by one positive integer or something like that but that's or something like that but that's not very efficient let's think about how not very efficient let's think about how could we do that could we do that um using extra space instead one of the um using extra space instead one of the ways you can do that is by having some ways you can do that is by having some sort of set sort of set that's going to keep track of what we've that's going to keep track of what we've seen so far so we'll have seen so far so we'll have a set called scene and what we'll do a set called scene and what we'll do is set our output as one at first is set our output as one at first because that's going to be the minimum because that's going to be the minimum positive integer possible positive integer possible and we'll say 4n and nums we'll add it and we'll say 4n and nums we'll add it to our scene set to our scene set and while output is still in scene and doing this is actually going to and doing this is actually going to return the right answer return the right answer and it's actually quite fast and it's actually quite fast surprisingly but surprisingly but is this o of n time and technically is this o of n time and technically it's not right because it's o n here but it's not right because it's o n here but we'll have this while loop we'll have this while loop being multiplied by however many numbers being multiplied by however many numbers that we might have would be the range of that we might have would be the range of o of n so it ends up being like o of n so it ends up being like basically n basically n squared so how could we do better squared so how could we do better well let's think about like if we had well let's think about like if we had an array like this one two three four an array like this one two three four one things you might notice pretty one things you might notice pretty quickly is quickly is our minimum positive integer will be in our minimum positive integer will be in between the range of one between the range of one all the way to n plus one inclusive all the way to n plus one inclusive and the reason for that is this is kind and the reason for that is this is kind of the maximum posit like of the maximum posit like numbers that we could have right so here numbers that we could have right so here the exam the answer would be the exam the answer would be five and that would be indeed four plus five and that would be indeed four plus one that would be five one that would be five now it doesn't matter what the numbers now it doesn't matter what the numbers in here are if they're like negative in here are if they're like negative 3 40. regardless the number 3 40. regardless the number for the least positive integer has to be for the least positive integer has to be within this range within this range here the answer would be 3 and that here the answer would be 3 and that indeed is still in between indeed is still in between one and n plus one so how can we use one and n plus one so how can we use this knowledge to take advantage of this knowledge to take advantage of um going through our array just one time um going through our array just one time to figure out to figure out what is the minimum positive integer and what is the minimum positive integer and we could do that by having some sort of we could do that by having some sort of array array that's going to be represented by all that's going to be represented by all zeros at first zeros at first and each one of these indexes is going and each one of these indexes is going to represent a number to represent a number it'll be like one two three four and we it'll be like one two three four and we actually need one more actually need one more for five and what we'll do is go through for five and what we'll do is go through our array and just our array and just mark these if we've seen them before so mark these if we've seen them before so we've seen one so we'll mark it we've seen one so we'll mark it scene two we've marked it negative three scene two we've marked it negative three i mean the negative i mean the negative negatives and numbers out of this range negatives and numbers out of this range don't matter so we don't care about don't matter so we don't care about those those and then we just go through our array and then we just go through our array and say oh three is our minimum one so and say oh three is our minimum one so the answer is three the answer is three so we can do that and that would be o so we can do that and that would be o event time right so event time right so let's do that first we need to append let's do that first we need to append one more one more number to our nums let's make it zero number to our nums let's make it zero because because it doesn't really matter there and what it doesn't really matter there and what we'll do is initialize n we'll do is initialize n as length of nums and we'll set an array as length of nums and we'll set an array this array is going to be all 0s at this array is going to be all 0s at first for first for blank and range of n now blank and range of n now what we want to do is go through our what we want to do is go through our nums and just mark nums and just mark these this array if we've seen the these this array if we've seen the number before so number before so what we'll do is say for i and range what we'll do is say for i and range [Applause] [Applause] of n of n if the number is within this range so if if the number is within this range so if numbers that i numbers that i is what if it's greater than zero is what if it's greater than zero and less or equal to n and less or equal to n then what we'll do is take this number then what we'll do is take this number and update our array and update our array so we'll say numsai increase it now once we're finished there actually i need to subtract one here because the one is actually going to be represented by the zero index right so make sure you know that and and say if dot array.i equals zero that's going to be our minimum one so just return and let's see if this works and let's see if this works and that works now this is great this is and that works now this is great this is oven time yes we make two passes oven time yes we make two passes technically three but whatever um it's technically three but whatever um it's still oven still oven but this uses extra space right uses on but this uses extra space right uses on space so the hint here was well space so the hint here was well using this approach how could we solve using this approach how could we solve it without using extra space it without using extra space and that's difficult that is very and that's difficult that is very difficult because difficult because if we had some example like um if we had some example like um like this we might go through it like this we might go through it and keep track of like what's the and keep track of like what's the minimum number so far minimum number so far and say well one it's gonna be one here and say well one it's gonna be one here one here one here one here but once we reach one we have one here but once we reach one we have to increase it to 2 right to increase it to 2 right but unfortunately we kind of lost track but unfortunately we kind of lost track of the fact that 2 still exists of the fact that 2 still exists and unless we go back and search the and unless we go back and search the entire array again we can't figure that entire array again we can't figure that out out so you so using like just integers is so you so using like just integers is going to be using just integer variables going to be using just integer variables is gonna be really hard to like what if is gonna be really hard to like what if this was like a three here this was like a three here you know it has to go up one two three you know it has to go up one two three four five all the way up so what could we use to store that information well what about the array nums itself could we somehow tinker with that without losing information from the original nums but mark somehow that yes we've seen this number because we could use this array to mark as these representing these the range right one two three four all those numbers could be represented inside of this array but the trick is how can we make sure to keep this information of the number itself and add that it's been marked well one of the ways we can do that is we can add the length of this whole array which would be what nine and have use a modular every time we check to still keep the information of what the original number was but each time we like updated with n we can say that yes we have marked this position so if it's greater than n than we've seen this number before so we can actually use the number array itself to do this okay so knowing that that's going to make it a lot easier but the trick is it gets tricky because we want to make sure to keep that information so let's first go through our um so let me delete this let's first go through our nums and what we're going to do is first get rid of the numbers outside of our range like just make them zeros because we don't care about those what we're going to do is say all right if the nums i if it's what less than zero or nums i is greater than n then just mark it as zero because why do we care about these numbers now only numbers that are greater than now only numbers that are greater than zero zero are are [Music] [Music] are what matters here right so i should are what matters here right so i should say say within the range but basically at this within the range but basically at this point it's going to be greater than zero point it's going to be greater than zero so for i so for i and range of m we'll say if and range of m we'll say if our num is not i if it's greater than our num is not i if it's greater than zero zero then we want to mark our number itself then we want to mark our number itself using the number using the number as an index but as an index but don't lose the original information so don't lose the original information so to do that we're going to use the to do that we're going to use the modular function modular function i'll show you what i mean we'll get nums i'll show you what i mean we'll get nums num is i it has to be subtracted by 1 num is i it has to be subtracted by 1 remember remember and we're going to just add n here and we're going to just add n here and to make sure to account for like and to make sure to account for like duplicates and stuff we'll do the duplicates and stuff we'll do the modular n modular n in case we've been updating this number in case we've been updating this number multiple times multiple times so at this point these numbers that so at this point these numbers that we've seen before we've seen before we're going to get marked up and we're going to get marked up and now all we need to do is go through our now all we need to do is go through our nums again and what we'll do is say okay nums again and what we'll do is say okay look if look if nums dot i divided by n nums dot i divided by n okay if it's basically less than n okay if it's basically less than n since if we've seen it it should be since if we've seen it it should be greater than n greater than n then return the i plus one right because it's zero index then we want to return the number itself otherwise if we can get this whole thing then just return n that's going to be the so let me see if this works i forgot so let me see if this works i forgot there is one weird there is one weird edge case where the very first number edge case where the very first number the zero index should be representing the zero index should be representing one but there are cases where that one but there are cases where that number could actually be equal to n number could actually be equal to n uh so when that happens like that kind uh so when that happens like that kind of throws a little of throws a little screwball so what we'll have to do is screwball so what we'll have to do is store that as a temp variable store that as a temp variable and say all right num0 store that here and say all right num0 store that here and just check at the very end look if and just check at the very end look if nums at zero nums at zero still equals the temp meaning we haven't still equals the temp meaning we haven't touched it touched it then we know the answer is one so that's then we know the answer is one so that's just to take care of the use case just to take care of the use case um weird edge case i mean all right so um weird edge case i mean all right so let me submit that let me submit that i'm not positive i did this right looks i'm not positive i did this right looks like i did like i did great so this is all event time yes we great so this is all event time yes we passed it three times but passed it three times but we use no extra space we've just been we use no extra space we've just been updating our nums instead updating our nums instead and we got the right answer so this was and we got the right answer so this was a pretty hard one a pretty hard one i think this right here is quite i think this right here is quite brilliant if you can brilliant if you can realize that yes we can mark this realize that yes we can mark this array index uh without losing the array index uh without losing the information information this is like what's key here and this this is like what's key here and this kind of reminds me it's kind of reminds me it's like a mishmash of pigeonholing of like a mishmash of pigeonholing of of hashing there's a lot of interesting of hashing there's a lot of interesting things going on here so i definitely things going on here so i definitely recommend taking recommend taking a look into this more that's it thanks a look into this more that's it thanks for watching my channel for watching my channel and remember do not trust me i know and remember do not trust me i know nothing
2024-03-20 09:12:18
41
https://i.ytimg.com/vi/n…AM/sddefault.jpg
Leetcode - First Missing Positive (Python)
VWVv1zf30gE
hello friends today that's over reconstruct itinerary given a list of reconstruct itinerary given a list of airline tickets represented by pairs of airline tickets represented by pairs of departure in the arrival airports thrown departure in the arrival airports thrown to reconstructed the itinerary in order to reconstructed the itinerary in order all of the tickets belong to a man who all of the tickets belong to a man who departs from JFK thus the ident departs from JFK thus the ident itinerary must begin with JFK and the itinerary must begin with JFK and the problem also mentions that we need problem also mentions that we need return lexicographically smallest order return lexicographically smallest order so if there is a time let's see this so if there is a time let's see this example we first start from JFK and example we first start from JFK and there is only one ticket depart from JFK there is only one ticket depart from JFK so we go to UMUC next and then there is so we go to UMUC next and then there is also one ticket from M you see to AOH R also one ticket from M you see to AOH R so we go to this place and the we keep so we go to this place and the we keep going in the finally we go to SJC so going in the finally we go to SJC so this is so this is owning order we can this is so this is owning order we can construct from these four tickets so construct from these four tickets so there is a place and there is a there is a place and there is a directional this there is a direction so directional this there is a direction so bases this this is a directional age and bases this this is a directional age and this is a vertex so this this relation this is a vertex so this this relation can be represented by a graph and can be represented by a graph and usually we will we use agency lists and usually we will we use agency lists and in this problem we also needed to return in this problem we also needed to return Alex Cole graphically smallest order so Alex Cole graphically smallest order so we paid her use a priority queue here as we paid her use a priority queue here as there are no more lists because when we there are no more lists because when we try to get the arrival we can quickly try to get the arrival we can quickly get the lexicographic smallest string get the lexicographic smallest string okay this is the data structure okay this is the data structure and I think this problem has some and I think this problem has some similarity with the public so 2/3 EFS similarity with the public so 2/3 EFS the implementation the implementation let's first test see the visualization let's first test see the visualization listen the graph and then we try to get listen the graph and then we try to get other talk other talk topological odor from this graph so how topological odor from this graph so how to get that we go from here and we keep to get that we go from here and we keep into DFS and we put it is 7 and then we into DFS and we put it is 7 and then we put 4 in the to 0 and the 1 and the 3 so put 4 in the to 0 and the 1 and the 3 so we basically we start from one vertex we basically we start from one vertex and we keep doing DFS until there is no and we keep doing DFS until there is no other neighbor vertexes we push that to other neighbor vertexes we push that to know the into the stack and we then push know the into the stack and we then push the 4 right and then 2 and then 0 and the 4 right and then 2 and then 0 and then 1 and we keep do the DFS from the 3 then 1 and we keep do the DFS from the 3 and we put these three and five and six and we put these three and five and six and the way we try to get them and the way we try to get them topological order we pop the notes of topological order we pop the notes of thrown the stack so in this problem is thrown the stack so in this problem is the same we start from JFK and then we the same we start from JFK and then we find there is Lester there is two places find there is Lester there is two places which is ATO and the SFO and as a TL is which is ATO and the SFO and as a TL is the lexical graphical smallest so he the lexical graphical smallest so he called you ATL and at the same time we called you ATL and at the same time we cut this H which means we remove this cut this H which means we remove this know the from its list and then we'll know the from its list and then we'll keep doing DFS and then we go to JFK and keep doing DFS and then we go to JFK and we go JFK and there is only one node in we go JFK and there is only one node in this list so we caught us f o and so on this list so we caught us f o and so on so forth so forth and when we finally go to the SFO there and when we finally go to the SFO there is no other neighbors so we push this as is no other neighbors so we push this as they fall to their stack and then the they fall to their stack and then the ATL ATL and the songs of force so finally the and the songs of force so finally the result just popped the notes in order result just popped the notes in order from the stack so this is a final order from the stack so this is a final order okay so now let's write the code and I okay so now let's write the code and I say that we need the first to write the say that we need the first to write the result which is already and we need a result which is already and we need a map so this is a string and this is a map so this is a string and this is a priority cube priority cube it's a string a street new hash map and it's a string a street new hash map and we call a build across function we pass we call a build across function we pass the G into the tickets okay and we also the G into the tickets okay and we also need attack we try to construct the need attack we try to construct the result code a stack array oh sorry result code a stack array oh sorry array tech and we do the DFS will pass array tech and we do the DFS will pass their stack in the graph and the first their stack in the graph and the first is JFK finally we try to generate a is JFK finally we try to generate a result so while this stack is not empty result so while this stack is not empty we result ads as a stack pop finally we result ads as a stack pop finally we'll return this result so now we we'll return this result so now we needed to write Q function which is GFS needed to write Q function which is GFS and this place should be tagged string and this place should be tagged string ah yes stack and the map string and fry ah yes stack and the map string and fry already queue already queue try rtq string which is G and this is try rtq string which is G and this is the throne someplace from and the we the throne someplace from and the we also needed to write the Butte across also needed to write the Butte across the first parameter is map string and a the first parameter is map string and a priority queue G and this is us our priority queue G and this is us our tickets please lease three tickets so tickets please lease three tickets so for every travel or every ticket ticket for every travel or every ticket ticket ticket the first item is from which ticket the first item is from which place right travel get 0 and the 2 is place right travel get 0 and the 2 is travel get 1 so if the G does not travel get 1 so if the G does not condense from we should put the from and condense from we should put the from and put a new priority priority queue this + put a new priority priority queue this + G we get the from and the we offer to G we get the from and the we offer to just place okay so how about the FS is just place okay so how about the FS is that we needed to change the graph so we that we needed to change the graph so we first get the priority try all right first get the priority try all right priority queue stream which is arrivals priority queue stream which is arrivals arrivals new to get the from so while arrivals new to get the from so while these arrivals arrivals not equal to no these arrivals arrivals not equal to no no and the arrivals arrivals is not no and the arrivals arrivals is not empty empty we get a tattoo which is from G gets we get a tattoo which is from G gets from and we pull from the priority queue from and we pull from the priority queue and we keep doing the DFS right which is and we keep doing the DFS right which is a stack and G and another from is the a stack and G and another from is the two this is an access tower while this two this is an access tower while this they had this place had no neighbors so they had this place had no neighbors so we push the Artic to the stack we push we push the Artic to the stack we push the front to the stack okay so there the front to the stack okay so there should be finished okay but we can do a should be finished okay but we can do a little team ization and you can see the little team ization and you can see the the function of this stack is just to the function of this stack is just to change the order of the changes of older change the order of the changes of older is like a reverse order so actually we is like a reverse order so actually we can do not add the place to the end of can do not add the place to the end of the stack we can add it directly to the the stack we can add it directly to the beginning of the result so we can just beginning of the result so we can just use a linked list the holing Lister has use a linked list the holing Lister has a method of air the first link the list a method of air the first link the list so we do not need a district which has a so we do not need a district which has a pass this result and this place we can pass this result and this place we can give it eight so currently this is give it eight so currently this is linked list we could result and the linked list we could result and the result so now we just need a result result so now we just need a result at first the from so this basically is at first the from so this basically is the same function actually you can also use a release that you can add a zero into the place okay thank you for watching and the Happy New
2024-03-24 10:42:49
332
https://i.ytimg.com/vi/V…axresdefault.jpg
LeetCode 332. Reconstruct Itinerary Explanation and Solution
OEW50g03mT0
Hey hey what's up guys Nick white here I detect OD stuff on Twitch on YouTube detect OD stuff on Twitch on YouTube haven't posted in a day or two we're haven't posted in a day or two we're gonna get back on it right now check the gonna get back on it right now check the description for all my information I do description for all my information I do premium leak Oh problems on patreon and premium leak Oh problems on patreon and join my discord this is ad binary this join my discord this is ad binary this is easy problem got a lot of likes if is easy problem got a lot of likes if you don't know a binary is it's like the you don't know a binary is it's like the first thing you learn in computer first thing you learn in computer science is that there's more than one science is that there's more than one number system so we use a decimal base number system so we use a decimal base number system base 10 which is you know number system base 10 which is you know 1 2 3 4 5 6 7 8 9 so there's like 9/10 1 2 3 4 5 6 7 8 9 so there's like 9/10 you know up to 10 different numbers you know up to 10 different numbers right but for binary it's actually base right but for binary it's actually base 2 so there's 2 different numbers there's 2 so there's 2 different numbers there's 0 and then there's one that's what 0 and then there's one that's what binary is computer science binaries is binary is computer science binaries is made up a bunch of zeros and ones you made up a bunch of zeros and ones you might have heard that before but decimal might have heard that before but decimal and binary can both represent the same and binary can both represent the same thing the number 3 in decimal is thing the number 3 in decimal is equivalent to the number 1 1 1 or 11 in equivalent to the number 1 1 1 or 11 in binary and that's because this is how binary and that's because this is how binary works binary works so that the binary works binary works so that the least significant digit is worth this is least significant digit is worth this is worth a value of 1 and then it goes up worth a value of 1 and then it goes up its exponents it's a exponents of 2 so its exponents it's a exponents of 2 so then this is worth 2 then this is worth then this is worth 2 then this is worth 4 then this is worth 8 then 16 32 64 etc 4 then this is worth 8 then 16 32 64 etc so least significant digit is worth 1 so least significant digit is worth 1 and then it goes up by exponents of 2 and then it goes up by exponents of 2 each time you go to the left so this is each time you go to the left so this is the idea here what we want to do is the idea here what we want to do is given 2 binary strings so we're given given 2 binary strings so we're given two strings that represent binary two strings that represent binary numbers then return there some so also a binary string so we want to return the sum as a binary string the input strings are both non empty and contain characters 1 or 0 okay so they're not and there's no empty strings either so let's see for the example what we're dealing with here so this like I said at least there's only one digit so it's the least significant so this represents one it's just one this represents three because it's one plus two when it's a one in that place so yeah when it's a when it's a zero it still means zero but when it's a one it counts as that factor of two so this counts as one if this was the number it would still be 1 but this is 3 because this counts as 2 in that case ok so this is you know 2 plus 1 which is 3 plus 1 which is 4 so you can't represent 4 with just 2 characters so we need another character and so we have a 0 here 0 in the ones place here on the twos place and then one in the forest place so it's 4 there you go so you might notice and then you can go through this example if you want to but you might notice that the way that we want to do these in almost when you're doing all these number problems are adding numbers of strings or there's actually a lot if you didn't notice but um you want to start in addition especially you're starting at the least significant digit when you do addition if you're doing addition just on paper if you're doing like 436 you know plus whatever plus you know 49 you're gonna start and you're gonna do 9 plus 6 you're gonna carry the 1 and then you're gonna do 4 plus 3 plus that 1 and etc and you're gonna fill out the number from least significant digit to most significant digit and that's what we're gonna do here so we're gonna go backwards we're gonna check ok 1 plus 1 and we're gonna say ok if it's greater it only goes up to 1 so if it's 1 to ones then we're gonna have to that's going to be a 0 and then we carry the 1 over and then it's 1 and 1 again and that's a 0 and we carry the 1 over and that's how we get 100 so to do this we need a stringbuilder because we're doing this in Java and that's how you construct strings so let's just start writing that out I'm gonna do string builder SB equals new string builder it's just a class we're gonna loop backwards so we're gonna set our indexes for each of the strings so we'll say I is equal to a dot length i's gonna be the pointer and each character and the a string going backwards so a dot length minus one in that J is gonna be the pointer in these going through the B string backwards so we set it to the last character of each index we're gonna initialize a variable called carry this is going to handle when we add a 1 and a 1 we want 1 plus 1 is 0 it's gonna be 2 but we carry we turn it into a 0 and we carry the 1 because there is no 2 in binary so what we're gonna do is we're gonna have this while loop will say while I is greater than or equal to 0 we're gonna go backwards like I said through the string or j is greater than equals 0 and we do or because we want to traverse them both completely we don't want to break when one of them is finished right if we're doing like I said 436 plus 49 you know you do the addition you do the addition but you even if there's no number if this was a and this was B even if there's no numbers left here you keep traversing because you want to add up this you know with nothing so that's it we for the rest of this will set our sum equal to carry and then what we're gonna do is we're going to calculate the current sum of the two digits that we're looking at so sum will be plus equal to the current character we're looking at an A which I is the pointer so a dot char I minus the character 0 to get the value 1 minus 0 is 1 0 minus 0 is 0 so this is gonna give us the value either way but what it's doing is converting a character to a number here so this is the idea we're gonna do some plus equals B char at J minus 0 and then what we're gonna do is if there we're gonna do SB dot append some mod to so why do we do this why do we append a the modulus well if if both of the current characters were looking at like in these strings so we look at this example if both of these should do this to make it more even so we're doing the addition between 1 and 1 it's 2 so we carry the 1 and turn this into a 0 so what we're doing is if they're both 1 then sub mod 2 will be 0 so we append a zero for that particular index we're looking at which is right because we want to turn this into a 0 and then we want to set carry equal to sum divided by 2 and what this is going to do is it is going to tell us if it was 2 so if it's 1 + 1 - 2 divided by 2 is 1 so we carry a 1 which is exactly what we want to do right in our output string when we compare the last characters and it's 1 and 1 we will say okay we add the sum so we add some one we had some now we have to sum sum mod 2 to mod 2 is 0 so we append a zero to the string and then we carry the one over to our next addition and that's exactly the strategy that we want to do here so that's what we're doing we set the carry also you have to decrement your point pointers each time always got to do that and at the end of this the only thing that we have to worry about is append is actually going forward so for the next edition so we carried the 1 right now we have to add the ones again and we get 1 plus 1 is 2 again so we carry the 1 again and we got another 0 but we're appending it like this and then the last addition is 1 so what's happening is this is our answer but it's backwards so we want a hundred but it's 0 0 1 because append puts things at the end there's not string builder dot put to the front so what we actually have to do is we have to when we return we have to do SB dot reverse dot two string so that's the whole thing and the other thing is if there's a carry left over at the end of this loop we want to add it at the end so we can do if carry is not equal to zero then we can just append that to our string sb depend carry so this should be good the only thing that you might want to do is if one string ends before the other like I could finish before J you want to make sure you're not gonna try and keep adding the current character because it'll be index out of bounds so actually you want to add conditions here to make sure that we're still equal you want to say okay if I is equal greater than or equal to zero and zero just to ensure because one of them will finish first Kenza since it's an order condition so this should be fine I would assume there we go so that's the whole idea it's kind of just scanning through both of the strings and doing the addition little binary calculations if you don't understand maybe lookup binary a little bit more I tried to explain it pretty well but um I think I did pretty good let me know in the comments if you don't understand anything but yeah good solution pretty quick good problem and thank you guys for watching I really appreciate anyone to watch the videos and supports me I love you guys and I will see you in the next video All Right
2024-03-20 11:09:44
67
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 67. Add Binary Solution Explained - Java
Hc54O-T3WEY
hey welcome guys so that song is one zero five one high checker so school is zero five one high checker so school is trying to end your photo of all students trying to end your photo of all students right so you have a photo a student i'll right so you have a photo a student i'll ask the standard single file a line of ask the standard single file a line of non-decreasing order for non-decreasing non-decreasing order for non-decreasing okay okay now this probabilities is probably now this probabilities is probably important but uh important but uh okay so you're giving a very highs okay so you're giving a very highs represent the current order represent the current order extend in and whatever and then you need extend in and whatever and then you need to return a number of indices which they to return a number of indices which they do not miss do not mismatch so this is do not miss do not mismatch so this is expected expected okay so one one four two one three if okay so one one four two one three if you sort it you get one one one two you sort it you get one one one two three four so you get a mismatch there three four so you get a mismatch there are three mismatch are three mismatch and for this one everything is and for this one everything is mismatched so you get five mismatched so you get five and for this one it's not mismatched and for this one it's not mismatched everyone's perfect everyone's perfect okay so uh the very simple ways to just okay so uh the very simple ways to just sort it is expect sorted it's original sort it is expect sorted it's original height and it goes through the array height and it goes through the array right and again right and again okay so this will be unloaded right okay so this will be unloaded right because uh you use the sorting so because uh you use the sorting so unknown unknown but you see you can see this problem is but you see you can see this problem is basically only 100 right so the standard basically only 100 right so the standard approach approach uh when this is very small you can use a uh when this is very small you can use a counting sort right you can use a counting sort right you can use a counting sort okay so counting so it's very easy you define h to be zero to be one hundred zero and one because i mean you have one i mean and you start from the heights and uh you count how many uh different heights with the same height so for example there will be three one and a one two one three one four now we need initialize the answer right and you basically you go through it and then you just check you just get a you just sort it right so after these parts your answer will be well released your answer will be expected right so this one is answer will be expected so this is just the standard counting okay so now uh you compute the length okay so now uh you compute the length and uh and uh define the answer to be zero and go define the answer to be zero and go through each one by one so this is through each one by one so this is linear time linear time uh it should be m plus 101 so it's uh it should be m plus 101 so it's linear time and uh check where they are linear time and uh check where they are if there are difference then you add one if there are difference then you add one right so basically it is just the right so basically it is just the counting sort counting sort okay very simple
2024-03-25 16:21:16
1,051
https://i.ytimg.com/vi_w…Y/sddefault.webp
Leetcode 1051 Height Checker
IaoaxyJUJFI
let's solve sine of the products of an array so we have a function it's called array so we have a function it's called array sign it has a parameter which is a array sign it has a parameter which is a vector of integers by reference it's vector of integers by reference it's called nums and we have to find the called nums and we have to find the products of all the values in the array products of all the values in the array and determine the sign of the results so and determine the sign of the results so if the result is positive that is the if the result is positive that is the products of all the values if it's products of all the values if it's positive then we have to return 1. positive then we have to return 1. otherwise if it's negative we have to otherwise if it's negative we have to return negative one in any other case return negative one in any other case it's zero so we have to return 0. first it's zero so we have to return 0. first I have a result variable you can use a I have a result variable you can use a long long type if you intend to get the long long type if you intend to get the actual products of all the values but actual products of all the values but then again it's a bit risky because if then again it's a bit risky because if you look at the constraints here the you look at the constraints here the values range from negative 100 all the values range from negative 100 all the way to positive 100 and we have anywhere way to positive 100 and we have anywhere between 1 and 1000 values so it's likely between 1 and 1000 values so it's likely that you're going to run into an integer that you're going to run into an integer overflow meaning that the value is going overflow meaning that the value is going to be too large to be stored in any kind to be too large to be stored in any kind of integer in this case it's simply of integer in this case it's simply better if I change this to a short better if I change this to a short integer to store A1 and then I change my integer to store A1 and then I change my Approach so I'm not actually going to Approach so I'm not actually going to find the products of all the values but find the products of all the values but instead I'm going to concentrate on the instead I'm going to concentrate on the sign of the results and to do this I can sign of the results and to do this I can actually substitute the values in this actually substitute the values in this for Loop here you can see what I'm doing for Loop here you can see what I'm doing Lane to avoid integer overflow I'm Lane to avoid integer overflow I'm substituting all the values with a 1 a 0 substituting all the values with a 1 a 0 or a negative one so if the value in my or a negative one so if the value in my array at index I is a positive value I'm array at index I is a positive value I'm just going to multiply my results by one just going to multiply my results by one if it's a negative value I'm going to if it's a negative value I'm going to multiply my results by negative 1. in multiply my results by negative 1. in any other case I multiply by zero now I any other case I multiply by zero now I can focus on the sign of the results by can focus on the sign of the results by having this conditional statement here having this conditional statement here if the value is greater than 0 then I've if the value is greater than 0 then I've written one otherwise if it's negative I written one otherwise if it's negative I return negative one in any other case we return negative one in any other case we return is zero so this matches the return is zero so this matches the conditions that they have here and it conditions that they have here and it also prevents this solution from running also prevents this solution from running into any form of issues such as an into any form of issues such as an integer overflow so let me run this we pass the three sample test cases you can see what they look like here we have very small values same thing for here and here as well I'm sure that if you check the other values in here you can check with very large numbers and this code should still be fine so let me submit this now so that we can check and we've passed everything without any and we've passed everything without any issue so that's it for this lead code issue so that's it for this lead code coding challenge it's called sign of the coding challenge it's called sign of the products of an array if you like my C products of an array if you like my C plus Solutions Please Subscribe and I'll plus Solutions Please Subscribe and I'll see you next time
2024-03-22 17:40:24
1,822
https://i.ytimg.com/vi_w…xresdefault.webp
Sign of the Product of an Array - LeetCode 1822 Solution in C++ (LeetCode Math)
ob1VPzu_rXs
welcome to my channel doctor today we welcome to my channel doctor today we are going to solve a problem called are going to solve a problem called square root of x square root of x so the main intention is to understand so the main intention is to understand what are the intuition what are the intuition behind this problem so behind this problem so when somebody asks you sk find the when somebody asks you sk find the square root of x or find the cube root square root of x or find the cube root of x of x or find the power of x there is a common or find the power of x there is a common algorithm or you can say it's common algorithm or you can say it's common cracks cracks or the problem is same or the problem is same so we need to implement a square root so we need to implement a square root and we have given input integer as x and we have given input integer as x and given output should return type and given output should return type should also be integer should also be integer okay so what does that mean if you have okay so what does that mean if you have 8 8 the square root of 8 is 2.82 so we are the square root of 8 is 2.82 so we are only interested in integer part of it only interested in integer part of it square root of 4 is 2. square root of 4 is 2. so yeah that's the problem is now so yeah that's the problem is now take an example as 16. take an example as 16. so you need to find the square root of so you need to find the square root of 16 which is actually 4. 16 which is actually 4. so let's say you have numbers like 1 so let's say you have numbers like 1 2 3 then 8 2 3 then 8 9 and then 16 9 and then 16 right so we can use something called right so we can use something called binary search approach here binary search approach here we look for the middle element so when we look for the middle element so when we see it we see it now 8 is the middle element of now 8 is the middle element of a range of number from 16 a range of number from 16 so 8 square it so 8 square it square is actually greater than 16 square is actually greater than 16 right that means we can we cannot find right that means we can we cannot find a square root of 16 on the right side of a square root of 16 on the right side of it it we can always find on the left side of we can always find on the left side of it it so in that case the next so in that case the next numbers will look for this range numbers will look for this range now next we will look for mid which is 4 now next we will look for mid which is 4 and the 4 square is equals to 16 right and the 4 square is equals to 16 right here we can return four so that's the basically uh binary search approach you look for the middle element and just square it and compare with the given input if it is equals to the x then you can return the value otherwise you check if it is greater than or if it is less than if you say if it is less than bit square value is less than value of x then you look for the right side of it and you need to store uh you need to store your output when you go for a right side so you uh let me just walk through it so the base case will be if the x value is 0 or x value is 1 then we can just written x then we can start value we can have n value now in binary search we do something like this we have a start and end now we try to find the mid value which is divide by 2 we can find the mid square divide by 2 we can find the mid square which is mid multiply mid then we check if the mid square is equals to equals to given value then we can just return bit but if this mid square value is less than x then our start will become mid plus one and we can store the answer value estimate else that's it so you can see that's it so you can see for the case of eight if you have eight for the case of eight if you have eight then let's say you have one two then let's say you have one two you go up to four and then you go to you go up to four and then you go to eight eight so first you check for four now four so first you check for four now four square is actually greater than eight square is actually greater than eight you look for the you look for the left half then you have number this left half then you have number this so we can say one two three so we can say one two three four now the middle element four now the middle element is let's say 2 the 2 square is let's say 2 the 2 square is 2 squared is 4 which is less is 2 squared is 4 which is less right so look for the right so that is right so look for the right so that is you look for only you look for only 3 and 4 but you already stored answer 3 and 4 but you already stored answer here here the answer value is 2 now the mid square the answer value is 2 now the mid square is 3 square which is greater than that is 3 square which is greater than that so you just stop it there the recursion so you just stop it there the recursion will get stopped will get stopped not the recursion just the while loop not the recursion just the while loop will get stopped so will get stopped so the time complexity will be log of the time complexity will be log of n because every time we uh n because every time we uh reduce our domain or the range of input reduce our domain or the range of input by half by half and the space complexity will be big of and the space complexity will be big of one because we are just storing one because we are just storing variables let's do an ansi perfect thanks for watching this video please subscribe to my channel for the upcoming videos see you soon
2024-03-20 11:18:32
69
https://i.ytimg.com/vi/o…axresdefault.jpg
Sqrt(x) | LeetCode 69 | Python Easy Explanation
gjP2MaPoguk
Loot Oil Welcome To Learn Repeat Today Bill Boxing Day Thirteen Update Change The Name Of The Boxing Day Thirteen Update Change The Name Of The Problem Me Shot Latest Updates Login Problem Me Shot Latest Updates Login Problem Only Problem States Give The Problem Only Problem States Give The Head Of Liquids Return Delhi Starter Head Of Liquids Return Delhi Starter Shopping Destination Digger Inform Shopping Destination Digger Inform This Can Us For Telling List In Open Login This Can Us For Telling List In Open Login This Can Us For Telling List In Open Login and open memory is a subject was it has been provided with the earliest and to samples for telling class 10 english not regret and uses in this world and give the sorted out now i am shocked we are the uses of marks for The can give The can give The can give one login time at 10 also login this sense one login time at 10 also login this sense pimples approach is pimples approach is but this tree is useless news18 approach and will give one but this tree is useless news18 approach and will give one piece brigade and login piece end piece brigade and login piece end of in login time in female cover dhawan page reach so lets of in login time in female cover dhawan page reach so lets technocrat example2 example2 technocrat example2 example2 421 421 421 Check The 421302 Divide The Mid Point Of The Parts Of The Day Dividing A Pan From South Africa Fashion Show Basically Into Divider First Epistle To Find Them And Tried So Let's Say Medical To Get Midnight List In List In List In Inox List 16 Right Down List Inox List 16 Right Down List Sarfaz Let's Get The Mid Point Sode From This Sarfaz Let's Get The Mid Point Sode From This My Deposit In RK Judgment Is The Head My Deposit In RK Judgment Is The Head Of The Right Most Part Right Surya The Head Of The Right Most Part Right Surya The Head Of The Rebel Swift So Let's Have This Is My Short Of The Rebel Swift So Let's Have This Is My Short In Threat And This In Threat And This In Threat And This list node in the basis of Notre Dame flashlights is not soiled comment part and again call the short and will give me a short for the lift key and similarly salute for the white part super soft pad right text start with And Sorry For The Life What Will Start And Sorry For The Life What Will Start And Sorry For The Life What Will Start With Head Panel Districts Of Clans What With Head Panel Districts Of Clans What Will Happen In His First Time Will Happen In His First Time Dividing This Is The Mid Point And Dividing This Is The Mid Point And Dividing This Link List Dividing This Link List That Aapke Is Ras Indian Elections And That Aapke Is Ras Indian Elections And Dividing This After Removing This Connection Between Dividing This After Removing This Connection Between The End Elements The End Elements The End Elements part and support element with right system limited by it is amazing hair same remove in this connection as well so fog clear force faith for 2 and 134 a tourist ok and again din will call record only after procedure for left and right Again Will Tree To Find Them And Again Will Tree To Find Them And Again Will Tree To Find Them And Chairman Balbir Das's Beautiful Successful Point To Chairman Balbir Das's Beautiful Successful Point To Them And End University Part Right To Them And End University Part Right To Boss Boss Again 10 Connection With Broken Down And Again 10 Connection With Broken Down And Will Be Left With Part--24 Will Be Left With Part--24 This Morning Online With Sprite You To That We This Morning Online With Sprite You To That We Can Can Can in which can check which means Greater Noida and formed during according to som rate that alcohol ten march on left and right that alcohol ten march on left and right and women are equal in the forest and check which and women are equal in the forest and check which means Greater Noida accordingly for means Greater Noida accordingly for telling light solution for this great telling light solution for this great telling light solution for this great to Sleep for Telling 10th 2.2 410 Left Most Parts Taken Care of OK Similar War Recessive Column 10 Man Ko Matri Exploitation Synthesis 30 Function Letter Foreign Minister OK Should Here It Will Have to List Thought Shot Also Its Life Present Shot Left Side Health Subcenter And right left can have And right left can have And right left can have attempted that attempted that and between bill check but I want to become a smaller and attempt by point to that smaller element wash nipple turn a wash nipple turn a smaller and smaller wrist take daina but smaller and smaller wrist take daina but umpire Dinesh Maurya made at feminine point umpire Dinesh Maurya made at feminine point this model school end this model school end this model school end time don't next who tempered with this particular slot 1234 ok khuda lut singh dhindsa and district so basically spoon dry ginger 6 two step obscene divide and other sources of vitamin D and sorry intake it's getting divide in the morning Dividing Africa Sunlight Se Of Log In Operation In The Morning Good Morning For All Elements And Operation Of Doing Log In Time In The Sky Itself In Log In A Time Complexity For Short Ok Software Doing A Division Respectively In The Divided They Can Visit Saturday Meat Divide Sudhir and Two Meat Divide Sudhir and Two Meat Divide Sudhir and Two Yesterday Morning Rubber Stamp of Dividing Weight and Yesterday Morning Rubber Stamp of Dividing Weight and the Second Step for Morning and Dividing the Second Step for Morning and Dividing Vansh Divide Vacancy in This Spot with Division Vansh Divide Vacancy in This Spot with Division Divine Virtues Develop Liquid Form Divine Virtues Develop Liquid Form Dividing in This Thought Exist Rate Dividing in This Thought Exist Rate That Your Northern Parts in Trivandrum That Your Northern Parts in Trivandrum and Spiderman White Amazing Link and Spiderman White Amazing Link and Spiderman White Amazing Link How They Find The Best All The Best Values For All Dual Gautam Basis Of Hair And What Is Approach White Dawood 642 Entry L'Liquid 22.81 Slow At The Time Of Annual Fest File First 5210 Dubai Journal 1.5 And Subscribe Remove They Should First First Point To Who The current noose dot nik at that time first The current noose dot nik at that time first The current noose dot nik at that time first point will appear and at the same time point will appear and at the same time snow point will move to this particular snow point will move to this particular position ok dena and check the fast does not position ok dena and check the fast does not and dinesh elements is not educated and dinesh elements is not educated channel motu next next sweet will move channel motu next next sweet will move to point here to point here to point here same time s loop control movie will share start from here.the principal da start from here.the principal da ghar ke members benefit ghar ke members benefit jai hind jai maharashtra jai hind jai maharashtra and finally on 10th select and finally on 10th select evening descending according will see evening descending according will see How the Made and Yadav present Operation How the Made and Yadav present Operation Bill Book not the best condition will be since Bill Book not the best condition will be since falling short list developed take right for the falling short list developed take right for the left and right with your introduction to pain additional left and right with your introduction to pain additional and dont national leaders in the written and dont national leaders in the written head no sense of just condition bound to get head no sense of just condition bound to get head no sense of just condition bound to get put and dum and what should declare get me in third famous head that 501 atom and right som from a downwards plenty of beating them don't worry morning i left side effect and breaking the in between connection rate is so let's no difficult to unknown Remove SIM Slot Matter For Self Ghrit Samaya Right From Wrong Words Ki And Dad I Can Simply March Left And Right And The Return Dashami Ki Sabzi Me Simple Model Online Payment The Great Indian Middle Head 2.5 Inch Le In-Between Loop And to the villagers And to the villagers And to the villagers 209 slow will be apps lo who 209 slow will be apps lo who is equal to good night good initiative in all in that is equal to good night good initiative in all in that case and points lo to end me help point myself to be introduced and fast will to solve valuable items will know to solve valuable items will know to solve valuable items will know to the mid point night show the best person whole moon start with right notes with them and not require a i made you this slot next okay so what everyone else has value from mother mine in this whole thing which is nothing but the right sub Be Are Not Only Be Are Not Only Be Are Not Only Dividing But Voice Of Breaking The Connection Between Dividing But Voice Of Breaking The Connection Between To The Connection M6 Lottery Ticket Na Sula Debit To The Connection M6 Lottery Ticket Na Sula Debit The Connection Haridwar Se Padhare Wedding The Connection Haridwar Se Padhare Wedding The List In To-Do List Servi Returning To Make Sure That Were Written The List In To-Do List Servi Returning To Make Sure That Were Written Media Which Nothing Media Which Nothing But Head Of The List But Head Of The List But Head Of The List Year Alarm Set Bill With Head Of The Laptop List And With Us List Sonu Yadav Improvement And Get Married Life In The Dreamhouse Method Well Mash Ghr Temporary Is Right And The Bell's Petra To Stay To That Point To That's The Role Of The Subscribe Now To The List Of The Volume This Question This Lineage Notification All And It's Not Good Humor Very Challenging Character Point Absolutely No Beat Them Zara Play List Play List Play List Play List The total classified.in The total classified.in The total classified.in dot next equal to dot next equal to play list on play list on what and want to two in treatments - 500 what and want to two in treatments - 500 list list are wn.com and now this water to two laxman dots are wn.com and now this water to two laxman dots next9 signinfreeman man tells pelican next9 signinfreeman man tells pelican 210 returned next exact something in 210 returned next exact something in to-do list tools to-do list tools to-do list tools Domestic To-Do List Do A Matter Of Industrial Control Student Next Mere Dil Ko Dean Student Welfare And Can Happen But If One Has More Element And List You Have More Element Site Record Swine Flu And Antill After Off List For All Not A Good But As Soon As One Of Not A Good But As Soon As One Of Not A Good But As Soon As One Of The National It Back Right Said That They Can See The The National It Back Right Said That They Can See The Table Spoon In Us And Elements And Table Spoon In Us And Elements And Plants In The List Limit Side 100g Dashrath Plants In The List Limit Side 100g Dashrath Elements And Directly Sign To The Elements And Directly Sign To The Telegraph Vinod Art 2064 Elements Which Telegraph Vinod Art 2064 Elements Which Can Directly Bless Can Directly Bless Can Directly Bless next that equal to swift playlist one is not equal to null in that case i first become scientist and say scientists to show share name section or buddha fun shot at least they can return the time set dot next flight development block Will Return Attempt Will Return Attempt Will Return Attempt Dots Next Dots Next Name Person Minute Fun Yes Of course Vihar Went To Meet Name Person Minute Fun Yes Of course Vihar Went To Meet The Division Part Between Getting Them And The Are The Division Part Between Getting Them And The Are Not Getting Comment But After Not Getting Comment But After Dividing Diet And The Bear Exists Hit The Dividing Diet And The Bear Exists Hit The Hunt Operation Namo Sop And The Write The Code People Hunt Operation Namo Sop And The Write The Code People On Diligence share your answer of Radhe Ki according to share your answer of Radhe Ki according to Bigg Boss Vihar Terminal Pradesh Bigg Boss Vihar Terminal Pradesh SP Sudhir Pani has added SP Sudhir Pani has added 154 additional and don't have national then button 154 additional and don't have national then button Vatavriksha head down so let's stay in get again so the are getting back paper Platform Add Us Dental College Platform Add Us Dental College Platform Add Us Dental College Chapter Member Post Speed ​​Mode 2 Hit The Like Chapter Member Post Speed ​​Mode 2 Hit The Like Button And Subscribe To This Channel Button And Subscribe To This Channel Thank You
2024-03-21 12:58:55
148
https://i.ytimg.com/vi/g…axresdefault.jpg
Sort List | LeetCode 148 | October LeetCode Challenge | Day 13
sj32Bf4-N7Q
hello everyone welcome to date night 15th of november challenge and today's 15th of november challenge and today's question is largest divisible subset in question is largest divisible subset in this question we are given an array of this question we are given an array of positive integers and we need to positive integers and we need to identify the largest subset as an answer identify the largest subset as an answer such that each pair entry that exist in such that each pair entry that exist in that subset satisfies this property that subset satisfies this property either either a modulus b is is equal to 0 or b a modulus b is is equal to 0 or b modulus a is equal to 0. if you sort modulus a is equal to 0. if you sort that subset in increasing order then one that subset in increasing order then one after the other each one will be after the other each one will be divisible with each other i'll tell divisible with each other i'll tell about it more in the presentation so about it more in the presentation so hold on without much to do let's look at hold on without much to do let's look at the ppt that i have created for this and the ppt that i have created for this and i'll walk you through the question as i'll walk you through the question as well as the solution in bpd itself well as the solution in bpd itself largest divisible subset lead code 389 largest divisible subset lead code 389 and let's take a very simple example and let's take a very simple example here in this case we have four elements here in this case we have four elements in our input data set one two three and in our input data set one two three and six six what is the possible solution with what is the possible solution with respect to this data set there are two respect to this data set there are two possible solutions that exist first one possible solutions that exist first one is one two six and other one is one is one two six and other one is one three six three six and it the answer could be any and it the answer could be any permutation of uh these three elements permutation of uh these three elements and any permutation of these three and any permutation of these three elements elements however however once we sort both of them what do we get once we sort both of them what do we get we get the elements in this fashion one we get the elements in this fashion one two and six one three and six so what is two and six one three and six so what is interesting about this sorted interesting about this sorted answer the interesting thing is if you answer the interesting thing is if you go pairwise each one will be divisible go pairwise each one will be divisible with each other for example the first with each other for example the first pair is one comma two pair is one comma two one comma two two is divisible by one one comma two two is divisible by one and as you progress ahead next pair is 2 and as you progress ahead next pair is 2 comma 6 6 is divisible by 2 and it will comma 6 6 is divisible by 2 and it will progress so as we have more elements in progress so as we have more elements in our answer data set similarly the first our answer data set similarly the first pair is 1 comma 3 3 is divisible by 1 pair is 1 comma 3 3 is divisible by 1 and as we progress ahead we have 6 comma and as we progress ahead we have 6 comma 3 6 is divisible by 3 and there could be 3 6 is divisible by 3 and there could be more elements depending on the size of more elements depending on the size of our answer data set so this gives us a our answer data set so this gives us a very interesting hint that we can use to very interesting hint that we can use to come up with an approach which is come up with an approach which is longest increasing subsequence longest increasing subsequence we have solved plenty of questions in we have solved plenty of questions in the past on the basis of longest the past on the basis of longest increasing subsequence problem increasing subsequence problem and we'll be using the same technique to and we'll be using the same technique to actually come up with an approach so actually come up with an approach so without much to do let's talk about this without much to do let's talk about this approach approach as a default case what is what would be as a default case what is what would be let's try and identify the length of the let's try and identify the length of the longest increasing subsequence that longest increasing subsequence that exists in this input array and exists in this input array and we'll follow the same approach as we we'll follow the same approach as we usually do in lis problems we'll take usually do in lis problems we'll take two pointers the first one two pointers the first one starting from the zeroth index which is starting from the zeroth index which is represented by j the other one for each represented by j the other one for each element considered individually element considered individually so let's point this as i and so let's point this as i and as a default case when we consider each as a default case when we consider each element separately what is the length of element separately what is the length of the maximum possible largest size that the maximum possible largest size that could be formed it is one because you could be formed it is one because you have you don't have any have you don't have any more elements you are only considering more elements you are only considering each element individualistically so each element individualistically so let's start the iteration let's start the iteration we we are intending and finding out the we we are intending and finding out the length of the longest increasing sub length of the longest increasing sub sequence out of this given array sequence out of this given array right now the ith pointer is pointing to right now the ith pointer is pointing to 2 and jth pointer is pointing at 1. 2 and jth pointer is pointing at 1. let's check whether it meets a condition let's check whether it meets a condition or not or not 2 modulus 1 is 0 that means the 2 modulus 1 is 0 that means the condition is met so what do we do in condition is met so what do we do in such cases we utilize the value that is such cases we utilize the value that is set at the jth index and add 1 to it set at the jth index and add 1 to it so what is the value set at the jth so what is the value set at the jth index it's 1 so 1 plus 1 gives us 2 so index it's 1 so 1 plus 1 gives us 2 so we go and update this with 2. we go and update this with 2. let's proceed ahead and this time the is let's proceed ahead and this time the is pointer moves to pointer moves to second index and let's start the second index and let's start the iteration js pointer again moves from iteration js pointer again moves from the zeroth index the zeroth index and here what do we see the current and here what do we see the current element is one the ith element is three element is one the ith element is three it's again a matching case three modulus it's again a matching case three modulus one is zero so we simply go and update one is zero so we simply go and update the value at the second index to the the value at the second index to the value at the js index plus 1 which gives value at the js index plus 1 which gives us 2 us 2 1 plus 1 gives us 2. 1 plus 1 gives us 2. let's proceed ahead and this time j is let's proceed ahead and this time j is pointing at 1 is the condition met 3 modulus 2 divisible by 0 no the condition is not met we again proceed with j to a higher value and this time i and j becomes equal we are about the process let's proceed ahead next i comes at the third index and we see six here so let's start the iteration and we have and we have g are zero is the condition met 6 g are zero is the condition met 6 modulus 1 is is it 0 the answer is yes modulus 1 is is it 0 the answer is yes so we'll utilize the value that is set so we'll utilize the value that is set as as j and add 1 to it so we get j and add 1 to it so we get 2 here let's proceed ahead and next we 2 here let's proceed ahead and next we have have is 2 is 2 is 6 divisible by 2 the answer is yes so is 6 divisible by 2 the answer is yes so we'll reutilize the value that is set at we'll reutilize the value that is set at the the dp of jth index the dp of the the the dp of jth index the dp of the 8th index is 2 8th index is 2 so we'll go and update it with 2 plus so we'll go and update it with 2 plus one which is three one which is three let's proceed ahead next we see is three let's proceed ahead next we see is three so is three modulus a six modulus three so is three modulus a six modulus three is zero is it zero the answer is yes so is zero is it zero the answer is yes so we'll reutilize the value we'll update we'll reutilize the value we'll update uh this with uh this with 2 plus 1 which is 3 so it won't make any 2 plus 1 which is 3 so it won't make any difference the answer still says 3 so difference the answer still says 3 so what is the updated state of the dp that what is the updated state of the dp that we have filled in we have 1 here we have we have filled in we have 1 here we have 2 here we have 2 here we have 3 here 2 here we have 2 here we have 3 here what is the largest entry that was found what is the largest entry that was found in the in the dp array the largest entry is dp array the largest entry is 3 3 so that means the length of the longest so that means the length of the longest increasing subsequence with respect to increasing subsequence with respect to this input array is this input array is 3 3 i hope we are good so far now how is i hope we are good so far now how is this three helping us in identifying the this three helping us in identifying the answer it's pretty simple and straight answer it's pretty simple and straight forward it's similar to narc problem how forward it's similar to narc problem how let's talk about it let's talk about it so so we will go search for that index where we will go search for that index where this maximum value is occurring the this maximum value is occurring the maximum value is occurring at maximum value is occurring at the third index and what is the value the third index and what is the value there the value there is 6 that means there the value there is 6 that means this will be possible contender for our this will be possible contender for our answer so we add 6 to our answer answer so we add 6 to our answer and we'll simply reduce the max value and we'll simply reduce the max value maximum value gets reduced by maximum value gets reduced by one and it gets updated to two one and it gets updated to two we'll reduce the pointer as well we'll reduce the pointer as well so the next element that we foresee so the next element that we foresee towards towards left left is is three is three and at three we have we three is three and at three we have we see that the dp value is two so it's see that the dp value is two so it's again a matching case again a matching case since it's a matching case since it's a matching case we will check we will check whatever previous value we witnessed whatever previous value we witnessed which was 6 which was 6 and where the condition was met or and where the condition was met or finding the largest element finding the largest element whether that value is divisible by this whether that value is divisible by this current value or not current value or not you can see that that value is divisible you can see that that value is divisible by the current value 6 modulus 3 is by the current value 6 modulus 3 is divisible that means this becomes part divisible that means this becomes part of our answer of our answer so so we will simply go and add 6 to our we will simply go and add 6 to our answer data 3 to our answer data set and answer data 3 to our answer data set and again we'll simply reduce the max value again we'll simply reduce the max value by one by one max value gets updated to one max value gets updated to one and and let's proceed here towards left let's proceed here towards left is the condition met what is the db is the condition met what is the db value at two value at two at this particular index it is 2 so at this particular index it is 2 so this value doesn't sound equal to this value doesn't sound equal to the max value we'll ignore this let's the max value we'll ignore this let's proceed ahead towards further left proceed ahead towards further left and and what is the current dp value at this what is the current dp value at this particular index the current dp value is particular index the current dp value is 1 1 is this equal to the max value is this equal to the max value yes that it's equal so what do we do we yes that it's equal so what do we do we simply go and check what was the simply go and check what was the previous last value that we saw that was previous last value that we saw that was matching the previous last value was 3 matching the previous last value was 3 so 3 so 3 was was the previous last value and is was it the previous last value and is was it divisible is it divisible by 1 the divisible is it divisible by 1 the answer is yes so we'll add 1 to it answer is yes so we'll add 1 to it so one possible solution that turns out so one possible solution that turns out to be is 1 3 and 6. to be is 1 3 and 6. now someone may question that what about now someone may question that what about the other case one two and six how can the other case one two and six how can we arrive at that particular solution we arrive at that particular solution let's reiterate the dp table once more let's reiterate the dp table once more we have one two we have one two three and six and what were the dp three and six and what were the dp entries one two two and three entries one two two and three so let's start the iteration from the so let's start the iteration from the last entry and the maximum length of li last entry and the maximum length of li that we found out was three so it's a that we found out was three so it's a matching case we fill in our answer matching case we fill in our answer data data set with six and we will data data set with six and we will simply reduce the simply reduce the maximum length by one the maximum length maximum length by one the maximum length gets updated to two gets updated to two and six gets added as our answer data and six gets added as our answer data set we move towards set we move towards left and we by left and we by chance there could have been case where chance there could have been case where uh uh instead of the value 2 here we could instead of the value 2 here we could have got some other value so for let's have got some other value so for let's hypothetically forget that hypothetically forget that here we had to let's assume here we had to let's assume uh there was no two here so let's again uh there was no two here so let's again progress towards progress towards uh the left most entry uh the left most entry and what is the db value here the db and what is the db value here the db value is two it's a matching case these value is two it's a matching case these two matches so we simply go and check two matches so we simply go and check what was the previous entry in our what was the previous entry in our answer data set the answer data set has answer data set the answer data set has six is it divisible by two six is it divisible by two yes it is divisible by two we'll simply yes it is divisible by two we'll simply go and add go and add two to our answer data set and reduce two to our answer data set and reduce the max the max length value the max length gets reduced length value the max length gets reduced to one and let's further proceed towards to one and let's further proceed towards left left what do we see we see one and at one we what do we see we see one and at one we the dp entry is again one so it's a the dp entry is again one so it's a matching case matching case what was the previously uh last entry what was the previously uh last entry that was added in our answer data set it that was added in our answer data set it was 2. was 2. so we check whether 2 is divisible by 1 so we check whether 2 is divisible by 1 2 is divisible by 1 yes so we'll add it 2 is divisible by 1 yes so we'll add it to an answer data set and it gets added to an answer data set and it gets added the length gets reduced to 0. the length gets reduced to 0. in this way we found out that 1 two and in this way we found out that 1 two and six does exist in an answer data set it six does exist in an answer data set it was a matter of chance that we gave more was a matter of chance that we gave more priority uh to 136 by coincidence we priority uh to 136 by coincidence we were not aware that whether two will were not aware that whether two will exist later in the exist later in the iteration or not we greedily accepted iteration or not we greedily accepted the one that was giving us one possible the one that was giving us one possible solution solution so so as the question said we are not as the question said we are not interested in identifying all the interested in identifying all the possible solutions we are interested in possible solutions we are interested in identifying just one of them so we identifying just one of them so we greedily pick one greedily pick one without much ado let's look at the without much ado let's look at the coding section and i'll be walking coding section and i'll be walking through the different parts of code through the different parts of code in exactly the same manner as i've done in exactly the same manner as i've done here here i've defined a dp array of size nums.length and i have defined a construct lds helper method even before going on to the details of this helper method we are internally invoking get largest lds size which is giving us the length of the longest lds possible in this complete input array so let's walk through this helper method first in the first place i sorted this input array then i filled in the dpr with one and i initialized the maximum lds size or the ldsi helper variable as one because default would be that and let's start the iteration it's a typical lis approach that we usually do i started with i equals 1 up till nums dot length j starts from 0 up till j is less than i and i check whether the ith element is divisible by jth element if that is the case then i update my dp array to math.max of dp at the is index comma db of j plus 1 and i update my lds size variable to math.max ldsi command dp of i once we iterate through this complete two loops i return the lds size variable that gives us the maximum possible size of longest divisible subset let's now walk through the construct lds helper method it's pretty simple and straightforward and it's exactly doing the same thing as i talked about in the presentation so i have defined a previous uh variable which is -1 because we are going to fill the first element first i'm storing all the elements in the form of a linked list and i'll tell you the reason why i start the iteration in the reverse direction going from the last entry to the first one because we want to pick choose the one which which is of higher amount while traversing back so let's check if my dp at the ith index is equal to lds size or and my previous happens to be equal to -1 if that is the case i go and add lds uh the current element in my lds answer set i reduce the value and assign the previous one to the current element that we have recently added for the next comparison to hartman and what is that comparison that the previous element is divisible by num at the its index we keep on going till the time the value of lds doesn't reduce to zero and that will only happen once we have iterated through the complete input array in the end i simply return the lds linked list that i have created why i am using linked list here because it supports add first method that adds the element at the zeroth index let's try [Music] [Music] accepted this brings me to the end of accepted this brings me to the end of today's session i hope you enjoyed it if today's session i hope you enjoyed it if you did please don't forget to like you did please don't forget to like share and subscribe to the channel share and subscribe to the channel thanks for being it have a great day and thanks for being it have a great day and stay tuned for more updates from coding stay tuned for more updates from coding decoded i'll see you tomorrow with decoded i'll see you tomorrow with another fresh question but till then another fresh question but till then good bye
2024-03-24 11:32:01
368
https://i.ytimg.com/vi/s…cqO9uhnlAqJIJltg
Largest Divisible Subset| Leetcode 368 | live coding session 🔥🔥🔥🔥
uaSnnAjbaXk
[Music] in this video we're going to be looking in this video we're going to be looking at this problem longest absolute file at this problem longest absolute file path so we're given a file system that path so we're given a file system that stores both files and directories here's stores both files and directories here's an example of that file system so you an example of that file system so you have dir then subdir1 file1.ext have dir then subdir1 file1.ext sub subdir1 subner2 sub subner2 and sub subdir1 subner2 sub subner2 and file2.ext file2.ext and here is that in text form and here is that in text form so you'll see that everything is on a so you'll see that everything is on a new line new line and the level of the directory or file and the level of the directory or file is the number of tab characters is the number of tab characters so this is that as a string slash n and slash t are the new line and tab characters so keep in mind these are individual characters every file and directory has a unique absolute path in the file system which is all the directories names concatenated with slashes and then the file name so the absolute path of file1.txext would be dur subdir1 file1.ext the absolute path of subsubter2 would be dir subter2 subsubdir2 and all the directories in this problem uh their names only consist of letters digits and or spaces whereas the file names will always be in the form name.extension like this so obviously this is not true in real file systems in real life but this problem is a simplification ultimately the goal is that given one of these strings representing the file system we want to return the longest absolute path to a file keep in mind this is not the longest absolute path to a directory we're only looking at files let's look at the examples so for the first one the longest absolute file path should be dur subdir2 file.ext so if you count the number of characters including the slashes it has length 20. for the second one we have two files file1.ext and file2.ext but file2.ext obviously has the longest longest absolute file path which is dur subdir2 slash sub sub32 file2.ext and this has length 32 and then for the last one so this kind of represents the kinds of edge cases where the file system only has directories and no files in which case we return zero okay let's break this question down from the string that's given obviously the first thing that we and then we would end up with something and then we would end up with something like this where every directory or file like this where every directory or file is on its own new line each preceded is on its own new line each preceded with tab characters with tab characters now we can iterate through this file now we can iterate through this file system line by line but how do we keep system line by line but how do we keep track of the current absolute path let's track of the current absolute path let's think about how we would iterate through think about how we would iterate through this by hand this by hand so first we're so first we're then we go to subdir1 then we go to subdir1 then we go to file1.ext then we go to file1.ext and then when we go to sub subner1 we and then when we go to sub subner1 we have to remove file1.ext have to remove file1.ext and then add sub subner1 and then add sub subner1 and then when we go to subdoor 2 we have and then when we go to subdoor 2 we have to remove to remove these two items and add subdir2 these two items and add subdir2 and then subsub 32 and the file2.ext and then subsub 32 and the file2.ext at this point should be pretty clear at this point should be pretty clear that we are exactly describing a stack that we are exactly describing a stack as we move deeper into the directory as we move deeper into the directory structure we push each subdirectory or structure we push each subdirectory or file onto the stack and as we move out file onto the stack and as we move out of each subdirectory we pop them from of each subdirectory we pop them from the stack the stack the question is how many items do we the question is how many items do we pump so let's look at the example of pump so let's look at the example of when we go from when we go from sub sub 1 to subdir2 sub sub 1 to subdir2 so at sub sub 1 the stack with three so at sub sub 1 the stack with three items items there subter 1 and sub subner1 there subter 1 and sub subner1 and at subject 2 we want to pop two and at subject 2 we want to pop two items since we want to remove sub sub 1 items since we want to remove sub sub 1 and subdirt 1. so if you try some more and subdirt 1. so if you try some more examples you'll see that you'll want to examples you'll see that you'll want to pop pop sizeofstack sizeofstack minus currentlevel number of items from minus currentlevel number of items from the stack where level is just the depth the stack where level is just the depth of the current directory or file it's of the current directory or file it's essentially the number of tab characters essentially the number of tab characters proceeding let's add this to the proceeding let's add this to the pseudocode pseudocode let's initialize the stack and then for each line if we're going we're going to push the directory or we're going to push the directory or file onto the stack file onto the stack and then otherwise we're going to pop and then otherwise we're going to pop as we said this number of items from the as we said this number of items from the stack then if the line well we're going to keep track of the well we're going to keep track of the current longest absolute file path current longest absolute file path so this is a great start but we actually so this is a great start but we actually come into a bit of a problem the thing come into a bit of a problem the thing is that we only care about the length of is that we only care about the length of the longest absolute file path but right the longest absolute file path but right now in the stack we're keeping track of now in the stack we're keeping track of the file path itself so meaning the the file path itself so meaning the names of its directories and files the names of its directories and files the issue is at this line when we encounter issue is at this line when we encounter a file we try to compute the length of a file we try to compute the length of its path we have to traverse through the its path we have to traverse through the entire stack summing up the lengths of entire stack summing up the lengths of each directory each directory and then adding the additional lengths and then adding the additional lengths with the slashes with the slashes let's try something slightly different let's try something slightly different in the stack instead of keeping track of in the stack instead of keeping track of the names of the directories or files the names of the directories or files let's keep track of the current file let's keep track of the current file path length so far so let's see this in path length so far so let's see this in action and this will probably become action and this will probably become more clear so one tidbit is we're going more clear so one tidbit is we're going to initialize the stack to initialize the stack with zero to indicate that starting from with zero to indicate that starting from the root of the file system the length the root of the file system the length is zero let's also have a variable is zero let's also have a variable keeping track of the max length to a keeping track of the max length to a file so far once we get to dur file so far once we get to dur instead of pushing dirt onto the stack instead of pushing dirt onto the stack we push three since that's the current we push three since that's the current length length once we get the sub door one we first once we get the sub door one we first take a peek at the stack to get the take a peek at the stack to get the length so far which is three then do length so far which is three then do three plus the length of subdue one three plus the length of subdue one which is which is three plus seven and then plus one since three plus seven and then plus one since with every level we introduce a slash in with every level we introduce a slash in the file path the file path so we push three plus seven plus one so we push three plus seven plus one which is 11. which is 11. once we get to file1.ext we do the same once we get to file1.ext we do the same thing so we peak the stack thing so we peak the stack see that's 11 at the length of file 1. see that's 11 at the length of file 1. ext which is 9 then plus 1. so we're ext which is 9 then plus 1. so we're going to push 11 plus 9 plus 1 which going to push 11 plus 9 plus 1 which equals 21. equals 21. and since this is a file we keep track and since this is a file we keep track of this length so we update max to be of this length so we update max to be 21. 21. once we get to sub subter one once we get to sub subter one well we're gonna have to pop from the well we're gonna have to pop from the stack but this time we're going to pop stack but this time we're going to pop size of stack minus current level minus one so the minus one is because we initially initialized the stack with zero then we push 11 plus the length of subdur1 which is 10 then plus 1 which is 22 onto the stack so then once we get to subdirt 2 we pop and then we push three plus the length and then we push three plus the length of sub two which is seven plus one which of sub two which is seven plus one which is eleven onto the stack is eleven onto the stack once we get to sub subner two we push 11 once we get to sub subner two we push 11 plus the length of sub sub 2 which is 10 plus the length of sub sub 2 which is 10 plus 1 which is 22 onto the stack plus 1 which is 22 onto the stack once we get to file2.ext once we get to file2.ext we push 22 plus length of file2.ext we push 22 plus length of file2.ext which is 9 plus one which is 32 onto the which is 9 plus one which is 32 onto the stack since this is a file we update max to be 32 and then finally we return max which is 32 and that's the correct answer let's update our pseudo code a little bit so we're going to initialize the stack with zero here and then instead of pushing the director or file into the stack let's instead push this value stack.peak plus the length of directory or file plus one onto the stack and then we're going to pop size of stack minus current level minus one items from stack and if line is a file we keep track of the current longest absolute file path so this looks fine okay great so we have a working solution let's look at the time complexity so we have a loop iterating through n lines pushing an item onto the stack is o1 popping is o1 but we're not popping one item we're popping size of stack minus current level minus one which is essentially on the order of the number of levels which can be arbitrarily deep so in our worst place we pop from an arbitrarily deep level to zero so our time complexity is going to be o of n times l where n is the number of lines and l is the maximum level depth we use space with the stack and the stack grows as we get deeper into the directory structure in the worst case the stack rose to the maximum level okay now let's implement this in java okay now let's implement this in java start off with a stack then we're going to initially push 0 onto the stack and we're going to also have a variable keeping track of the max length so far and we're going to iterate through this input but we're also going to split it by that those new lines [Music] now the level is going to be the number of tabs so one way we can compute it is do last index of the tab character and then plus one [Music] then we're going to pop those items from the stack it's going to be wild levels less than stack dot size that's one now we're going to push the current now we're going to push the current length onto the stack length onto the stack so as we said the length is going to be so as we said the length is going to be we're going to peak we're going to peak and take the current length and take the current length minus the level minus the level plus 1. plus 1. so so we're going to do s dot length minus we're going to do s dot length minus level because if you think about it if level because if you think about it if we try to just push the length of the we try to just push the length of the string it's also going to include those string it's also going to include those tab characters so we do need to subtract tab characters so we do need to subtract them from that calculation them from that calculation and we're going to push that onto the and we're going to push that onto the stack stack the way we're going to check if it's a the way we're going to check if it's a file is that we're just going to check file is that we're just going to check if the period exists in this string if the period exists in this string that contains that contains period period then we know that it's a file so that then we know that it's a file so that we're going to update the maximum length and at this point we're going to return the maximum length okay let's submit this great and you'll see that it passes and that's how you solve this problem
2024-03-24 12:02:45
388
https://i.ytimg.com/vi/u…axresdefault.jpg
Longest Absolute File Path | Top Google Coding Interview Question
V2VrBK5FjoY
Hello Hi Everyone Welcome To My Channel Today Vishal's Problem Repeated DNA Sequence Vishal's Problem Repeated DNA Sequence Sold In Is Composed Of A Series Of Sold In Is Composed Of A Series Of Nucleotides Every Son CET For Example Nucleotides Every Son CET For Example A CGTTCE Web Streaming A CGTTCE Web Streaming DLNA Mitti Sometime Useful To Identify DLNA Mitti Sometime Useful To Identify Repeat Sequences With Tel Repeat Sequences With Tel Function To Find All The Channel Subscribe Function To Find All The Channel Subscribe Indian molecule for example subscribe Indian molecule for example subscribe and subscribe and subscribe the letter and subscribe and subscribe the letter sequences and 181 others like this sequences and 181 others like this candy crush off switch off but also let this is the candy crush off switch off but also let this is the worst thing is formed with worst thing is formed with this CGT characters in the at all the this CGT characters in the at all the possible like starting from here.the possible like starting from here.the time time time one to 1100 21000 tenth wicket all subscribe key basic of the subscribe person that updates of string and will be taking up this will increment account plus other wise will continue to deal with account in this live with great all the frequency of All the sub strings of passion from distic head from death will pick put do subscription death in the frequency grade one hour video video.com is to hair is the code implementation of the approach explain just suffers death system app created during this time later skin Cutting All The Subscribe From Wearing His Cutting All The Subscribe From Wearing His Cutting All The Subscribe From Wearing His Client 10 Likes Decide So I'll Get Client 10 Likes Decide So I'll Get Destroyed Loop - The Video then Line Of Food Which Line Of Food Which Can Also Write In One Line Using Java Apps Can Also Write In One Line Using Java Apps Peene Par So This Is And Hair Soft Peene Par So This Is And Hair Soft Peene Par So This Is And Hair Soft and decided in Ubuntu from this cream and after that all the best ringtone all entries from main entry set between frequency like person written in the map subscribe like this is the solution we need subscribe like this is the solution we need to check justin bieber to check justin bieber to check justin bieber also role frequency business needs to check weather the sequence like it servi gas so let's move with string of 1000 cc interference rather edison has one set between is not same set thursday decide which will be repeated-repeated subscribe and subscribe this subscribe this subscribe this Video is not servi for all Dual Video is not servi for all Dual is so let's implemented solution is 42% is so let's implemented solution is 42% solution first is looted call the scene in Amla from solution first is looted call the scene in Amla from is set up is set up that hindi setting set is later call repeated that hindi setting set is later call repeated in this worthy place this is wealth from that in this worthy place this is wealth from that nobody will treat all nobody will treat all nobody will treat all 8 - Northern Region At All The Serving Of 70 Plus No Will Cut First Tasting Labs A Visual Vs Dot String Of Islands A Visual Vs Dot String Of Islands Of Two Of Two That I Plus Time When Will Check If Scene That I Plus Time When Will Check If Scene Contains Lots Of String Till Arab Skin Already Contains Lots Of String Till Arab Skin Already Brainwashed This Brainwashed This Brainwashed This repeated set else will always keep adding to the scene on 220 This is the case will get her so she will be updated and will return the list of weights reduce by repeated on 210 Shetty implementation let's compile code Not find a Not find a Not find a simple typo scene repeated notice simple typo scene repeated notice a c n letters in thoughts and specific btc a c n letters in thoughts and specific btc not know d j not know d j i saudi shutbox networking sites of i saudi shutbox networking sites of medicated that i have tractor pet so what is the time complexity of dissolution the time complexity of dissolution and you can see the Drawing for full length of verses in the hair for creating subscribe in a reader subscribe and subscribe the Channel and subscribe the
2024-03-21 14:17:21
187
https://i.ytimg.com/vi/V…axresdefault.jpg
repeated dna sequences | repeated dna sequences leetcode | leetcode 187 | Set | Map
FGL01lcNBeE
uh this question is a minimum difference between PST nodes so you're given a root between PST nodes so you're given a root of a PSD and then return the minimum of a PSD and then return the minimum difference between the value of any two difference between the value of any two different nodes different nodes in the tree so basically like you can in the tree so basically like you can Traverse the tree and then uh get your Traverse the tree and then uh get your current now and then subtract by the current now and then subtract by the previous node and then this will be the previous node and then this will be the solution so how do you how do you sort solution so how do you how do you sort the tree I mean so sort the PST tree you the tree I mean so sort the PST tree you are going to use in order traversal are going to use in order traversal in order in order [Music] so if you know it's actually good to know then basically you are your time you try this to left then you try this to the right so uh like this the idea is like this right but what we need is we need to keep track of the previous node so actually no three right and now I need to know the minimum minimum difference so in I'm going to call result so I'm going to initialize 3 equal to now and now we're just calling order follow and now we're just calling order follow root and when I return and it will root and when I return and it will return the result right so return the result right so um what I need is what uh and this is um what I need is what uh and this is reverse all the way to the left in the reverse all the way to the left in the tree then I need to make sure if the tree then I need to make sure if the tree is not equal to no right then I tree is not equal to no right then I would definitely know like I need to would definitely know like I need to obtain my results right obtain my results right so it's going to be a lot of the current so it's going to be a lot of the current value minus the previous value okay and value minus the previous value okay and once I once I um uh once I take I mean once I know I'm um uh once I take I mean once I know I'm not the first the first note right so if not the first the first note right so if I'm one right I don't have a previous I'm one right I don't have a previous note right but if I'm at two I know my note right but if I'm at two I know my previous note is one right because the previous note is one right because the immortal traversal immortal traversal uh sorry uh sorry I know you know the traverses go all the I know you know the traverses go all the way to a lab and then go back to the way to a lab and then go back to the period and go all the way to the right period and go all the way to the right right so so once I know I'm in a parent right so so once I know I'm in a parent of this one I need to know I need to of this one I need to know I need to update this to my previous right update this to my previous right all right so I'll just say previous all right so I'll just say previous and this is pretty much it right so uh and this is pretty much it right so uh if the previous that's not equal to now if the previous that's not equal to now you update the current value for result just run it so let's talk about the time in space this is a space so I would say it's constant this is a time right the time is actually all the same uh it's actually the number of notes in the tree and this is a pretty much a Time complexity so there's no other uh there's no other time complexity in this function so uh this is this is a
2024-03-21 16:38:41
783
https://i.ytimg.com/vi/F…axresdefault.jpg
LeetCode 783 | Minimum Distance Between BST Nodes | In order Traversal | Java
XbJh14wtriQ
everyone it's Orkin welcome to my Channel today we are gonna solve a lead Channel today we are gonna solve a lead code 162 find Peak element problem so code 162 find Peak element problem so the problem statement is that we are the problem statement is that we are given an input array and we need to find given an input array and we need to find a peak element and return that Peak a peak element and return that Peak element in case if we have multiple element in case if we have multiple Peaks we can return any pick Peaks we can return any pick um um another important requirement is that another important requirement is that the algorithm must run in log n time the algorithm must run in log n time complexity complexity uh so what's the peak element Peak uh so what's the peak element Peak element is the element that is more than element is the element that is more than its neighbors for example in the example its neighbors for example in the example one we have one we have um three which is the peak element um three which is the peak element because it's more than two and the one because it's more than two and the one it's neighbors so we can return it as a it's neighbors so we can return it as a peak element the same way peak element the same way um um in the example two we have six which is in the example two we have six which is uh which is the which is the peak uh which is the which is the peak element because it's more than five and element because it's more than five and the more than four and we need to return the more than four and we need to return not the element but we need to return not the element but we need to return the the index of the element the the index of the element and return its index okay uh so that's and return its index okay uh so that's the problem let's see how we are gonna the problem let's see how we are gonna solve it solve it um let's take example of one um let's take example of one two three and one our first example and two three and one our first example and let's uh let's work on it so let's uh let's work on it so um by requirement we need to solve this um by requirement we need to solve this problem with the log n time complexity problem with the log n time complexity and right away we can say that okay uh and right away we can say that okay uh login time complexity we need to use a login time complexity we need to use a binary search here to find our binary search here to find our uh to find our Peak element so what we uh to find our Peak element so what we need to do first we need to Mark left need to do first we need to Mark left and right for the binary search and right for the binary search um so our first element would be our um so our first element would be our left and our last element would be our left and our last element would be our right so let's do that in the iteration right so let's do that in the iteration in the first iteration what we do we are in the first iteration what we do we are finding a mid element which is equals to finding a mid element which is equals to 2 and we are comparing the element that 2 and we are comparing the element that comes after it so basically whatever comes after it so basically whatever element comes after the mid we are element comes after the mid we are comparing if it's more than our mid comparing if it's more than our mid element then we are searching our element then we are searching our uh for our Peak on the right side of our uh for our Peak on the right side of our array in this case yes the three is more array in this case yes the three is more than two so we are selecting this part than two so we are selecting this part and the searching for our uh searching and the searching for our uh searching for our for our Peak element on the right side so in the Peak element on the right side so in the second iteration so we are moving our second iteration so we are moving our left here so we are moving our left here left here so we are moving our left here and we are searching for our pick and we are searching for our pick element on the element on the on the right side in the second on the right side in the second iteration what we do is we are our mid iteration what we do is we are our mid element is three so we are comparing if element is three so we are comparing if the element that comes uh the next the element that comes uh the next element after our mid if it's more than element after our mid if it's more than three then we are searching on the three then we are searching on the second part for our second part for our um pick in this case it's not so we are um pick in this case it's not so we are selecting uh three as our Peak element selecting uh three as our Peak element and we are returning left and we are returning left we are returning left as we are returning left as as a as a result because it's the index as a as a result because it's the index of our Peak element okay let's actually of our Peak element okay let's actually take a look at the one more Corner case take a look at the one more Corner case let's say that we don't have this let's say that we don't have this um we don't have this example but we um we don't have this example but we have something like one two uh two three have something like one two uh two three uh four five something like this uh four five something like this so in this case uh in this case uh if we so in this case uh in this case uh if we are gonna so in the first iteration we are gonna so in the first iteration we also move our we also move our left to also move our we also move our left to the uh to the three but the hour in the the uh to the three but the hour in the as you can see here our array in the as you can see here our array in the second part is just to keep increasing second part is just to keep increasing so how we can make sure that we are so how we can make sure that we are selecting our uh we are selecting our selecting our uh we are selecting our uh or on the right side we are going to uh or on the right side we are going to find the peak element because it's just find the peak element because it's just keep increasing well in that case we are keep increasing well in that case we are marking five as a peak element because marking five as a peak element because uh the in this case 5 has only one uh the in this case 5 has only one neighbor four and it's more than its neighbor four and it's more than its neighbor and in this case we are marking neighbor and in this case we are marking as a peak element as a peak element so that's how we are going to solve this so that's how we are going to solve this problem yeah let's uh let's put our problem yeah let's uh let's put our um this algorithm to code um this algorithm to code okay uh first thing that we need to do okay uh first thing that we need to do we need to Define our left we need to Define our left uh is equals to zero because we are uh is equals to zero because we are starting from the beginning of the array starting from the beginning of the array and we need to Define our right which is and we need to Define our right which is the end uh last element in the array so the end uh last element in the array so for that we are taking our length for that we are taking our length minus one okay so the net next thing minus one okay so the net next thing that we need to do we need to while our that we need to do we need to while our left is less than our right left is less than our right so what we need to do we need to find so what we need to do we need to find first the mid element let's call it mid first the mid element let's call it mid and left and left plus plus um right um right minus left minus left divided by 2 so that's how we are divided by 2 so that's how we are finding our mid element and we are finding our mid element and we are checking if our checking if our um nums uh mid element um nums uh mid element uh is if our next element that come uh is if our next element that come after the mid if it's more than our mid after the mid if it's more than our mid element so element so meet a plus one if it's more than our meet a plus one if it's more than our mid element then we are searching for mid element then we are searching for the our pick on the the our pick on the um on the right side of the array so for um on the right side of the array so for that we need to move our left pointer so that we need to move our left pointer so our left is equals to Mid plus one okay our left is equals to Mid plus one okay so if not then we are searching for the so if not then we are searching for the we are searching for the uh our Peak we are searching for the uh our Peak element on the left side of the array element on the left side of the array for that we need to move our right for that we need to move our right pointer pointer right is equals to Mid okay right is equals to Mid okay uh that's it uh that's it um once we exit this Loop we have the um once we exit this Loop we have the you know we have our pick so for that we you know we have our pick so for that we need to return need to return uh we need to return uh we need to return uh our index so we are returning uh left uh our index so we are returning uh left uh we are returning index not the uh we are returning index not the element itself because that's the element itself because that's the requirement requirement um that's it let's check our code okay it works as expected uh so let's go go over the code one more time first we are defining left and right pointers then we are moving our left and right pointers until we find our Peak element for that we are defining a mid element and if our mid plus one the element that comes after the mid is more than our mid element then our we are moving our searching for the um for the um pick element on the right side of the array the for that reason we are moving left otherwise we are searching for the Peak on the left side of the array and we are moving our right and at the end we are returning the index of the element that that is that is that is the peak so that's it um hope you like my content if you like it please hit the like button and the Subscribe my channel that's it for today see you next time
2024-03-21 13:48:07
162
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode - 162.Find Peak Element | Binary Search | Step-by-Step Explanation
tUz4Bb59rbU
Soon hello guys normal tell me their video line and liquid problem problem problem problem video line and liquid problem problem problem problem description And kuch nahin soch raha hoon nine mostly ko kuch nahin soch raha hoon nine mostly ko Meghnad teri tarf and video arrow button like Meghnad teri tarf and video arrow button like share subscribe subscribe 0nline Adhir share subscribe subscribe 0nline Adhir Veerwati subscribe must subscribe Veerwati subscribe must subscribe subscribe channel listen, according to the blossom on the mango trees, on the important awards, lust, darkness, and maximum, 10 loot, loot, loot, loot, subscribe, so that this 100, today is Tuesday 2104, who is the appointment of Sirvi, the minimum is 200, hey brother, the maximum. minimum is 200, hey brother, the maximum. minimum is 200, hey brother, the maximum. Shyam, reduce that Ravan, say something, the structure is at maximum, the not forget to subscribe my channel, not forget to subscribe my channel, that Shivlinga demand, if you speak, your husband, more than 100 quantity of salt, subscribe to that more than 100 quantity of salt, subscribe to that Ministry of External Affairs appointed on this number Ministry of External Affairs appointed on this number 12 12 that on Friday morning Pawan Dev Ji will take the road that on Friday morning Pawan Dev Ji will take the road Swad 153 acting Purna Vaas Timed Swad 153 acting Purna Vaas Timed Kaboul Switch on the first number Kyun Loota Kaboul Switch on the first number Kyun Loota Loota Loota Accused No. 90 Subscribe now He will start acting here and there He will start acting here and there He will start acting here and there on the number one playlist to my channel number, make your own number one impatient person click the subscribe button on the side and subscribe my channel like and subscribe to loot jaane loot jaane loot jaane first for u first formal mist and are wow last first formal mist and are wow last seeervi seeervi seervi subscribe do seeervi seeervi seervi subscribe do that in the number four hai fuel maang ki hai ok was that in the number four hai fuel maang ki hai ok was so impressed upon it's very so impressed upon it's very difficult to decide the 63.51 hai difficult to decide the 63.51 hai hua tha loot and dynasty chicken teaching be the richest Half hour of crocodiles etc constipation Half hour of crocodiles etc constipation Half hour of crocodiles etc constipation and inside number school the said number of which and inside number school the said number of which keeping our personality business stuffed idli idli keeping our personality business stuffed idli idli batter subscribe button maximum retail in is more that the said number 90 number one side someone subscribe to subscribe to a a a but when this 15 Avinash Dutt Mandir person must come subscribe with not forget to subscribe on Thursday and subscribe to not forget to subscribe on Thursday and subscribe to soon ok WhatsApp Twitter Solid Waste Plant soon ok WhatsApp Twitter Solid Waste Plant Money Problem Interview Money Problem Interview Subscribe that a hua hai
2024-03-21 18:40:29
401
https://i.ytimg.com/vi_w…xresdefault.webp
Binary Watch | Leetcode 401 | Bit Manipulation | coding interview problems | java | leetcode easy
0nhjhVv1VLs
hey guys how's everything going this is jayster in this video i'm going to solve jayster in this video i'm going to solve another another problem from lead code uh uh problem from lead code uh uh it's a one seven five three two check if it's a one seven five three two check if array is sorted and rotated array is sorted and rotated given an array nums return true if the given an array nums return true if the array was originally array was originally soared in a non-decreasing soared in a non-decreasing non-decreasing order non-decreasing order then the rotated then rotated some then the rotated then rotated some number position number position including zero otherwise return false including zero otherwise return false there might be duplicates in your there might be duplicates in your original array i see original array i see so because it's non-decreasing right so because it's non-decreasing right okay an array okay an array a rotated by x position results in array a rotated by x position results in array b of the same length such as b of the same length such as a i equals b i a i equals b i plus x mod by a to l where my module operation it's like three four five one two is this is original solid array and then rotate it by x three zero one zero hold it back here uh zx means i a uh so 0 means uh so 0 means nothing is changed right for nothing is changed right for multiply length so z okay wait a minute multiply length so z okay wait a minute so a move actually is means okay a i equals i move left right move left for uh i uh for uh some positions like okay so one move forward we'll move backward move backward for one position for two position for three position so three one two is here uh three four five is here great so let's do it so for the original array it's uh non-decreasing we could just check the item from uh with the previous one right see to see is if it is uh smarter than it if it is smarter then it's a downward slope so like like we have an array and we find a position to rotate it so it will be split it into two parts a b and c d right and then it be become c d and a and b this is the uh arguments we get so there are several conditions we need to uh find it map being matched it means c is not decreasing to d and a not decreasing to b and b is smaller or equal to c right so yeah this is it so how do we uh find this and find this uh it means that uh we the d a am i equal to d yeah so these kind of downward slope like turning point their maximum should be one right it's only one or zero because if it is zero positions then the array is totally the same as the original one so yeah so the uh the condition here actually could be uh summarizing to one the turning point turning point is maximum one if has turning point and b is must be not decreasing comparing to to c right yeah so this is it let's do it uh we loop through the numbers we compare it with previous ones so actually we start from uh one in x1 if num oh and we can keep track of the uh turning point uh like what is it let turning points zero okay if i is smaller atoms numbs i negative one it's not decreasing equalness is okay uh we increment the turning points count and if if there are over two turning points then we could just return right away it's it's not rotated okay and then at last we return that there if there's no turning points right or if there's one turning point and the the last one is comparing to the first number it should not be non-decreasing it should be non-decreasing it should be no no it should be non-decreasing yeah it should be yeah not decreasing uh returns nums uh nums.nth negative one it should be smaller or equal to nums zero right so this is it let's run the code looks great submit yeah passed so that's it it's pretty simple uh but actually i failed for the first time uh yeah i need to pay more attention especially for the zero uh zero positions stuff okay so this is it helps you next
2024-03-22 11:59:25
1,752
https://i.ytimg.com/vi/0…axresdefault.jpg
LeetCode 1752. Check if Array Is Sorted and Rotated | JSer - Front-End Interview questions
wtoNj0d-OEI
and welcome back to the cracking fang youtube channel today we're going to be youtube channel today we're going to be solving lead code problem 301 remove solving lead code problem 301 remove invalid parentheses invalid parentheses given a string s that contains given a string s that contains parentheses and letters remove the parentheses and letters remove the minimum number of invalid parentheses to minimum number of invalid parentheses to make the input string valid return all make the input string valid return all possible results you may return the possible results you may return the answer in any order let's look at an answer in any order let's look at an example say we're given this input here example say we're given this input here what would be our solution here well what would be our solution here well let's count the number of parentheses so let's count the number of parentheses so for the left we have one for the left we have one two two three left parenthesis for the right we three left parenthesis for the right we have one have one two three four so obviously there's a two three four so obviously there's a mismatch between the left and the right mismatch between the left and the right parentheses so obviously we can't get parentheses so obviously we can't get rid of left parentheses because then rid of left parentheses because then we'll just have even left less left we'll just have even left less left less left and we'd still have the same less left and we'd still have the same amount of right so clearly the right amount of right so clearly the right parentheses are the ones that we need to parentheses are the ones that we need to remove remove so so as we can see there's this one right as we can see there's this one right parenthesis which is oops let me change parenthesis which is oops let me change my color here so you can actually see my color here so you can actually see this this and we'll use green so there's this one and we'll use green so there's this one right parenthesis which is invalid right parenthesis which is invalid because it doesn't have a corresponding because it doesn't have a corresponding left parenthesis so we could remove it left parenthesis so we could remove it and then we'd get this as one answer so and then we'd get this as one answer so this would be closed so this is one this would be closed so this is one potential answer potential answer or or what we could do is we could remove one what we could do is we could remove one of the left that comes before it of the left that comes before it so for example we could remove so for example we could remove um um let's see one of these left ones or let's see one of these left ones or sorry one of these right ones sorry one of these right ones we don't necessarily have to remove this we don't necessarily have to remove this right one it could be one of the ones right one it could be one of the ones earlier so we could remove this one and earlier so we could remove this one and we'd get you know left left and then the we'd get you know left left and then the two rights right right and then closed two rights right right and then closed and that would be a valid answer and and that would be a valid answer and obviously in this case we've removed obviously in this case we've removed just one parentheses from both of these just one parentheses from both of these right in the first case we removed this right in the first case we removed this one here one here this first one this first one and then in the second one i believe we and then in the second one i believe we removed this one so in both those cases removed this one so in both those cases we just removed one obviously we could we just removed one obviously we could just remove every single parentheses but just remove every single parentheses but we're looking for the minimum number we we're looking for the minimum number we need to remove so obviously that's not a need to remove so obviously that's not a good answer because we'll just end up good answer because we'll just end up removing everything removing everything so the way that we're going to solve so the way that we're going to solve this is actually using a backtracking this is actually using a backtracking dfs dfs and what we're going to do is we're and what we're going to do is we're going to start going to start at the beginning of the string and we're at the beginning of the string and we're going to go to the left oh sorry to the going to go to the left oh sorry to the from left to right and what we're going from left to right and what we're going to do is that every iteration to do is that every iteration we're going to make a decision of we're going to make a decision of whether or not we want to take the whether or not we want to take the current parentheses or leave it current parentheses or leave it those are our two options right we can those are our two options right we can either take the current parentheses or either take the current parentheses or we can ignore it if it's going to be we can ignore it if it's going to be invalid so invalid so you know with other parentheses problems you know with other parentheses problems that we've done before we know that okay that we've done before we know that okay if you know the left count is actually if you know the left count is actually less than the right count or equal to it less than the right count or equal to it then that means that we're not allowed then that means that we're not allowed to take any right parentheses because to take any right parentheses because that would be invalid and there's no that would be invalid and there's no possible left parentheses that could possible left parentheses that could close a right parenthesis if we took it close a right parenthesis if we took it if this statement is true so we can do if this statement is true so we can do some sort of validation as we go to some sort of validation as we go to basically make sure that our right basically make sure that our right parentheses don't ever parentheses don't ever exceed the left parenthesis before it so exceed the left parenthesis before it so we can make sure that when we get to a we can make sure that when we get to a right parenthesis we can do that check right parenthesis we can do that check and that means that we'll need to keep and that means that we'll need to keep track of our left parentheses count and track of our left parentheses count and our right parentheses count our right parentheses count as we're going we don't know when we see as we're going we don't know when we see a left parenthesis whether or not we're a left parenthesis whether or not we're going to see a right parenthesis later going to see a right parenthesis later that can close it so we're going to take that can close it so we're going to take all left parentheses greedily and we're all left parentheses greedily and we're also going to ignore it in the case that also going to ignore it in the case that you weren't allowed to take it because you weren't allowed to take it because we're not going to be able to go back we're not going to be able to go back and remove things we're simply going to and remove things we're simply going to evaluate once we get to the end of the evaluate once we get to the end of the string does the left count equal to the string does the left count equal to the right count if it does then that means right count if it does then that means that we have found a valid parenthesis that we have found a valid parenthesis and and we can double check whether that answer we can double check whether that answer works so as we go from left to right works so as we go from left to right we're going to build our strings using a we're going to build our strings using a string builder and you know in a string builder and you know in a backtracking manner and what we're going backtracking manner and what we're going to do when we get to the end we're going to do when we get to the end we're going to say okay does left equal right if it to say okay does left equal right if it does then we want to look at the length does then we want to look at the length of our string right we want the minimum of our string right we want the minimum number of parentheses removed so we're number of parentheses removed so we're looking for the longest possible string looking for the longest possible string at the end such that left equals right at the end such that left equals right right because if we the longer it is right because if we the longer it is that means that we removed less items so that means that we removed less items so if our new string let's say its length if our new string let's say its length is five is five if that equals to the maximum length if that equals to the maximum length that we've seen so far for an answer that we've seen so far for an answer then we can add it to our answer add to then we can add it to our answer add to answer right answer right if actually 5 is greater than our answer if actually 5 is greater than our answer that we found so far then that means that we found so far then that means that everything in our last answer was that everything in our last answer was invalid and we need to reset our answer invalid and we need to reset our answer to be whatever this new length is five to be whatever this new length is five and then just add that string to it so and then just add that string to it so this is a little bit confusing i think this is a little bit confusing i think once we go to the code editor you'll see once we go to the code editor you'll see exactly what i mean and we'll walk by exactly what i mean and we'll walk by everything line by line this question everything line by line this question really isn't that complicated i think really isn't that complicated i think it's just a mishmash of backtracking it's just a mishmash of backtracking plus knowing how to work with plus knowing how to work with parentheses if this is confusing go parentheses if this is confusing go watch some of my other videos and this watch some of my other videos and this should explain how to work with should explain how to work with parentheses i've done a lot of questions parentheses i've done a lot of questions before this one is really no different before this one is really no different it just has that backtracking element to it just has that backtracking element to it so enough blabbing let's go to the it so enough blabbing let's go to the code editor and we're going to type this code editor and we're going to type this up it's actually really not that bad and up it's actually really not that bad and let's solve this question we're in the let's solve this question we're in the code editor let's type this up let me code editor let's type this up let me give us a little bit of extra room here give us a little bit of extra room here because we don't actually care about the because we don't actually care about the question prompt we just want to see the question prompt we just want to see the code so we need a few variables to help code so we need a few variables to help us with our solution like i mentioned we us with our solution like i mentioned we need to keep track of the longest string need to keep track of the longest string that we found so far that works as an that we found so far that works as an answer and we also need to find our um answer and we also need to find our um you know our solution set so we're going you know our solution set so we're going to say self.longest string and we're to say self.longest string and we're just going to set this equal to -1 this just going to set this equal to -1 this is going to be our initial value and is going to be our initial value and we're going to need some sort of result we're going to need some sort of result here and we're going to set this equal here and we're going to set this equal to a set um because we want the unique to a set um because we want the unique results we don't want to have duplicates results we don't want to have duplicates in our results and we don't really care in our results and we don't really care about the order so uh we can use a set about the order so uh we can use a set here to basically take care of any here to basically take care of any duplicates duplicates now remember that we need to do a now remember that we need to do a backtracking dfs so let's set that up backtracking dfs so let's set that up and we're going to call our dfs function and we're going to call our dfs function and we'll write this in a second but and we'll write this in a second but basically we're going to pass in the basically we're going to pass in the string string s we're going to s we're going to pass in the current index of our string pass in the current index of our string remember that we're going over the remember that we're going over the string from left to right so we need to string from left to right so we need to keep track of where we are we need to keep track of where we are we need to keep track of our current solution which keep track of our current solution which is just going to be a string builder so is just going to be a string builder so we're going to pass in an empty list we're going to pass in an empty list because obviously we don't have any because obviously we don't have any answer yet and remember that we need to answer yet and remember that we need to keep track of the left and right count keep track of the left and right count for the parentheses so those are going for the parentheses so those are going to both be 0 because we haven't done any to both be 0 because we haven't done any processing and we're going to call the processing and we're going to call the dfs function with those initial dfs function with those initial arguments and at the end all we need to arguments and at the end all we need to do is return do is return self.res self.res so sounds easy but now it's actually so sounds easy but now it's actually time to write the dfs function time to write the dfs function so let's define the function arguments so let's define the function arguments and we just talked about them so the and we just talked about them so the first argument is obviously going to be first argument is obviously going to be the string that we're working with the string that we're working with second argument is going to be the second argument is going to be the current index the third argument is current index the third argument is going to the current result which is going to the current result which is going to represent the string builder of going to represent the string builder of uh the result that we're building as we uh the result that we're building as we go through the backtracking and then we go through the backtracking and then we have our left count and we also have our have our left count and we also have our right count so those are going to be our right count so those are going to be our function arguments function arguments now now obviously this is a backtracking dfs and obviously this is a backtracking dfs and we don't want our recursion to go on we don't want our recursion to go on forever it has to end at some point so forever it has to end at some point so what is the endpoint the endpoint is what is the endpoint the endpoint is actually going to be when our current actually going to be when our current index is greater than or equal to the index is greater than or equal to the length of the string because that means length of the string because that means that we have exhausted all the possible that we have exhausted all the possible indices of our string so at this point indices of our string so at this point we need to evaluate whether or not we we need to evaluate whether or not we actually have a solution so we're going actually have a solution so we're going to say if current index is greater than to say if current index is greater than or equal to the length of the string or equal to the length of the string now what we need to do is check whether now what we need to do is check whether or not our solution is valid and because or not our solution is valid and because we're going to be validating whether or we're going to be validating whether or not we're taking not we're taking a correct left or right parenthesis as a correct left or right parenthesis as we go at the end all we need to do is we go at the end all we need to do is check whether the left count equals the check whether the left count equals the right count because that means that we right count because that means that we will have removed invalid parentheses as will have removed invalid parentheses as we've gone through our solution and we've gone through our solution and you'll see how we do that in a second you'll see how we do that in a second this is really just building out the this is really just building out the solution so we're going to say if the solution so we're going to say if the left count is equal to the right count left count is equal to the right count what we want to do now is check whether what we want to do now is check whether or not we have a better solution or not we have a better solution remember that we're looking for the remember that we're looking for the minimum that we have to remove right minimum that we have to remove right remove the minimum number of invalid remove the minimum number of invalid parentheses right we could just parentheses right we could just literally remove all the parentheses and literally remove all the parentheses and that would technically be a valid string that would technically be a valid string but that's not the minimum remove so we but that's not the minimum remove so we want to make sure that our answer is want to make sure that our answer is actually the best answer that we can get actually the best answer that we can get and the way that we're going to do this and the way that we're going to do this is we're going to check whether or not is we're going to check whether or not our current result its length our current result its length is actually longer than the best answer is actually longer than the best answer that we have so far that we have so far because that means that we actually because that means that we actually removed less parentheses and that where removed less parentheses and that where therefore we have a better answer therefore we have a better answer so our previous answer is no longer so our previous answer is no longer valid so we need to actually overwrite valid so we need to actually overwrite it so we're going to now say it so we're going to now say if the length of the current if the length of the current result result is actually greater than self.longest is actually greater than self.longest string so now we have a better answer we string so now we have a better answer we need to set our need to set our new longest string to be the length of new longest string to be the length of whatever the current result is and we whatever the current result is and we need to reset our result right need to reset our result right so whatever result we had before is no so whatever result we had before is no longer valid because we now have a longer valid because we now have a better solution so we're going to reset better solution so we're going to reset the result to an empty set and we're the result to an empty set and we're going to add to it going to add to it our new result which is this current res our new result which is this current res but obviously it's a string builder so but obviously it's a string builder so we actually need to join it together so we actually need to join it together so we're going to say we're going to say string.join and we're going to add the string.join and we're going to add the current result so that's the case where current result so that's the case where the current result is actually greater the current result is actually greater than our best result so far we could than our best result so far we could also have the case that our current also have the case that our current result is equal to the best result that result is equal to the best result that we have so far which means that we we have so far which means that we simply need to add our string to this simply need to add our string to this result set because it's another valid result set because it's another valid answer so what we're going to do is answer so what we're going to do is we're going to say else if the length of we're going to say else if the length of the current result is equal to the current result is equal to self self the longest string the longest string now what we want to do is we just want now what we want to do is we just want to add the answer to it so we're going to add the answer to it so we're going to say self.res.ad to say self.res.ad and then we're going to join our and then we're going to join our stringbuilder here to get our string stringbuilder here to get our string because remember we're returning the the because remember we're returning the the actual string not the string builder so actual string not the string builder so we're going to say join keras we're going to say join keras and that's how we basically and that's how we basically uh take care of the case when we process uh take care of the case when we process the entire string otherwise if we the entire string otherwise if we haven't processed the entire string then haven't processed the entire string then we actually need to do our processing we actually need to do our processing so let's get whatever the current value so let's get whatever the current value is at the current index so we're going is at the current index so we're going to say the current character is going to to say the current character is going to be string of cur index be string of cur index so remember that there's three values it so remember that there's three values it can take right our string can contain can take right our string can contain parentheses and letters if it's a letter parentheses and letters if it's a letter we don't do anything we just take them we don't do anything we just take them and we continue we can't not take the and we continue we can't not take the letters we just ignore them and we just letters we just ignore them and we just add them to the string builder and move add them to the string builder and move on we only want to you know make a on we only want to you know make a decision of whether to take or not to decision of whether to take or not to take in the case that we don't have in take in the case that we don't have in the case that we have a left or right the case that we have a left or right parenthesis strings characters always parenthesis strings characters always get taken get taken so we're going to say so we're going to say if the current character is actually a if the current character is actually a left parenthesis left parenthesis we don't know whether or not the left we don't know whether or not the left parentheses will ever be closed after it parentheses will ever be closed after it so we can't not take it because it could so we can't not take it because it could be the case that we needed it be the case that we needed it but we could actually but we could actually accidentally take it so what we're going accidentally take it so what we're going to do is we're going to have two things to do is we're going to have two things we do here right we're going to take the we do here right we're going to take the current character current character and we're also not going to take it so and we're also not going to take it so we're gonna do two backtracking one we're gonna do two backtracking one where we take it and one where we don't where we take it and one where we don't take it so let's do the one where we take it so let's do the one where we take it first so we're gonna say take it first so we're gonna say currentres.pend currentres.pend so we're gonna add it to our so we're gonna add it to our stringbuilder so we're gonna add the stringbuilder so we're gonna add the current character and then we're gonna current character and then we're gonna go into our back tracking so we're going go into our back tracking so we're going to call self.dfs it's our string our to call self.dfs it's our string our current index obviously we're going to current index obviously we're going to move the index up by one our current move the index up by one our current result result now we've taken a left parenthesis so we now we've taken a left parenthesis so we need to increment our left count oops need to increment our left count oops left count by one and we need to keep left count by one and we need to keep our right count the same obviously it our right count the same obviously it stays the same and now once that stays the same and now once that finishes we'll exit from the back finishes we'll exit from the back tracking and remember that tracking and remember that typical backtracking since we added it typical backtracking since we added it to our result we now need to remove to our result we now need to remove itself oops not this isn't itself this itself oops not this isn't itself this should be should be pop yeah cares.pop pop yeah cares.pop so that's the case where we're taking it so that's the case where we're taking it and then we also need to go through the and then we also need to go through the backtracking where we actually ignore backtracking where we actually ignore this current left parenthesis so we're this current left parenthesis so we're not going to add anything to our not going to add anything to our stringbuilder because obviously we're stringbuilder because obviously we're ignoring it so we're simply just going ignoring it so we're simply just going to call the backtracking function with to call the backtracking function with our string we're going to move the in our string we're going to move the in we're going to move the index up by i we're going to move the index up by i index up by one we're going to pass in index up by one we're going to pass in the current result oops current res oh the current result oops current res oh geez i can't type today geez i can't type today l count hasn't changed because we're l count hasn't changed because we're ignoring the left parenthesis and ignoring the left parenthesis and obviously right count hasn't changed obviously right count hasn't changed because we're not even working with the because we're not even working with the right parentheses so there's no reason right parentheses so there's no reason it should have cool so that's the case it should have cool so that's the case where we have a left parenthesis what where we have a left parenthesis what about the case where we have about the case where we have where we have a right parenthesis so where we have a right parenthesis so we now have a right parenthesis we now have a right parenthesis and remember that there's two cases and remember that there's two cases again we can either ignore the right again we can either ignore the right parenthesis or we can take it so let's parenthesis or we can take it so let's do the case where we ignore it first do the case where we ignore it first because it's simpler so we're going to because it's simpler so we're going to say self.dfs so string all we're going say self.dfs so string all we're going to do is move the current index up by to do is move the current index up by one and we're going to pass in current one and we're going to pass in current res we're going to pass an l count and res we're going to pass an l count and right count right count easy peasy now when it comes to taking a easy peasy now when it comes to taking a right parenthesis remember that we can't right parenthesis remember that we can't take take right parentheses greedily because if we right parentheses greedily because if we have something like this or have something like this or is it going to autofill so if we have is it going to autofill so if we have something like this something like this right this is a balanced parenthesis right this is a balanced parenthesis right these two lefts are closed by right these two lefts are closed by these two rights but if we see another these two rights but if we see another right now we can't take this parenthesis right now we can't take this parenthesis because it doesn't matter what comes because it doesn't matter what comes after it we could have you know one after it we could have you know one million left parentheses they will never million left parentheses they will never close this one right that came before it close this one right that came before it right lefts can only close a right right lefts can only close a right parenthesis that comes after it so if parenthesis that comes after it so if this parentheses on the right is invalid this parentheses on the right is invalid then we can't take it then we can't take it because nothing will ever close it that because nothing will ever close it that right parenthesis needs to be closed by right parenthesis needs to be closed by a left that comes before it so what we a left that comes before it so what we need to do is we need to check that the need to do is we need to check that the left count is currently greater than the left count is currently greater than the right count because if it isn't that right count because if it isn't that means that that right parenthesis will means that that right parenthesis will never be closed and we can't take it so never be closed and we can't take it so we need to make sure that left count is we need to make sure that left count is strictly greater than the right count strictly greater than the right count otherwise it won't work so otherwise it won't work so if we have the case where we can take if we have the case where we can take the right parentheses we can basically the right parentheses we can basically do the same thing with the left do the same thing with the left that we did except for this time what's that we did except for this time what's going to be with the right so we're going to be with the right so we're going to say current res thought append going to say current res thought append we're going to take the current char we're going to take the current char we're going to say self.dfs we're going to say self.dfs string obviously the current index moves string obviously the current index moves up by one we're going to pass in the up by one we're going to pass in the current res left count stays the same current res left count stays the same except this time the right count gets except this time the right count gets incremented by one once that dfs incremented by one once that dfs finishes then we can say currentres.pop finishes then we can say currentres.pop so we're going to pop from that and so we're going to pop from that and we're good to go we're good to go cool so that's the case where we have cool so that's the case where we have the right parentheses so we've handled the right parentheses so we've handled the left and the right and now i'll the left and the right and now i'll remember that we can have like english remember that we can have like english letters in here and in that case we just letters in here and in that case we just need to take it add it to the string need to take it add it to the string builder and continue moving on so we builder and continue moving on so we have to take all of our uh right and all have to take all of our uh right and all of our letters of our letters so what we're going to do is we're just so what we're going to do is we're just going to say kerres.pen whatever the going to say kerres.pen whatever the current character is current character is uh we're going to say self.dfs we're uh we're going to say self.dfs we're going to go past the string in obviously going to go past the string in obviously we're going to pass curindex we're going to pass curindex plus one plus one uh plus one we're gonna say kurez uh plus one we're gonna say kurez obviously and then left count hasn't obviously and then left count hasn't changed changed and right count and right count right count hasn't changed right count hasn't changed and once we exit added this dfs all we and once we exit added this dfs all we need to do is remember this is a need to do is remember this is a backtracking so we need to get rid of it backtracking so we need to get rid of it so we simply say cares dot pop so we simply say cares dot pop so so that is what we do there that is what we do there and actually i don't think we even need and actually i don't think we even need this karez.pop because we always keep this karez.pop because we always keep the letters so we can actually just the letters so we can actually just leave that out leave that out uh uh there we go so let me just run this make there we go so let me just run this make sure i haven't made any bugs because sure i haven't made any bugs because it's quite a lot of code and i can catch it's quite a lot of code and i can catch it now okay let me submit it and it now okay let me submit it and hopefully this works hopefully this works and this is a long one um because and this is a long one um because there's a lot of there's a lot of test cases oh okay so i think we test cases oh okay so i think we actually do need that uh kerrez.pop to actually do need that uh kerrez.pop to make the backtracking correct so let me make the backtracking correct so let me just add that back in just add that back in and okay cool yeah okay nevermind it turns out we didn't need that all right uh anyway so that is how you solve this problem let us think about the time and space complexity so obviously this is a backtracking question and most backtracking questions are exponential uh run times right and the x the the base for our exponential runtime is going to depend on how many things we can possibly do at each iteration of the backtracking so let's think about the worst case scenario here which is that our string that we're given is all left parentheses so the reason that this is the worst case is that because when we have something that's all left parentheses every single time we go into the backtracking we're always going to take the left parenthesis and we're always going to ignore it which means that there's two things that we could potentially do right if it's all right parentheses then we have you know one for sure that we do and then potentially two but we're not guaranteed to go into this block here so you know at a minimum we would do one same with if it was just all english characters it would just be one thing that we do each time but with left parentheses we always take it and we always ignore it which means that there's two things we can do each time and obviously there's n characters in our um string so that means that we have two to the n basically um operations so our time complexity here is going to be two to the n so our space complexity here is going to be big o of n and the reason for this is well we need to store our um you know our solution which you know could potentially just be the string that we're given if the string there's actually no characters that we need to remove then we're just going to end up storing the string in our result and then also each backtracking will finish you know itself before actually going to the next one so that depth is going to be big o of n because there's only n iterations we could possibly do so that is your time and space complexity for this algorithm just going over it again it's two to the n for the time because there's in the worst case our string is all left parentheses and we would have to do two operations at each of the n you know iterations through our back tracking so that's why it's two to the n and then for the space we have big o of n so that is how you solve this question not exactly the most complicated one is quite a lot of code to write and you know handling some of these cases can be a bit tricky but if you've seen you know your back tracking questions before it's really not that bad i think it's pretty straightforward uh how you actually solve this one you just have to have done a few parentheses ones and just be familiar with backtracking but otherwise like even if you haven't seen it before like this this solution is pretty easy to memorize i haven't done this question in you know forever when was the last time i touched it in what is this like november and i it's what is it june now and i basically have it memorized so uh yeah this one's not really that hard anyway i'm gonna stop blabbering that's how you solve this problem lee code 301 remove invalid parentheses if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this please subscribe to the channel i have a ton of videos already uploaded and i plan to make a whole lot more so subscribe to the channel and also leave in the comment section below what questions you want to see and i will add them to my work queue otherwise thank you so much for taking the time to watch
2024-03-24 09:59:00
301
https://i.ytimg.com/vi/w…axresdefault.jpg
REMOVE INVALID PARENTHESIS | LEETCODE # 301 | PYTHON BACKTRACKING SOLUTION
Pdgg7eIGb2U
welcome to july's lee code challenge this problem is called decode ways 2. this problem is called decode ways 2. a message containing letters from a to z a message containing letters from a to z can be encoded into numbers using the can be encoded into numbers using the following mapping following mapping a is 1 b is 2 z is 26. a is 1 b is 2 z is 26. to decode an encoded message all the to decode an encoded message all the digits must be grouped together digits must be grouped together uh or grouped then mapped back into uh or grouped then mapped back into letters using the reverse of the mapping letters using the reverse of the mapping above above so aajf with a grouping of one one ten so aajf with a grouping of one one ten six six and kjf with eleven ten six so notice and kjf with eleven ten six so notice how how this string here can be mapped two this string here can be mapped two different ways different ways so in addition to the mapping above an so in addition to the mapping above an encoded message may contain encoded message may contain a uh what is this a star a uh what is this a star character which can represent any digit character which can represent any digit from one to nine from one to nine zero is excluded so that's nice because zero is excluded so that's nice because zero would overcome zero would overcome complicated even more but but for complicated even more but but for example if we had example if we had one star this could be represented by one star this could be represented by one one one two one three all the way to one one one two one three all the way to 1 9 1 9 so that means whatever you want whatever so that means whatever you want whatever we have to figure out how many ways we we have to figure out how many ways we can decode this can decode this okay so there's a decode ways problem okay so there's a decode ways problem one which is a pretty classic problem one which is a pretty classic problem which i found very complicated but which i found very complicated but i basically went with that approach and i basically went with that approach and you can see you can see this was my solution and i did this was my solution and i did eventually get it to work eventually get it to work um it took a lot of submissions and a um it took a lot of submissions and a lot of lot of edge cases i had to take care of but edge cases i had to take care of but after i after i finished solving it i realized i had no finished solving it i realized i had no idea what i'm doing like this idea what i'm doing like this is not something i could really explain is not something i could really explain so that was a terrible approach so that was a terrible approach don't do what i did this is not a good don't do what i did this is not a good idea idea let's look at some of my code though and let's look at some of my code though and see if we can figure out some insights see if we can figure out some insights and then i'll go through a solution that and then i'll go through a solution that i thought was the most clever i thought was the most clever um so one of the one of the things we um so one of the one of the things we realize here is if it's a star realize here is if it's a star um we basically have to take our um we basically have to take our number of waves that we decoded in our number of waves that we decoded in our dp array so say that we had like dp array so say that we had like uh one star something like that uh how uh one star something like that uh how many ways can we decode one here we many ways can we decode one here we already know that's going to be one already know that's going to be one right right now what about what about here at the now what about what about here at the very least very least there's gonna be nine ways we can decode there's gonna be nine ways we can decode that so we have to multiply that so we have to multiply however many many ways we decoded here however many many ways we decoded here with at least nine with at least nine so that would be one times nine so this so that would be one times nine so this would be nine but would be nine but keep in mind we also need to think about keep in mind we also need to think about well what about well what about the ways that we can decode to like 11 the ways that we can decode to like 11 12 13 like those are all extra 12 13 like those are all extra ways that we can decode so because of ways that we can decode so because of that that uh depending on whether this is a one or uh depending on whether this is a one or a a two we have to uh if it's a one we have two we have to uh if it's a one we have to add to add another um basically another um basically multiply nine times however many ways we multiply nine times however many ways we decoded when it was a one here so that's decoded when it was a one here so that's still a one so this would just be nine still a one so this would just be nine times times one here but if this was a nine times one here but if this was a nine times one like this one like this but this was a two that'd be different but this was a two that'd be different because we don't have nine ways we can because we don't have nine ways we can do that we can't do do that we can't do we can't code 29 but we can encode 26 we can't code 29 but we can encode 26 here here as well as like two six right two and as well as like two six right two and six like this six like this so how many ways are there is up to so how many ways are there is up to twenty one twenty two twenty three twenty one twenty two twenty three twenty four twenty five six six twenty four twenty five six six so if this was a two uh this would be so if this was a two uh this would be actually six actually six there'd be six ways now things get even there'd be six ways now things get even more complicated if more complicated if if there's like an extra star here if if there's like an extra star here if there was an extra star there was an extra star uh we have to actually keep track of uh we have to actually keep track of both those two ways both those two ways because we know one and two are both because we know one and two are both possible so not only do we have to possible so not only do we have to multiply multiply whatever value we had here this would be whatever value we had here this would be what 15 what 15 we have to multiply that by nine but now we have to multiply that by nine but now we have to also multiply we have to also multiply um the nine ways that we had um the nine ways that we had right there so we have to do what 15 right there so we have to do what 15 times 9 and then we also have to add i times 9 and then we also have to add i think it's going to be 15 think it's going to be 15 times 9 plus 15 times 6 i believe right times 9 plus 15 times 6 i believe right and i put that and i put that somewhere here i believe it's something somewhere here i believe it's something like this and notice how in this dpoa like this and notice how in this dpoa we're looking back we're looking back two spaces and the reason for that is two spaces and the reason for that is like like like at this point here uh just just like at this point here uh just just imagine that we have like i don't know imagine that we have like i don't know some values some values two three uh once we get to like one two three uh once we get to like one if we i don't know what these values are if we i don't know what these values are here but once once we get like let's say here but once once we get like let's say this was a hundred this was a hundred um and now we have nine we know we have um and now we have nine we know we have to multiply this by 900 to multiply this by 900 but we also want to know okay how many but we also want to know okay how many ways were there to decode here ways were there to decode here okay because we have nine other ways to okay because we have nine other ways to decode from this point so we have to add decode from this point so we have to add plus nine whatever this value is here so plus nine whatever this value is here so that's kind of like two states that's kind of like two states we have if this character is a one or a we have if this character is a one or a two we need to keep track of that two we need to keep track of that previous one previous one in case next time it's a star so if when in case next time it's a star so if when that happens we have to keep track of that happens we have to keep track of that that so that's kind of the key insight that i so that's kind of the key insight that i want to kind of dig in but otherwise i want to kind of dig in but otherwise i realize my realize my the way i'm going to solve this right the way i'm going to solve this right now isn't going to make much sense now isn't going to make much sense but i think if i want to really go deep but i think if i want to really go deep into this just take too long into this just take too long so what we'll do is we'll just go with so what we'll do is we'll just go with first creating a dp array okay and first creating a dp array okay and this dp array is going to contain this dp array is going to contain three things the first thing is going to three things the first thing is going to be the number of ways that we could be the number of ways that we could decode decode uh regardless of whether it was a one or uh regardless of whether it was a one or two okay so the previous two okay so the previous the previous dp value essentially so the previous dp value essentially so very first we'll start with one very first we'll start with one now these two values here are going to now these two values here are going to represent represent uh we're going to store one thing uh we're going to store one thing previous in case this character is a one previous in case this character is a one or a two so or a two so this second position if if the last this second position if if the last character was a one we're gonna keep character was a one we're gonna keep track of whatever the previous track of whatever the previous dp was in case we see a star and we want dp was in case we see a star and we want to figure out hey was the previous one to figure out hey was the previous one and one and one if it was we need to also multiply that if it was we need to also multiply that and same thing here that's going to be and same thing here that's going to be representing a 2. it's going to be 1 representing a 2. it's going to be 1 this will be a 2. this will be a 2. i'll show you what i mean so we'll say i'll show you what i mean so we'll say 4c in 4c in string there's going to be two main string there's going to be two main cases that we have to take care of cases that we have to take care of first i'm going to create a temporary dp first i'm going to create a temporary dp array here and if array here and if c equals star a couple things here so in the beginning this would be what we'll start with 000. so temp zero at this point we will take our dp of zero and we'll multiply it by nine we'll also take our dp of 1 and add that and we have to also multiply that by 9 and take our dp of 2 right here and i think we have to multiply this by okay now temp one this okay now temp one this since this is a star that means a one since this is a star that means a one and two are both possible so we just and two are both possible so we just need to store these two here need to store these two here in case the next one comes up now in case the next one comes up now otherwise otherwise uh this is where it gets complicated uh this is where it gets complicated let's see let's see so temp kind of doing the same thing at so temp kind of doing the same thing at this point but we will this point but we will uh take our dp of zero uh take our dp of zero but we we need to see if our character but we we need to see if our character is is um basically we need to make sure it's um basically we need to make sure it's not a zero here not a zero here if it's a zero it kind of changes if it's a zero it kind of changes changes things up we changes things up we if it's a zero we have to only take the if it's a zero we have to only take the values here with values here with one and two because remember if this one and two because remember if this value is a zero value is a zero uh if we had like one one zero like if uh if we had like one one zero like if the previous value was a nine or seven the previous value was a nine or seven this wouldn't be possible we have we this wouldn't be possible we have we have to have to assume that one and two came before that assume that one and two came before that otherwise there's nothing to add here so otherwise there's nothing to add here so that's why we have these two states so that's why we have these two states so what we'll say is c is greater than we can just use character 0 like this and we multiply that so as long as it's greater than 0 it's going to be 1 so we'll multiply that by dp 0. let's see and also we'll need to like the previous dp of one right here that as well as uh dp of two that is if the character is less or equal to six okay so c has to be less or equal to and we multiply that okay so now temp one is equal to one then we'll just multiply is equal to one then we'll just multiply that by t p that by t p of zero right here and temp two of zero right here and temp two if character is equal to if character is equal to two then we'll multiply that by dp of zero i guess so this isn't really like multiplying it really it's just uh if it's not a one it's going to be zero if it's a one then we store it if it's a two we store it so that's really all it is and make sure to now make dp equal to temp and actually uh i think in order to get this to pass we have to do a modular here so seven and i guess we can say i mod for i n tip now finally once we get out here we just now finally once we get out here we just return our dp and the first value so return our dp and the first value so um i hope i got this let's see if this um i hope i got this let's see if this works okay um i'm going to put in a couple test cases here okay it looks like it's working so it's okay it looks like it's working so it's going to submit it and there we go all right so this is much cleaner clearly and it's going to be a of n time complexity and of one space it's constant space because this would be just this and that so this is the best solution that i saw um you can certainly go my approach and do all those crazy efl statements you know it actually seemed to work a little bit faster but ultimately i hated the approach because i started to lose track of exactly what i was doing but this works i don't fully understand it i'll admit but um yeah hopefully you get the decent idea and you can start you know playing around with it yourself so okay thanks for watching my channel
2024-03-20 14:28:14
639
https://i.ytimg.com/vi/P…2U/sddefault.jpg
Leetcode - Decode Ways II (Python)
DjOU6ohtJ7o
hey hey everybody this is larry this is day 23 of the leeco day challenge hit day 23 of the leeco day challenge hit the like button to subscribe on drum and the like button to subscribe on drum and discord let me know what you think about discord let me know what you think about today's problem today's problem problem problem i have gotten comments recently about my i have gotten comments recently about my mic being too low um i'm checking the mic being too low um i'm checking the levels and it does seem a little low levels and it does seem a little low i don't know what to make of it but um i don't know what to make of it but um yeah let me know what you think in the yeah let me know what you think in the comments whether the comments whether the the sound level is good enough i always the sound level is good enough i always find it okay but i always also max to find it okay but i always also max to the sound whenever i listen to stuff the sound whenever i listen to stuff which is maybe a bad habit so let me which is maybe a bad habit so let me know anyway today's prom is 630 know anyway today's prom is 630 course schedule three okay so the end course schedule three okay so the end courses from one to n you're given courses from one to n you're given courses duration and last day courses duration and last day that i of course could be that i of course could be and must finish the last day okay and must finish the last day okay the maximum number of courses that i can the maximum number of courses that i can take uh take uh oh god so this is a hard problem or i mean like it's classified as hard um already i so one is i feel like i really have some idea about this but i don't remember how to do it so you know it's move um [Music] the second thing is that i have a feeling it's greedy but i think this is why i don't really like the current format of of you know these weekly themed things is that you know i kind of have already have like a preconceived notion of how to solve it um only just because i know that it is uh heap week or maybe greedy week depending how you want to phrase it and as a result i'm like yeah you know maybe it's just that right like where i would much rather i would much rather go into it without any bias of like hey it's a fresh problem it can be anything right so i think that makes it slightly easier and a little bit because i think this is a problem especially as i mentioned you know in previous greedy is one of my weaknesses and i greedy is one of my weaknesses and i appreciate any effort to kind of appreciate any effort to kind of practice greedy practice greedy but mostly because of the proofs i would but mostly because of the proofs i would have to at least in my head there are have to at least in my head there are ways about it but ways about it but but that's what i think right so but that's what i think right so okay so with all that being said let's okay so with all that being said let's think about this think about this um so the last day so are these sorted in any way so so are these sorted in any way so they're not sorted um the couple of ideas that i have and maybe they're related anyway my first idea is some sort of binary search i know i just said all that stuff about uh keep i mean maybe but there is a similar structure there so maybe there's something like that where where for every if i sort this by the last day right the input if i sort it by the last day then i'm thinking that okay if if for example just given a slice of um if the last day is 1300 how many um if the last day is 1300 how many things can i fit in right and in that things can i fit in right and in that case um i think in that case we would try to um i think in that case we would try to really choose really choose all the smaller classes or um all the smaller classes or um or the smaller courses that could fit or the smaller courses that could fit into 1300 right and what i mean by that into 1300 right and what i mean by that is that in a greedy kind of way let's is that in a greedy kind of way let's say we're given say we're given 1300 uh right then that means that we 1300 uh right then that means that we will only be able to fit one hundred and will only be able to fit one hundred and two hundred because inside the 300 units two hundred because inside the 300 units of time and it'll finish by then um and from that on basically doing variant there is just going from left to right from the number of time so i thought it may be binary search in that way but actually you just keep on building on right and as you so you the way that i think about it even though we spoiler alert we are going to use heap some of this because of how we talked about it but i think actually i think about this as a scanline algorithm right or sweep line algorithm if you will and my idea here is okay let me let me do some minor drawings because people always complain that i don't do enough drawing uh but also because i like i want to draw because uh because if it doesn't make sense to draw i'm not going to draw it just to whatever but but basically for example hmm is that where i can just copy and paste this because these are just numbers let's see if that works nope cannot paste it um so basically the idea is this right so this is why this is why okay this is a okay i could just use a okay this is a okay i could just use a straight line too straight line too but right and then the question is okay uh i don't want to draw all the input but you could kind of see that i'll just talk about the input and then we'll see right let me actually move this a little bit so i could see it on my screen um okay so for example you're given for your friends you're given the last day being 200 and it takes 100 day uh so this is let's call it uh okay this is d for duration and the other one is d for last day no that's terrible larry uh let's just say l and d right and you have another event and i'm sorting them you know before you so you know on the last day so let's say the next one is 1250 1300 1300 200 200 and then 3200 so these are just that's basically the so these are just that's basically the example one that i'm doing the idea here example one that i'm doing the idea here for me is that okay so you know we put for me is that okay so you know we put these numbers on the number line let's these numbers on the number line let's just say this is here this is here-ish just say this is here this is here-ish this is very hand you know but uh this is very hand you know but uh something like that right say um something like that right say um okay okay so then the idea is that going from oops so then the idea is that going from oops going from left to right i can't even draw a straight line okay straighter um going from left to right let's say 200 right well now we know that we used a hundred of these right in terms of unit let's say we go to a thousand well now we use a thousand um oops what the hell what happened here i think maybe i have a bun home why is it so weird okay uh anyway sorry friends technical difficulties so 100 and a thousand roughly speaking right um and then now so that now we can do both events before 1250 and now we look at 1300. 1300 we could do 200 does that fit actually no yeah actually it fits exactly something like magnetic interference or something like magnetic interference or something i think so weird okay something i think so weird okay actually this is a wait is that true actually this is a wait is that true maybe i did the math well one hundred one thousand thirteen hundred right so why is oh well two thousand is the one that doesn't fit okay and then now we have 2000 and obviously it doesn't fit so this is actually a terrible example sorry friends but let me just rewrite some of these real quick um but the idea that i wanted to convey was this is a terrible example but let's say we have something like this right let's say this is the first box this is the second capacity because in a greedy kind of way you always want to take it near the beginning and then now let's say in the dirt box it's re it's too long well what happens well now we know that we cannot fit three classes right so let's say we get rid of one well which one do you want to get rid of in a greedy way you always want to get rid of the most expensive class in terms of time so it'll be this one but let's if it was like this if this is really if it was like this if this is really long and this is just a little bit more long and this is just a little bit more then of course you get rid of the middle then of course you get rid of the middle one right so this is greedy in a way and one right so this is greedy in a way and of course of course that that's greedy and part of that that that's greedy and part of that greedy is yeah so that that that's the greedy part of it and and part of the greedy implementation is what you're doing what are you asking all the time and what you're asking all the time is get remove the max element and what happens when you want to remove the max element use a heap to get the max element every time or repeatedly right so that's basically the idea and then it becomes bookkeeping after that um and what i mean by bookkeeping is just keeping track of numbers and so forth and we'll see in a second so if you if you're if i'm a little bit unclear well we'll be okay alrighty um by the finish time so that we can go from left to right as we said and then and then now we just do for what was it a duration and last day in courses uh of course we have to set up our heap and here we again just like yesterday we want the max heap right because we only repeatedly get the max number so let's also the way that i i i think i like to do it this way a little bit better but but you feel free to do whatever you like at home um and the way that i i said this yesterday and i feel like i've said this something a few times today or this week rather um the way the reason is because in python it's a min heap in a lot of languages you actually get a maxi by default but in python it's a min heap so then to get the max we just take a negative of every popular possible number uh input um and then you know return it and keep it consistent which is why i have some abstraction here because then now i don't have to worry about it later on or if it's typo i can fix it in one place instead of many places so okay so then now we also want to keep track the total and this is just the sum of all the numbers that are in the heap which are all the courses we took uh and maybe our best thing um to just keep track of best in case we need it i think this but i think this is monotonically increasing so i i cuz so the two things my one thing i want to say is that especially if i'm on a competitive you know like a contest i sometimes do things that i do things in a way that i don't have to prove uh meaning that in this case every time i add a thing it should be monotonically increasing because at the worst case you will just get rid of the course that you just got and then you have the same amount of courses as before so in that case we actually don't have to but i would say like but i would also like if i was in a competition i would maybe like i'll be like oh i don't want to prove that i would just have to do something like this after everything and even though this is my time like this h should be monotonically increasing i would just keep keep it like this because then i don't have to worry about you know i don't have to worry about anything really right like i just i just know that in a way it is like a brute force and that i check it every time so i don't have to worry about it but in this case we actually don't need to do it because everything in the heap will be the classes we take so we should be good um and here we go okay let's um let's sign let's try to sign up for this class right so then total we sign up for the duration uh heap we push d yeah and then now we go okay is total uh the last day right uh the last day right because if this is if the total is because if this is if the total is greater than last day that means that greater than last day that means that your current set of classes will go past your current set of classes will go past the last day so that's no bueno and then the last day so that's no bueno and then you pop and of course some someone in you pop and of course some someone in the comments will be like oh this can the comments will be like oh this can actually be an if statement because of actually be an if statement because of the invariant that we set the invariant that we set so but so but yeah i'm okay you know it's fine yeah i'm okay you know it's fine i like my get a while because then here i like my get a while because then here we can prove that the invariant is true we can prove that the invariant is true afterwards if i do something here afterwards if i do something here um then i know that the invariant is um then i know that the invariant is true and it just again i think i said true and it just again i think i said this yesterday as well just fewer things this yesterday as well just fewer things to prove right um but yeah i think to prove right um but yeah i think that's oh and here while we pop we that's oh and here while we pop we remove remove that from the total obviously otherwise that from the total obviously otherwise it would just be an infinite loop let me it would just be an infinite loop let me give it a quick spin and then see how give it a quick spin and then see how that goes that goes uh yeah maximum number of courses right uh yeah maximum number of courses right oh i i think i made the same mistake oh i i think i made the same mistake yesterday yesterday heap heap syntax in python is just very awkward syntax in python is just very awkward but yeah okay that's pretty much but yeah okay that's pretty much hopefully that's the idea let's give it hopefully that's the idea let's give it some minute of oh i got one as a choice some minute of oh i got one as a choice last time hopefully this time i don't last time hopefully this time i don't yes who why did i get one into twice yes who why did i get one into twice last time 814 day streak uh yeah so if last time 814 day streak uh yeah so if you want to look at complexity this is you want to look at complexity this is actually straightforward for space we actually straightforward for space we only have h only have h and h is of course and h is of course um um [Music] [Music] uh what i was going to say this is just uh what i was going to say this is just of n right and because we have a sword of n right and because we have a sword this is o n log n but after that this is o n log n but after that this will be also o of n log n right i this will be also o of n log n right i suppose because this thing can have n suppose because this thing can have n elements um so yeah so n log n time elements um so yeah so n log n time and and like oh sorry linear space and and like oh sorry linear space is the the idea behind this one um is the the idea behind this one um that's pretty much what i have i'm going that's pretty much what i have i'm going to take a look in the past larry to see to take a look in the past larry to see why he got why he got the wrong answer the wrong answer oh it seems like i did the same i don't know why just as well but i did do this thing that i was talking yesterday uh even i guess i'm doing factor into i think i i guess i'm doing factor into i think i made this i think the mystic that's here made this i think the mystic that's here is the same mistake that i'm oh i did it is the same mistake that i'm oh i did it by duration i did greedy by duration by duration i did greedy by duration does that work does that work i don't know that that works so maybe i don't know that that works so maybe that's what's wrong did i is that the that's what's wrong did i is that the fixed data and then i fixed data and then i sorted again but by the other direction sorted again but by the other direction i did i tried to greedy by the other i did i tried to greedy by the other direction direction and then at the way and and then at the way and i sorted by the finishing time which is i sorted by the finishing time which is what i did today and then it worked what i did today and then it worked but it also has some of the stuff that but it also has some of the stuff that we talk about just best human though we talk about just best human though it should be monotonically increasing it should be monotonically increasing but like i said fewer proofs so it's but but that also comes to wow it took me 17 minutes after the first two long and so i was very bad last time i ran on this but this time i feel like i did a bit better so thank you uh especially since most of it was explanation but but also show i just want to point out though like it's very easy to make greedy mistakes as you can see from last year maybe not this year you want to see those mistakes check it out and see how i can um improve on it but you know past larry i beat you one more time but though sometimes i don't and then i get sad anyway uh that's all i have for today let me know what you think stay good stay healthy take good mental
2024-03-20 14:16:35
630
https://i.ytimg.com/vi/D…axresdefault.jpg
630. Course Schedule III - Day 23/30 Leetcode June Challenge
nqdf23xVehs
hey friends welcome to the new episode of Kult was just and today we're going of Kult was just and today we're going to do lead code number 151 reverse words to do lead code number 151 reverse words English training if the input is the sky English training if the input is the sky is blue and alpha will be blue is sky is blue and alpha will be blue is sky and we can see the edge cases includes and we can see the edge cases includes the leading and trailing spaces and we the leading and trailing spaces and we need to delete all the actual spaces in need to delete all the actual spaces in between two words so before use this as between two words so before use this as example the result will be world so my example the result will be world so my approach is to reverse the stray and it approach is to reverse the stray and it will look like this will look like this and as we go through the list we reverse and as we go through the list we reverse each word and escape this spaces so I each word and escape this spaces so I have left pointer in the right pointer have left pointer in the right pointer if the left pointer is pointing to an if the left pointer is pointing to an empty space we move both pointers empty space we move both pointers forward like so if we see the left forward like so if we see the left pointer is pointing to a non empty pointer is pointing to a non empty character then we move the right pointer character then we move the right pointer until the red pointer hits in space that until the red pointer hits in space that means that we have a valid word so we means that we have a valid word so we reverse the word and put it to our reverse the word and put it to our result string after that we set the left result string after that we set the left pointer to the right pointers position pointer to the right pointers position and we check full of spaces again and and we check full of spaces again and again the left pointer riched to a non again the left pointer riched to a non space character then we move the right space character then we move the right pointer until it hits a space then we pointer until it hits a space then we reverse the string after that we set the reverse the string after that we set the left pointer to the right pointer and left pointer to the right pointer and keep moving towards the end of the keep moving towards the end of the stream and that's how we get the result stream and that's how we get the result however if we have this case and when however if we have this case and when the right pointer is pointing to the the right pointer is pointing to the last character of the string our loop last character of the string our loop ends so that makes us will have to check ends so that makes us will have to check after the iteration and see if we after the iteration and see if we reaching this scenario then we'll have reaching this scenario then we'll have to do the reverse again to do the reverse again now let's code this problem so before now let's code this problem so before everything I will check if the input is everything I will check if the input is valid if the string is null or it valid if the string is null or it doesn't have anything we return itself otherwise let me create a stream motor to hold our result and I'll have these two pointers pointing to the beginning of the string next step we're going to reverse the string we will need a river after that we iterate through each after that we iterate through each character off the string was well loop we check if the left pointer is pointing to empty space if so we'll move both left and right pointer otherwise it means that the left pointer is not pointing to a space so we just need to check if the right pointer is pointing to the empty space if it's not then we otherwise that means the left pointer is otherwise that means the left pointer is not pointing to an empty space but the not pointing to an empty space but the right pointer is pointing to a empty right pointer is pointing to a empty space like so that means we have a space like so that means we have a complete word and we want to reverse it complete word and we want to reverse it and put it in to our result don't forget to space then remove the left pointer to the right pointers position so after this iteration we need to check one more edge case that's when the left is pointing to a valid character and the right pointer is pointing to the end of the word that means we also need to reverse this word so we check if left is less than right you know so left pointer is not pointing to a space then we do this again now we're ready to return the result so if the string voters length is greater than one because it's also possible with that we have empty string like this if we have an empty string like this our our string builder will look like empty string so if the string builder is length is greater than one then we return string builder to string but we need to exclude the last empty space that we added otherwise we return an empty now that we just need to write this reverse string method give it a string I converted into a character array and also used a left pointer in the right pointer but left pointer pointing to the beginning of the string and the right pointer pointing to the end of the string then we move the left pointer in the right pointer towards the center and switch the characters on the and after that weight return a new and after that weight return a new string was the reversed character array let's take a look at it from the top we get an input as a string we check if it's null or if has a valid length then we'll create a string builder to hold our results a left pointer in the right pointer and then we reverse the input string while right pointer is less than the string length we check the left pointer first to see if it's pointing to a space if it is then we move both left and the right pointer otherwise that means the left pointer is pointing to a valid character then we check the right pointer if it's also pointing to a valid character then we'll move the right pointer otherwise that means the left pointer is pointing to a valid character but the right pointer is pointing to an empty space in that case we reverse the word back and appended to our result then we move our left pointer to the right pointers position now when the right pointer is pointing to the very end of the string we check if the left pointer is less than right pointer and the left pointer is pointing to a valid character that means we need to do this append operation again with the reversed word by the end we check if the string builders length is greater than 1 if it is then we return the substring dot to string and remove the last empty space otherwise we return empty string so for this reverse stream method we have a string as input we convert it to a character array we have the left pointer pointing to the beginning of the string the right pointer pointing to the end of the string and while left is less than right we switch those two characters and move the pointers by the end we return the new strand was the reversed character array I'm sure we'll have a mistake here for this case the left pointer needs to pointing to a non empty space that means we have a valid word now let's run it okay this test case is valid let's try some more edge cases add some more empty spaces in between the words and also passes and what if I only have empty spaces that also works let me try a test case with trailing spaces it also worked let's submit it okay so since we're going through the string twice to reverse it and reverse it back the time complexity would be O two times n which
2024-03-21 13:09:26
151
https://i.ytimg.com/vi_w…xresdefault.webp
Code with Jess - Leetcode #151 Reverse Words in a String
8A2G20k67go
all right let's talk about the maximum square so you're given an unbiased square so you're given an unbiased matrix so you have to return the largest matrix so you have to return the largest square containing only one square containing only one so so you have to return the area so this you have to return the area so this question is supposed to be easy so question is supposed to be easy so um um you are given a matrix like this so you are given a matrix like this so basically just create another matrix basically just create another matrix the same size is going to be um the same size is going to be um right right and then and then if you see the one if you see the one you consider one right you consider one right um then you just what then you have to um then you just what then you have to check uh the neighbor on what so if you check uh the neighbor on what so if you if you see that one right over here if you see that one right over here if you see a one right over here right if you see a one right over here right you have to check your neighbor so when you have to check your neighbor so when i say neighbor this is going to be your i say neighbor this is going to be your top left and top left and i mean top left and top left right i mean top left and top left right so basically find out the minimum so basically find out the minimum between this between this between this square between this square so we already know these cells is so we already know these cells is already one right so we don't care about already one right so we don't care about it so we have to find out the cells it so we have to find out the cells uh uh cells around me right cells around me right so if the minimum is zero so if the minimum is zero from these three right from these three right one two three right if if this one is one two three right if if this one is zero right then zero right then uh this is not a square right but what uh this is not a square right but what if the minimum of this if the minimum of this of the square is one the minimum between of the square is one the minimum between the three spots is one the three spots is one then i know then i know this one is supposed to be a square this one is supposed to be a square right so i would just update my right so i would just update my uh my metric uh my metric for this cell to two because i'm in this for this cell to two because i'm in this location right location right and so on right then just keep going on and so on right then just keep going on the bottom line right so uh this is uh the bottom line right so uh this is uh there's the base case for there's the base case for for i equal to zero and j equals zero so for i equal to zero and j equals zero so i put the zero represent what the rule i put the zero represent what the rule and then j equals zero percent column right so again now we we cannot actually find a square for i equals zero and j equals zero so we basically just append append a value one zero one zero zero to the uh to the new metric and one on one to the new metric so this is supposed to be the idea like for the i equal to zero and j equal to zero and i know like this is a string right and i know like this is a string right uh this is a chart right so i have to uh this is a chart right so i have to convert to the integer inside my 2d convert to the integer inside my 2d array and basically this is pretty much array and basically this is pretty much it for the best case then later on i it for the best case then later on i will just have to traverse my current will just have to traverse my current cell cell so my current cell is going to be like so my current cell is going to be like this so this is my current cell right so i will say okay for this one if this is one then i will have to traverse my square but this is zero right so i don't care what now i i'm not at this one right this one is one so i traverse my neighbor so my neighbor is what the minimum of the neighbor is zero so i don't care about it i don't update so this is this is supposed to be what uh suppose uh the default value one right and then again then i would just keep moving on the uh on the rest of the column and reverse of the rolling columns so this is pretty much it right so let me start doing this so this is a rolling high and i need to so this is a rolling high and i need to have a return value i'm going to call have a return value i'm going to call result result this is going to be a length and at the this is going to be a length and at the end end i will have to find out the area so the i will have to find out the area so the area of the squares area of the squares is is resource square right resultant result resource square right resultant result so now i traverse the square this is my new query right so i would this is my new query right so i would say i j say i j equal to what character dot equal to what character dot uh uh what else what else get get numerate value so i will say matrix ij numerate value so i will say matrix ij right and like just for example like this is what the one resource is actually uh the area right so i can i have to update my results all right so now this is the basic for all right so now this is the basic for the i 0 and j to 0 so i continue the i 0 and j to 0 so i continue i know what if the i is not equal to i know what if the i is not equal to zero or j is not equal to zero right i zero or j is not equal to zero right i have to make sure have to make sure make sure i j is actually equal to one make sure i j is actually equal to one so if this is a one i could check my so if this is a one i could check my neighbor neighbor and i and i already know like already know like my d uh my degree sorry my query ij my d uh my degree sorry my query ij since since the current cell is one since since the current cell is one right so i have to say one plus and then right so i have to say one plus and then the minimum between the the minimum between the minimum between my neighbor minimum between my neighbor so so again again so as i create so as i create the grid right and then by default it's the grid right and then by default it's actually zero right so actually zero right so i mean just for example i mean just for example this is zero right this is one one zero this is zero right this is one one zero one and by default this is supposed to one and by default this is supposed to be zero right but i know the metric and be zero right but i know the metric and this cell is one right so i have to this cell is one right so i have to i have to add one for i have to add one for uh for the cells which is already one so uh for the cells which is already one so one plus a neighbor so the neighbor is one plus a neighbor so the neighbor is this so the minimum between this is this so the minimum between this is actually zero so one plus zero is actually zero so one plus zero is actually actually one one so so this is it right this is it right so um this is going be three i minus one j minus one this is gonna be my top left and then three i j minus one this is gonna be my left right three i minus one okay this is my top right all right so after what i need to update my what my maximum value for the results and this is supposed to be the solution and this is supposed to be the solution so let me run it so let me run it uh uh right so i have a mistake right so i have a mistake for the what else oh sorry so what else oh sorry so uh in java you cannot have multiple uh in java you cannot have multiple value for the mean value for the mean you can only have two you can only have two so i would say i will have to have so i would say i will have to have another another math i mean and then this is it right all right so let me submit all right so let me submit uh let's talk about the time and space uh let's talk about the time and space all the time all the time uh this is the time right to follow so uh this is the time right to follow so it's going to be m times n it's going to be m times n all right well space is going to be the all right well space is going to be the m times m as well so this is a solution m times m as well so this is a solution and i was using this time
2024-03-22 10:53:16
221
https://i.ytimg.com/vi/8…go/sddefault.jpg
LeetCode 221 | Maximal Square| Matrix | Java
MpzdLtlto6w
Jai hind this video clip year digit code number 6 7 4 dictionary number 6 7 4 dictionary 2012 - ring return visam also this 2012 - ring return visam also this resting in posting and sense nine marks lead resting in posting and sense nine marks lead character 0512 subscribe video number two main one plus one two three and find to how how how Variables And He Call To Take Tel Last Length Of This Data Length -1.2 World Class Loot Digit From Being This Example And Faster Dry This Point Is Equally And Faster Dry This Point Is Equally Gallant Of This Complete Singh - Book Point Gallant Of This Complete Singh - Book Point Gallant Of This Complete Singh - Book Point Point To That Was So They Decided To Reduce Collector Orders From This Character 24 Carat Against A A This Amazing Aerial Act Flash Lights Jaipur To Bidders Length - Born Commander Objective To Lines On Which Theorem Per Tenth Westphal 111 Swami Ko D0 Darshan Swami Ko D0 Darshan Swami Ko D0 Darshan Test Live Webcasting This Article 243 Ki Garlic Medicine Lo Paaye Is Greater Than Or Equal 10 Far From Andhra And Juice Kar Dena Record Biology Mobile During Fasting More Last Digit Subscribe To Seek Digit From This Now This Don't Care It Last Pinpoint Thursday Poem after reading Eye - 0 That on this technique to convert into individual soul will forget all SIM liquid form The last digit copy and economic plight Neil Let's Uday Singh loose if it is a greater than or equal to Possible To Date Craft Possible To Date Craft Possible To Date Craft Videos J Videos J Jo Person Sahi R Jo Person Sahi R Ajay Ko How To Ajay Ko How To Hard Reset Udhar Bet Results Hard Reset Udhar Bet Results Point Ricardo Point Ricardo A Sanam 80 Mode Of Two Six Class 10th A Sanam 80 Mode Of Two Six Class 10th Result Adnan Sami Code To Mumbai To Red A Result Adnan Sami Code To Mumbai To Red A Reminder Reminder Are Common Next 9 News Se Vinnie Degree Is The Are Common Next 9 News Se Vinnie Degree Is The Value of by - manus and also given - - 9 Value of by - manus and also given - - 9 how to hide your line vijendra a great sub plus how to hide your line vijendra a great sub plus 2 this - - 2 this - - that this - - and reduced to live for others on i that this - - and reduced to live for others on i vijay kumar condition containing porn content vijay kumar condition containing porn content value from his paternal record value from his paternal record value from his paternal record 1008 1008 To The Same Thing Like Result Some Research On I Finally Can Return With A MP Ranbir Singh MP Ranbir Singh Bisht To Examples Bisht To Examples Yes Yes That Akhilesh Kumawat It's Clear That Akhilesh Kumawat It's Clear 2 Do There is a recent version 17.82 Percentage of Violence Mission 10 Year 2009 Sir Verification Code part of which Language Presence Sir Pesh Till and that A Girl in This Country The Property Snow A Girl in This Country The Property Snow Damaged The Research of Some Balance Capsule It has Damaged The Research of Some Balance Capsule It has Change Summary Change Summary Change Summary yes string like fight on small ki decision clear vidmate user can reduce and several years by his intellect and use this a is scrub rocket and similarly e f and this vowel hua hai do do hai coffee batting set proposal liquid Radhe has that as long as the loot was submitted the structures will remain 4 lessons for 94.20 to 0.5 inch video will solve different
2024-03-20 11:10:52
67
https://i.ytimg.com/vi/M…axresdefault.jpg
Leetcode | 67. Add Binary | Java | C#
6ngJWBA-nZk
we're going to take a look at a legal problem called distinct sub sequences so problem called distinct sub sequences so given two strings s and t return the given two strings s and t return the number of distinct subsequence of number of distinct subsequence of s which equals t so a string subsequence s which equals t so a string subsequence is a new string formed from the original is a new string formed from the original string by deleting some string by deleting some can be none of characters without can be none of characters without disrupting the remaining disrupting the remaining characters relative or positions so you characters relative or positions so you can see here we have an example right can see here we have an example right where uh let's say we have a c e where uh let's say we have a c e a c e is a subsequence of a b c d e a c e is a subsequence of a b c d e because you can see a because you can see a is come before c and c has come before e is come before c and c has come before e so in this case so in this case the subsequence is the same relative the subsequence is the same relative order as order as this original string right but the thing this original string right but the thing is that aec is not is that aec is not a subsequence of this because you can a subsequence of this because you can see here that a see here that a is come before e that's correct but c is come before e that's correct but c should not should not come after e right in this case you can come after e right in this case you can see see here e is comes after c here e is comes after c but c should not come after e so in this but c should not come after e so in this case this is not case this is not a subsequence of this right so we must a subsequence of this right so we must subsequence must subsequence must uh follow the same relative positions uh follow the same relative positions as uh from the original string right as uh from the original string right so here you can see we have our s and we so here you can see we have our s and we have our t have our t right so in this case we have our s right so in this case we have our s string and t string so in this case string and t string so in this case the output is three because there are the output is three because there are three ways you can generate three ways you can generate t from s right so in this case one t from s right so in this case one subsequence subsequence from s could be this and a b here right r b and b i t r a b and b i t right so in this case another example would be r a b b i t right another example would be r a b b and i t right so you can see here we can generate three separate combination uh three separate subsequence from s that equal to t right so you can see that basically this is how we solve outward in this case this is basically what we want to output is a number that represents how many distinct subsequence in s that equals t so let's take a look at the constraints so the constraints here is you can see here that uh s length of s and length of t is between 1 to 1 000 and then s and t should consist of english letters so let's take a look at a couple of base cases here so let's say we have a situation where s is equal to empty string right and t is equal to an empty string as well so what's the output look like so the output is actually going to be one because you can see here an empty string is a subsequence in s and that subsequence is equal to t so therefore the output is one now however though let's say if s is equal to a and then t is equal to empty string we still output is equal to one right because you can see here that empty string is also a subsequence in s and that subsequence is equal to t so therefore the output is one now let's say if s is equal to an empty string but t is equal to a then the output is going to be zero right because you can see here that there is no subsequence in s that equal to t so therefore the output is zero so let's take a look at another example right so let's let's say we have two strains here a b b and a b forget about how many distinct subsequence we can find in s that have that's equal to b let's take a look at how we can be able to find one subsequence in s that is equal to b right so you can see here what we can do is that we can basically have our pointer points to the last character in s and have another pointer point to the last character in t we're going to have our pointers go from the back to the front you can also go from the front to the back but basically you can see here we're basically comparing two characters right in this case that s at the last character in this case the current character in s and current character in t they do equal each other so we do is we move our pointer right so in this case we move our pointer one to the left and then we also move one of our pointers and t one to the left to compare to see if they're the same right in this case they are not the same so what we do is we basically move our pointer one to the left right for our t string in this case you can see this is basically what we're doing is that if they are the same right then what we're gonna do is that we're trying to figure out maybe how was the total distinct characters that we have for the remaining substrings right for the remaining substring right in this case you can see if they equal each other b and b they do equal each other so in this case if i want to find the total distinct subsequence for the current string if the current characters in s and current character and t they do equal each other so we do is we basically have our pointer right uh move one to the left to to figure out how many distinct subsequence or how many unique subsequences that we have in a remaining string right and if they don't equal each other in this case uh we basically just going to uh move right in this case move the left pointer uh move the the the pointer for the s string one to the left to figure out what's the total distinct subsequence right but there could also be a situation here you can see at the end you can see we're going to get a and b here right from s but the thing is that there could also be a sub sequence that we could have a b right where we're starting our pointer at here right which is here we're starting our pointer here comparing with this pointer right character for this pointer you can see this b and this b right here they do equal to each other right so we don't have to just compare this character with this character we also have to compare the remaining substring for uh an s with the current substring in t right so you can see here we basically just go also going to uh get the total right distinct subsequence starting from the next character right the next character in or the next substring in s comparing with the current substring that we have in t right because you can see here we can also have b b here and then a a here right so that will be one substring that we can be able to generate so this is our recursion tree and then you can see s is a b b and t is a b and then we can go down in this case we can there's two ways because now b they do equal each other right if they don't equal each other then we're just going to uh go down to s i minus one basically we're just going to uh look at the substring a remaining substring for s comparing with the current substring with t right so in this case they do match so we do is we're going down two pound one path is we're going to check the remaining substring and s and remaining substring in t to see what's the total distinct subsequence and the other path is we check the remaining substring in s and then the current substring in t right so you can see here for the current substring t and then the remaining substrate in s is a b and then current substring and t is a b right so in this case we're going to go down this path in this case we have a a right we can also go down where in this case we're just going to take the remaining substrate in s and remaining substrate in t and then there is one path if i go down this path where i take the remaining substrate in s and the current substring t in this case there is no path and then now in this case if i backtrack and i go back go down this path then you can see here that if i take the remaining substrings in this case the remaining substrings in s and remaining substituency t there's one path where we can basically go down this way and then there's one pound and you can see that there's total of two distinct subsequence that we can generate uh for this input so now let's take a look at a bigger example right so let's say we have a b a b and a b okay so in this case this is our recursion tree and what we're expecting is we're expecting three right we can have a b as that's equal to t we can have a b like this where we can also have a b like this which is also equal to t so their total the output i'm expecting is three right so in this case you can see we're starting from the root and then in this case we have a b a b and it is a b so in this case we can go down two path because now the last characters do equal each other right so in this case what we can do is that we can go down this path where we're basically just focus on the remaining substring for s and the remaining substring of t is because we have a b8 and a right and in this case you can see we can go down this two path so in this case we can get the subcurrent substrings of uh in this case s and t right the current substrings occur remaining sub uh remaining substrings of s comparing with the remaining substring was t in this case an empty string was t and then and then we have a b and s this is one the reason why we have one just like i mentioned before right let's say if we have a situation where this is s and then we have empty string in t this is our t this is our s right in this case an empty string is a subsequence in s that is equal to t right so therefore in this case we're just going to return what but however though let's say we have an empty string in s and we have a and t there's no subsequence in a there's no subsequence in in s that is equal to a that right that is equal to t so therefore there's no subsequence if we have a situation like this so therefore we're returning one uh so here you can see we can also go down another path where we're not taking the we're taking the current substring in t and we're taking the remaining substrings in s in this case a b comparing with the current substring and t in this case we can also go down this path where we can have a a right because now these characters they don't equal each other so we take the remaining of s right and the current substring was t and then we're going down this path right so we have one so in this case so far we have two so we can backtrack to the root here and then we're going down the other path in this case you can see we can also have a b a b a and a b right so we're taking the the remaining substring of s and then the current substring of t uh yeah so then in this case for this one right here you can see the last character doesn't equal each other so we're taking the remaining substring in s and then current substrate in t so we're going down this path so we have a b and a b in this case you can see we're taking the remaining substrings of s and t right to to make it one path in this case we can have a a which is one and then we can also have just like remaining substring of s and then the current substring of t in this case you can see here uh they don't equal each other for last characters so we're taking the remaining substrings of s which is just an empty string and then the remaining substring of t which is just a right uh sorry just a b because we cannot take the roommate we have to take the current substrings in in in t so in this case we have an empty string for s and then the current string and t is a b but you can see here just like i mentioned if s is empty string and then t is a character a or a b or the abc it doesn't matter so in this case there is zero because there's no way that there's no subsequence in s that is equal to t right so in this case we're outputting two we're outputting zero and then you can see if we collect all our ones here you can see we have three ones and the output is three right now as you can see here um this is our top down approach right this is our recursion tree and you can see here that this computation is computed multiple times right this computed it multiple times so what we can do is that we can basically just have a cache uh to basically cache the current index right the current index of s and current index of t in a 2d cache array so that if this is already computed before right we only have one character left with s and we only have one character left for t then we compute that pre-computed result in a 2d array so that if we visit that situation again we can basically retrieve that in the in the cache array right so now let's take a look at the top-down approach so you can see here this is our top-down approach right and this is our non-distinct function which takes the s string and the t string and then we're first creating some global variables here and then what we're going to do is we're going to define our base case and our base case is that if s is smaller than t that we know that there's no subsequence uh in s that we can generate that equals to t right because you can see this the size of s equal to t right is less than t so that we create our cash array and then in this case you can see here the cash array which basically is the size or basically is s times t right so in this case that's basically our space complexity as well and then we're calling this dfs dfx function uh dfs function and then we're passing in we're starting from the last character for both strings so this is the t index which is the last character initially and then this is the s index which is the last character initially and at first we define our base case right just like our recursion tree that we saw uh let's say we have a situation where s is not empty and t is empty right then we can be able to find a empty string an empty string is basically a subsequence in s that is equal to t so therefore we return one if they're all equal to empty string then in in this case we can also equal we can also return one because s uh a uh empty string is a subsequence of s that is equal to t however though if t is not empty but s is empty so therefore there's no way that s can be able to generate t right there's no subsequence in s that's equal to t so therefore we're returning zero so once we have our three base case defined then what we're gonna do is we're gonna see if if this current uh computation is already computed in our cache if it is then we're going to return that if not what we're going to do is we're going to compute it now just like i mentioned before there are two uh paths we can branch out to right but however it depends on the condition if the current character in s and current character in t is equal to each other so what we're going to do is we're going to compute the current position right the current position is basically either or sorry is we can go down one path where we're going to comparing the remaining substrings for both strings or we're going to comparing the remaining substrings in s uh and then the current substrings in t and then the other path is that if they don't equal each other we're basically just going to do this right we're going to compute the current position right the current situation where the current we're going to compare with the current sub current substrings in s with the current strings uh in in t right current current substrings and t with the remaining substrings in s right and we're going to save it in our cache and then we're going to return that as our result for the current position and this is basically how we're going to do it for how we solve this problem using a top-down approach so before we jump into the bottom-up approach i want to talk about the time complexity so time complexity is basically just going to be s times t right the size of our size of s times the size of our t and the space complexity because we're using our 2d cache array with t times s in this case we have a space complexity of s times t right so now let's take a look at a bottom up approach so for our bottom-up approach you can see on the right we have our 2d table right which is basically s times t but the thing is that you can see there's also an extra space there right this extra row and extra column is basically empty string this is our base case just like i mentioned before if our if we have let's say we have s which is equal to empty string and t right is equal to let's say a or something right in this case you can see we should have zero distinct subsequence right however though if s is equal to let's say a or let's say empty string and then t is equal to a empty string in this case there should be one solution right if it's an empty empty we're just going to have one distinct subsequence right and then if s is equal to let's say a right and that we're just we have t which is equal to empty string then there should be one distinct subsequence right because in this case an empty string and s is a this thing is a subsequence that is equal to t right so we're going to have that row that entire row to be one so that's what we're doing here we're building the first row and fill them up with just once and then the second row we're gonna you can see for nested loop we're actually starting at here because we already have the outer layer defined uh or the in this case the second row second column i should say so you can see here that we basically do our check if the current character doesn't equal each other then what we're going to do is we're basically just going to uh you know either take two paths right either take uh the remaining substrings right the remaining substrings of t oh sorry remaining substrings of t comparing with remaining substrings of s or i take the current substrings in t comparing with the remaining substrings at s which is basically those two positions right so that's basically the remaining substrings and s comparing with remaining substrings in t this position is basically remaining substrings in s comparing with the current substrings in t right so in this case there's one distinct subsequence here zero this thing subsequence here so i'm i'm going to get the sum of that which is what right and then you can also see here we're basically building up our table here you can see that for b we know that the b in this case they don't equal each other right so if they if r and b doesn't equal each other so what we do is we basically inherit from the uh from this from this value right here right because in this case if they don't equal each other so we're just basically taking the remaining substrates the s comparing with the current substrings in t so which is basically just one we'll just inherit that value from here and same thing here if they don't equal each other we just inherit that value from the previous uh previous column same row and previous call right and then for this for this position for this row right same thing here in this case they don't equal each other so i'm going to inherit it from the previous column which is here here in this case they don't they do equal each other so then what we're going to do is we're going to take that um in this case we're going to comparing with the remaining substrings which is basically one and zero right which is the sum of that which is one and now here you can see those two are equal to each other so in this case we're basically just taking the sum for those two right so in this case you can see the answer is just basically two and this is what we're doing here at the end we're basically just take returning the last element in the 2d array right so this is basically how we solve the problem the time complexity and space complexity it's basically just going to be t times s right so there you have it and thank
2024-03-21 10:52:57
115
https://i.ytimg.com/vi_w…xresdefault.webp
[Java] Leetcode 115. Distinct Subsequences [DP Subsequence #5]
mW1-hkW-wLM
elephants so today we are discuss this question on feed code 171 if you could question on feed code 171 if you could bt 171 question number one three months bt 171 question number one three months if convert integer to the sum of non if convert integer to the sum of non zero mission statement states that you zero mission statement states that you are given and into the tent and you have are given and into the tent and you have to return two integers a and B says that to return two integers a and B says that the two a and B are the nonzero integers the two a and B are the nonzero integers it means it doesn't contain any zeros it it means it doesn't contain any zeros it means a and B are the numbers which are means a and B are the numbers which are formed from M should not contain any formed from M should not contain any zero and the sum of TL plus B equal to zero and the sum of TL plus B equal to them and it is also guaranteed at at them and it is also guaranteed at at least one valid solution is like they least one valid solution is like they exist a valid for it so as you can see exist a valid for it so as you can see in this example who can open into one in this example who can open into one plus one well into one and one and the plus one well into one and one and the solution is that one plus one is equal solution is that one plus one is equal to and both are nonzero number same for to and both are nonzero number same for this case if we subtract 1 it will this case if we subtract 1 it will become 10 and 1 and 10 has zero on it become 10 and 1 and 10 has zero on it that's when I subtract 2 and it become that's when I subtract 2 and it become to a 9 in this we can subtract 1 and to a 9 in this we can subtract 1 and this also we can subtract 1 so like if this also we can subtract 1 so like if we do a brute force method is a very we do a brute force method is a very simple question but I have done this simple question but I have done this port I have taken both integers the port I have taken both integers the first is 1 and the second is in minus 1 first is 1 and the second is in minus 1 I just subtracted 1 because we want the I just subtracted 1 because we want the sum to be equal to if we add a and B is sum to be equal to if we add a and B is equal to M then what I do I'll make a equal to M then what I do I'll make a while loop and an admit a function and while loop and an admit a function and not has zero so I'll check is EA not has not has zero so I'll check is EA not has EO and all should be what has 0 if this EO and all should be what has 0 if this statement true will break out of this statement true will break out of this pilot or else this while loop is always pilot or else this while loop is always true and whenever I this condition is true and whenever I this condition is not true not true I will be payment K by 1 so that will I will be payment K by 1 so that will become 2 and now P is the gripper 1 so become 2 and now P is the gripper 1 so that the sum always remain equal to that the sum always remain equal to and we iterate over this loop until a and we iterate over this loop until a solution is found not a zero function is solution is found not a zero function is also simple we'll just in trade over the also simple we'll just in trade over the number such that it is not equal to zero number such that it is not equal to zero and we check every digit of that number and we check every digit of that number and if if it has zero then we return and if if it has zero then we return false because my function is not has and false because my function is not has and it ought it not has zero false because it ought it not has zero false because that number has zero and if not has zero that number has zero and if not has zero will return to because any any digit in will return to because any any digit in that number is not as you and if both that number is not as you and if both are true then I will break order to are true then I will break order to break out of the loop and we'll return break out of the loop and we'll return the list of LP which are the two back the list of LP which are the two back two numbers which equal which are whose two numbers which equal which are whose sum equal to n and Booth has not your sum equal to n and Booth has not your integer and I hope you understand the integer and I hope you understand the question question thank you
2024-03-20 12:02:12
1,317
https://i.ytimg.com/vi/m…axresdefault.jpg
1317. Convert Integer to the Sum of Two No-Zero Integers || leetcode || easy question || c++
Zsj-zudsUSM
[Music] hello everyone welcome to quartus camp hello everyone welcome to quartus camp we are a 22nd day of march lead code we are a 22nd day of march lead code challenge and the problem we are going challenge and the problem we are going to cover in this video is smallest to cover in this video is smallest string with a given numeric value so the string with a given numeric value so the input given here is to integer value n input given here is to integer value n and k and we have to return and k and we have to return a string as an output which is nothing a string as an output which is nothing but lexicographically smallest string but lexicographically smallest string with length n and numeric value equal to with length n and numeric value equal to k so here the problem statement says k so here the problem statement says that that the alphabet starting from a to z will the alphabet starting from a to z will be be positioned with one index positioned with one index that is a is 1 b is 2 and so on and we that is a is 1 b is 2 and so on and we have to form a string whose numeric have to form a string whose numeric value is equal to k value is equal to k or end of length n and return it so or end of length n and return it so let's understand this with an example so let's understand this with an example so here is a given first example where n is here is a given first example where n is equal to 3 and k is equal to 27 so which equal to 3 and k is equal to 27 so which means we have to form a 3 character means we have to form a 3 character string whose value is equal to 27 string whose value is equal to 27 so so the output could possibly be a a the output could possibly be a a y because a is equal to 1 again a is y because a is equal to 1 again a is equal to 1 which sums up to 2 and the equal to 1 which sums up to 2 and the rest is going to be rest is going to be 25 25 y is going to be 25 and finally is that y is going to be 25 and finally is that is going to be is going to be 26 which we already know so we can also 26 which we already know so we can also form a form a b b and and x or a c x or a c and w and w which will also sums up to 27 but here which will also sums up to 27 but here the problem statement clearly says we the problem statement clearly says we have to form have to form lexicographically smallest lexicographically smallest string so in that case a y would be the string so in that case a y would be the lexicographically smallest out of all lexicographically smallest out of all these solutions because the second these solutions because the second character is b and c here in the other character is b and c here in the other words when the first word is having a words when the first word is having a this is going to be lexicographically this is going to be lexicographically smallest so how are we going to approach smallest so how are we going to approach this programmatically so here the idea this programmatically so here the idea is to first form the string with all a's is to first form the string with all a's because our string has to be smallest because our string has to be smallest and a is the smallest of all characters and a is the smallest of all characters so we are going to fill a string with so we are going to fill a string with all is so that we get the smallest all is so that we get the smallest string first and then we are going to string first and then we are going to append or overwrite the last character append or overwrite the last character or from the last character towards left or from the last character towards left so that we make sure that the string so that we make sure that the string maintains the lexicographical order so maintains the lexicographical order so now we have all a's in our first example now we have all a's in our first example n is equal to 3 which sums up to 3 so n is equal to 3 which sums up to 3 so now our k given here is 27 we have to now our k given here is 27 we have to have 24 more values that has to be have 24 more values that has to be satisfied in order to get our first satisfied in order to get our first example done so here our string is example done so here our string is already formed with all a's whose sum is already formed with all a's whose sum is equal to 3 so now we have our k is equal equal to 3 so now we have our k is equal to 27 we still have 24 more values to be to 27 we still have 24 more values to be filled so let's start by overriding the filled so let's start by overriding the last character with values so let's say last character with values so let's say the first two a stays the same and we the first two a stays the same and we are appending a with b so now it becomes are appending a with b so now it becomes four same way we are overriding b with c four same way we are overriding b with c and this is 5 and d this is 6 and so on and this is 5 and d this is 6 and so on finally we are going to append it with y finally we are going to append it with y which which will give you the value of which which will give you the value of 27 27 so as we finally fix the last so as we finally fix the last character's value as y the rest of the character's value as y the rest of the two characters are going to seem going two characters are going to seem going to stay the same and this is going to be to stay the same and this is going to be our output our output so how did we do it we just started to so how did we do it we just started to override the values override the values from the last most character so now we from the last most character so now we already have a 1 we have to have 24 more already have a 1 we have to have 24 more so character y will actually get you to so character y will actually get you to that range which will simply be we are that range which will simply be we are first going to check whether we can first going to check whether we can append this with an is it so is that is append this with an is it so is that is nothing but the last character which is nothing but the last character which is having the value 26 so in this case we having the value 26 so in this case we are simply going to remove this are simply going to remove this character and override it with is it so character and override it with is it so we don't actually add 26 we add only 25 we don't actually add 26 we add only 25 why why because we already have a value a which because we already have a value a which is 1 so in this case we add 26 and is 1 so in this case we add 26 and subtract 1 so which is simply done by subtract 1 so which is simply done by doing a minus 1 for this character so if doing a minus 1 for this character so if we add 25 to it which will actually we add 25 to it which will actually be overriding 24 because we have only 24 be overriding 24 because we have only 24 left if we add 25 then it goes in left if we add 25 then it goes in case value goes in minus 1. so in that case value goes in minus 1. so in that case we should not we cannot append it case we should not we cannot append it with it so what would be the previous with it so what would be the previous character is it which is nothing but y character is it which is nothing but y so for y the actual value is 25 so we so for y the actual value is 25 so we are going to replace a with y so in that are going to replace a with y so in that case we will be adding only 24 to it case we will be adding only 24 to it because we'll add 25 and subtract 1. so because we'll add 25 and subtract 1. so 24 satisfies with the existing 24 that 24 satisfies with the existing 24 that is the value of k so we are going to is the value of k so we are going to append it with y so hope you are append it with y so hope you are understanding this logic if not let us understanding this logic if not let us do a quick do a quick run through for the second example so run through for the second example so you will get a get better understanding you will get a get better understanding so now n is equal to five so we have to so now n is equal to five so we have to form a string of length five so let us form a string of length five so let us fill with all a's in all five positions fill with all a's in all five positions so as i said we are going to replace or so as i said we are going to replace or overwrite the values from the last overwrite the values from the last character towards the first character so character towards the first character so now we have our value as 73 so now k is now we have our value as 73 so now k is equal to 73 equal to 73 so as i said we have added 5 a's which so as i said we have added 5 a's which means which sums up to 5 for now so let means which sums up to 5 for now so let us subtract 5 from 73 which will give us subtract 5 from 73 which will give you 68 you 68 so why we are subtracting 5 because we so why we are subtracting 5 because we have the sum of 5 so we have to add 68 have the sum of 5 so we have to add 68 more to this string so we are going to more to this string so we are going to replace the last character with the replace the last character with the highest value possible so what is the highest value possible so what is the highest value from a to z which is z highest value from a to z which is z whose value is equal to 26 so here we whose value is equal to 26 so here we are going to check whether we can add is are going to check whether we can add is it at the end so it at the end so 68 minus 26 is something higher so we 68 minus 26 is something higher so we can actually add the value is it at the can actually add the value is it at the end but here instead of adding 26 we are end but here instead of adding 26 we are simply going to add 25 why because simply going to add 25 why because the last character will be replaced by z the last character will be replaced by z so in this case if we are going to so in this case if we are going to replace a we are going to first remove a replace a we are going to first remove a which will take away minus 1 from the which will take away minus 1 from the total sum and we add 25 to it so in total sum and we add 25 to it so in short we simply add 20 to 25 instead of short we simply add 20 to 25 instead of 26. so the characters are going to be 26. so the characters are going to be same for the first four places and same for the first four places and finally we are going to add an is it finally we are going to add an is it which will actually sum up to which will actually sum up to 5 plus 25 30. so as we have added one 5 plus 25 30. so as we have added one more 25 to our string let us subtract more 25 to our string let us subtract this 25 from 68 which is 43 so we have this 25 from 68 which is 43 so we have 43 more value left to be added to the 43 more value left to be added to the string as we have added our last string as we have added our last character to z which is the maximum character to z which is the maximum value so we have to now move to our last value so we have to now move to our last but one character and check whether we but one character and check whether we can replace it with the highest value can replace it with the highest value which is is it so if you subtract 43 which is is it so if you subtract 43 with 26 you still have more values to with 26 you still have more values to add so in this case again the rest of add so in this case again the rest of the characters are going to be same and the characters are going to be same and we are going to replace it with set and we are going to replace it with set and the last character is already said so the last character is already said so now we have to subtract one more 25 from now we have to subtract one more 25 from here which will give you 18 so we still here which will give you 18 so we still have 18 more to be added to our string have 18 more to be added to our string so now we have last two characters so now we have last two characters appended to the maximum value so we appended to the maximum value so we cannot change it so now it's time to cannot change it so now it's time to move to one last but one character so move to one last but one character so now we have only 18 left to be filled now we have only 18 left to be filled so we are checking whether z can be so we are checking whether z can be replaced in this place no because we replaced in this place no because we only have 18 but the value of is it is only have 18 but the value of is it is 26 and for our problem it is going to be 26 and for our problem it is going to be 25 so we can't do it so further we 25 so we can't do it so further we reduce it by one character y will be 24 reduce it by one character y will be 24 w will be 23 and so on and finally s w will be 23 and so on and finally s will be your 18 so when you fill this will be your 18 so when you fill this character with s this 18 will be character with s this 18 will be subtracted and our k will become zero subtracted and our k will become zero so our solution will actually be so our solution will actually be a a a a s set set and rk has become 0 and our s set set and rk has become 0 and our size is already length is already 5 and size is already length is already 5 and this satisfies our input criterias and this satisfies our input criterias and this is going to be our output this is going to be our output so this is going to work in big o of n so this is going to work in big o of n time and space complexity because we are time and space complexity because we are going to use an additional memory to going to use an additional memory to compute this characters which is a compute this characters which is a character array and we are going to character array and we are going to iterate all the characters of length n iterate all the characters of length n and fill in the values so let's get into and fill in the values so let's get into the code now the code now so here is a code for a problem which is so here is a code for a problem which is pretty simple as i said we are going to pretty simple as i said we are going to have a character array which is going to have a character array which is going to hold all our characters and finally we hold all our characters and finally we are going to return it in form of string are going to return it in form of string because our output is going to be because our output is going to be in string and first we are filling our in string and first we are filling our array with all a's as i said we have to array with all a's as i said we have to fill it with minimum value and first we fill it with minimum value and first we are going to subtract with n because if are going to subtract with n because if we add a in all the positions from total we add a in all the positions from total k k n will be subtracted as we have added as n will be subtracted as we have added as many number of a's to it many number of a's to it and finally we are going to iterate till and finally we are going to iterate till our k is becoming 0 and our k is becoming 0 and at the position from the last because n at the position from the last because n is at the last position we are going to is at the last position we are going to subtract subtract or decrement our n at every iteration so or decrement our n at every iteration so that our values will be that our values will be filled or overridden from the last filled or overridden from the last position so as i said we are going to position so as i said we are going to check which is minimum whether 25 or k check which is minimum whether 25 or k if 25 is minimum from k we first if 25 is minimum from k we first append it with a z and subtract the append it with a z and subtract the value from k value from k if not if k is minimum then we are going if not if k is minimum then we are going to append it with result with that to append it with result with that particular character and subtract it particular character and subtract it from k and finally rk becomes zero so we from k and finally rk becomes zero so we are going to replace the characters from are going to replace the characters from the last till however position it holds the last till however position it holds and finally we are going to return it in and finally we are going to return it in form of result so hope you are form of result so hope you are understanding this code let's give it a understanding this code let's give it a try yes the solution has been accepted and yes the solution has been accepted and returns in 23 milliseconds so thanks for returns in 23 milliseconds so thanks for watching the video hope you like this watching the video hope you like this video if you like this video hit like video if you like this video hit like subscribe and let me know in comments subscribe and let me know in comments thank you
2024-03-20 10:24:42
1,663
https://i.ytimg.com/vi/Z…axresdefault.jpg
Smallest String With A Given Numeric Value | LeetCode 1663 | Coders Camp
LoycI7Y-hww
welcome to september's lego challenge today's problem is combination sum today's problem is combination sum three find out possible combinations of three find out possible combinations of k numbers that add up to a number n k numbers that add up to a number n given that only numbers one to nine can given that only numbers one to nine can be used and each combination should be a be used and each combination should be a unique unique set of numbers so that's actually very set of numbers so that's actually very helpful that each combination can only helpful that each combination can only be be a unique set of numbers so we should a unique set of numbers so we should never have any repeating numbers never have any repeating numbers now if we are given the number k equals now if we are given the number k equals three and n equals seven three and n equals seven then we can see our output's gonna be then we can see our output's gonna be one two four because this is the only one two four because this is the only combination of numbers from one to nine combination of numbers from one to nine uh with three numbers that's ever gonna uh with three numbers that's ever gonna equal seven equal seven with three and nine here we have one two with three and nine here we have one two six one three five and two three four six one three five and two three four uh so that's basically it um uh so that's basically it um now one of the things that we can see now one of the things that we can see with this problem is that with this problem is that the numbers that we can use are the numbers that we can use are potential candidates let's say potential candidates let's say are always going to be sorted it's going are always going to be sorted it's going to be one through nine so that's to be one through nine so that's actually very helpful in what we want to actually very helpful in what we want to use our approach we can use a depth use our approach we can use a depth first search recursion and what we're first search recursion and what we're going to do going to do is basically check every single go through a recursive loop where we check to see every single combination that we can build from our numbers one through nine and we'll build up our stack as we move along and once we have a stack that is the length of k we'll check to see if the number is n and if it is we'll add it to an output and if it isn't we just will stop our recursion right there because one of the good things about this is because it's sorted once we see that the sum is greater than the sum that we want to calculate for we could stop our loop we don't need to calculate any more after that because say that we have like one two six now we want to check one two seven well we don't need to check that because we already know everything after this point is going to be greater than nine so we could break our loop there all right so the first thing i might want to do is set a output of an empty list and we're going to do a depth first search recursion and a couple primers we need to pass first we need to pass our stack or the build list that we're building up and we need to pass in our number to know where we are in our recursion like are we at one are we at two um and that way we can know like we're not going to make any repeats and and check numbers that we've already set so we don't need a set here we just need to know where are we in our in our recursive path let's say uh and the last thing we want to pass is some so far and what this is going to allow us to do is not have to check our build to see how what the sum is every single time we just check that here and say hey if the sum that we calculate so far equals n then add our build to the output all right so the first thing we need to do here is have our base case right and if this build i should say the length of this build is equal to k then we know we can end our recursion we don't want to go any further than that but one thing we need to do is check to see if our sum so far equals n because if it does then we add it to our output otherwise we don't we don't and we just keep we just stop our recursion so if sum so far equals n then add to the pen to our output the build and this is our stack that we're building up um and that would be it so at this point here this is where we're going to be actually making our recursion and what we'll have to do is basically check from i and range of the number we're on all the way up to nine and we actually need to add one there to make sure we take care of nine um and we will call our deaf research we'll call our pass in our build plus the number that we've just calculated for we'll pass in our uh i as a number but we'll actually add that one there so that we don't like repeat the same number and we need to pass in our sum so far plus the i so this is going to be what allows us to check to make sure that the number is equal to number we're checking for right and one thing we can actually do here is just check sum so far plus i if this is greater than n then we can just break our loop actually we don't need to calculate any further because that would be a waste of time since we know our sum so far is already exceeded and like we don't need to calculate any more than that and that would be it um all we need to do now is just call our debt for search we'll call in a passing empty list as a stack we'll pass in our num so far which is going to be i'm sorry number we're on which is going to be 1 first and the sum so far which is going to be 0 at first and that's it after that we just return our output and this should solve the question let's make sure this works and there we go so that's accepted that and there we go so that's accepted that works perfectly fine works perfectly fine and it's a good solution uh one thing to and it's a good solution uh one thing to note is one of the things note is one of the things also you can do is actually use inner also you can do is actually use inner tools and tools and why don't we just use inner tools and why don't we just use inner tools and find all the possible combinations for find all the possible combinations for the numbers one through nine with a the numbers one through nine with a length of k right and we actually have a length of k right and we actually have a tool tool for that in inter tools so we can use for that in inter tools so we can use create a list say nums i for i in create a list say nums i for i in what range of what range of one through nine plus one one through nine plus one uh while this numbs and we'll say okay uh while this numbs and we'll say okay give me all the combinations using inner give me all the combinations using inner tools tools that's some numbs with a length of k that's some numbs with a length of k right so this is going to give us all right so this is going to give us all possible combinations with a length of k possible combinations with a length of k and then really all we can just do here and then really all we can just do here is say all right is say all right well we turn for c in combo well we turn for c in combo if the sum of c equals if the sum of c equals n then add it to our list and just n then add it to our list and just return that and let's make sure that works it does and this should be accepted it does and shockingly this actually is faster in lead code now technically this is slower in terms of time complexity because we're not breaking our loop um before we're actually checking for every single combination but it actually runs faster and the reason for that i'm not completely sure but my guess is it's got something to do with the way the algorithm works for combinations here it's just whatever is going in the background it's faster than my stupid little recursive for loop um so sometimes like even though in theory like my time complexity is faster sometimes these things the reality just doesn't match and that this is actually faster so it's like one of those things to remember stay humble even though you think you know something like the reality might be different this might actually be a better use than my recursive function so all right i think i'll end it there thanks for watching my channel and remember do not trust me
2024-03-22 10:42:52
216
https://i.ytimg.com/vi/L…ww/sddefault.jpg
Leetcode - Combination Sum III (Python)
0d6WF79hQME
welcome to july's leeco challenge today's problem is k today's problem is k smallest element in a sorted matrix smallest element in a sorted matrix given an m times n matrix where each of given an m times n matrix where each of the rows and columns are sorted in the rows and columns are sorted in ascending order ascending order we turn the kth smallest element in the we turn the kth smallest element in the matrix matrix now note that it is the k smallest now note that it is the k smallest element in the sorted order not the case element in the sorted order not the case distinct element so we had duplicates distinct element so we had duplicates we're still looking at the index number we're still looking at the index number not the distinct element not the distinct element okay so at first glance it kind of looks okay so at first glance it kind of looks like this is just like this is just sorted in like road column fashion 159 sorted in like road column fashion 159 10 11 13 so why don't we use like 10 11 13 so why don't we use like divisors and divisors and modulars but that's not going to work modulars but that's not going to work because you can easily imagine some because you can easily imagine some examples where examples where we're sorted row and column but it's not we're sorted row and column but it's not going to be sorted in that same going to be sorted in that same direction so this direction so this technically is sorted rolling column but technically is sorted rolling column but if we moved left to right here if we moved left to right here that wouldn't work because it's not in that wouldn't work because it's not in sorted order sorted order so that's not going to work is there so that's not going to work is there anything we could anything we could take advantage of given that it's sorted take advantage of given that it's sorted well before we do that why don't we just well before we do that why don't we just do a brute force method do a brute force method let's just flatten this matrix into a 1d let's just flatten this matrix into a 1d array array and see if we could sort it and return and see if we could sort it and return the kth element in there the kth element in there and all we have to do then is say 4l in and all we have to do then is say 4l in matrix matrix we'll just extend our temporary array we'll just extend our temporary array with the list with the list and make sure to sort this and literally and make sure to sort this and literally just return the temp just return the temp k minus 1 element right so k minus 1 element right so this would be the brute force method and this would be the brute force method and it actually does work in fact it gets it actually does work in fact it gets accepted here accepted here um because time complexity wise it's um because time complexity wise it's going to be what n going to be what n squared to the log of n squared because squared to the log of n squared because of the sort here of the sort here so you know at first glance i thought so you know at first glance i thought like okay well this is it maybe like okay well this is it maybe maybe that's it that's the solution but maybe that's it that's the solution but something didn't sit right something didn't sit right with me because i knew that because it's with me because i knew that because it's sorted in row and column fashion sorted in row and column fashion there has to be something we can take there has to be something we can take advantage of here otherwise it's like advantage of here otherwise it's like we're literally just storing the whole we're literally just storing the whole thing we're not taking advantage of the thing we're not taking advantage of the fact that it's sorted in rolling column fact that it's sorted in rolling column um so one way that you could do that is um so one way that you could do that is to do a binary search to do a binary search but instead of looking at the elements but instead of looking at the elements here what we're going to do is look at here what we're going to do is look at the the gap between the minimum number and the gap between the minimum number and the maximum number that's going to be our maximum number that's going to be our range when we do a binary search and range when we do a binary search and we're going we're going to do another we're going we're going to do another binary search through each row to find binary search through each row to find how many elements are less how many elements are less than the element that we're searching than the element that we're searching for as soon as we find our left and for as soon as we find our left and right right range equal another and our k is yeah equal to 8 then then we can return whatever number we come up with so one of the few things we do know about this matrix is that the top left right here and the bottom right is going to be the min and max of our matrix right so let's first take advantage of that we'll set our left and right pointers as well as the n here make the left pointer is going to be matrix of zero zero right point is gonna be matrix of negative one negative one and the n is just going to be what length of matrix so first let's write a helper method to show us how many elements are less than whatever input that we put in to check whether we should move our left pointer to the middle or the right corner to the middle so we'll call this less than k and we'll pass in some number so let's see we're going to count the numbers initialize it with zero and we'll say four say row and range of n let's do a binary search here we'll do a bisect but we have to do a bisect right and the reason for that let's see here the reason for that is if let's see here the reason for that is if if if we find a number that's like we find a number that's like equal to all these numbers here we want equal to all these numbers here we want to go all the way to the right side to to go all the way to the right side to see how many see how many are less than k so we'll say bisect are less than k so we'll say bisect right right and then we'll add this number to our and then we'll add this number to our account here finally return our account and now let's do our binary search so while l is less than r calculate the mid which is going to be l plus r divided by two uh if less than k oops less k of mid if this value is less than k then we want to move our left pointer to the middle right and we're going to have to add one here because we want to find um the right the right gap here so otherwise we'll say r equals to mid and then we can just return r l or r doesn't matter which one so let's see if this works okay that doesn't look like it's working and there you go so that's accepted as and there you go so that's accepted as well uh time complexity wise this would well uh time complexity wise this would be be i think it's gonna be log oh no no it's i think it's gonna be log oh no no it's gonna be n gonna be n to the log of whatever the gap between to the log of whatever the gap between the min and max is so we'll call that m the min and max is so we'll call that m so n log so n log of a right here i believe that's correct of a right here i believe that's correct although this part here might make it n although this part here might make it n log n hmm n log n log n hmm n log n times log of the m something like that times log of the m something like that but either way when i look at the speed but either way when i look at the speed it's about the same because of our it's about the same because of our constraints constraints uh really depends on what would be our uh really depends on what would be our constraints if we had like really large constraints if we had like really large ends this solution would be much better ends this solution would be much better otherwise the brute force otherwise the brute force method works fine and it's uh in fact method works fine and it's uh in fact sometimes faster sometimes faster when we run it and look at the the time when we run it and look at the the time so so it's up to you i did see one other it's up to you i did see one other solution that is oven time but it was so solution that is oven time but it was so complicated complicated it used math and median values and it it used math and median values and it was just way too complex for me to go was just way too complex for me to go through so through so let's end it here thanks for watching my let's end it here thanks for watching my channel and remember do not trust me channel and remember do not trust me i know nothing
2024-03-24 11:47:00
378
https://i.ytimg.com/vi/0…ME/sddefault.jpg
Leetcode - Kth Smallest Element in a Sorted Matrix (Python)
0AC-TjfomZw
hello everyone welcome to day 17th of march lead code challenge and today's march lead code challenge and today's question is generate random points in a question is generate random points in a circle circle in this question you are given three in this question you are given three parameters the first one is the radius parameters the first one is the radius of the circle the second one of the circle the second one is the x coordinate of the center of the is the x coordinate of the center of the circle followed by the y circle followed by the y coordinate of the center of the circle coordinate of the center of the circle what we need to do what we need to do is to generate random points which lie is to generate random points which lie within the circle this point should be within the circle this point should be highlighted highlighted but the point that that we need to but the point that that we need to generate generate should lie within the circle not on the should lie within the circle not on the circumference of the circle circumference of the circle nor outside the circle so please keep nor outside the circle so please keep this point in mind this point in mind and let's quickly understand the and let's quickly understand the algorithm that i have created for this algorithm that i have created for this we need to fill in these two methods in we need to fill in these two methods in the solution the first one being the the solution the first one being the constructor of the class and the second constructor of the class and the second one one is a random point generation logic is a random point generation logic so moving on to the algorithmic part the so moving on to the algorithmic part the slideshow that i have created for this slideshow that i have created for this let me just take a pen here so even let me just take a pen here so even before jumping onto the details of the before jumping onto the details of the algorithm let's try and understand few algorithm let's try and understand few properties of a circle properties of a circle the center of the circle is a comma b the center of the circle is a comma b let's highlight that let's highlight that a is x coordinate b is the y coordinate a is x coordinate b is the y coordinate and the radius is r so this is r this and the radius is r so this is r this length is r length is r this length is r this 2 being r so let's write all the this 2 being r so let's write all the extreme coordinates of the circles this extreme coordinates of the circles this point would be point would be a comma b a comma b plus r the bottom one would be a comma b minus r comma b and comma b and the left one would be a minus the left one would be a minus r comma b r comma b so this is a minus r comma b also so this is a minus r comma b also let's try and understand few properties let's try and understand few properties that we read in 11th or 12th standard that we read in 11th or 12th standard x minus a where a is the center of the x minus a where a is the center of the circle circle square plus y minus b square plus y minus b square if it's equal to r square then square if it's equal to r square then it lies on the circle so if there's an x it lies on the circle so if there's an x and y coordinate and y coordinate whose distance from the center whole whose distance from the center whole distance from the center which is given distance from the center which is given by a square by a square x minus a square plus y minus b square x minus a square plus y minus b square happens to be equal to r square then happens to be equal to r square then that point lies on the circle that point lies on the circle if it's greater than r square that means if it's greater than r square that means it's like it's like it lies outside the circle somewhere it lies outside the circle somewhere here like anywhere around here like anywhere around along this region and if it lies within along this region and if it lies within if it is less than r square that means if it is less than r square that means this distance this distance is less than r square x minus is less than r square x minus a square plus y minus b square is less a square plus y minus b square is less than r square than r square that means that lies inside the circle that means that lies inside the circle so these all for all these points this so these all for all these points this property will be true property will be true pretty simple and let's reduce the pretty simple and let's reduce the problem problem from a circle to a 1d problem from a circle to a 1d problem to a point to a to 1d problem from a 2d to a point to a to 1d problem from a 2d to a 1d problem to a 1d problem how let me just explain that let's how let me just explain that let's assume this coordinate as a assume this coordinate as a and we are interested in finding a and we are interested in finding a random number random number between a plus r between a plus r starting from a minus r starting from a minus r so this is pretty much clear to us that so this is pretty much clear to us that the range that we are interested in is a the range that we are interested in is a minus r to a plus r as stated here the minus r to a plus r as stated here the range of x coordinate range of x coordinate how can we do that let's how can we do that let's try and generate random numbers up to a try and generate random numbers up to a range of range of 2r so 2r so if we are able to do that starting from if we are able to do that starting from 0 0 we can generate random numbers up to 2r we can generate random numbers up to 2r pretty straightforward pretty straightforward we can use java rand helper class we can use java rand helper class uh to generate numbers from 0 uh to generate numbers from 0 up to 2r and let's then add up to 2r and let's then add a minus r to it so if i add a minus r to a minus r to it so if i add a minus r to it it this point will become this point and this point will become this point and this point will become a minus r will become this point and the center would be a so which mathematical formula can we derive we need to generate numbers a minus r plus so this is the formula that we have that so this is the formula that we have that we will use we will use for generating random numbers between for generating random numbers between the range of a minus r up to a plus the range of a minus r up to a plus r a minus r plus random r a minus r plus random 2 r that means first you generated 2 r that means first you generated a random number starting from 0 to 2 r a random number starting from 0 to 2 r and you added and you added a minus r to it and therefore you are a minus r to it and therefore you are able to able to generate this range we'll do this for generate this range we'll do this for the x coordinate the x coordinate here we'll do it for the y coordinate here we'll do it for the y coordinate and we will pass and we will pass the x and y coordinates uh to this the x and y coordinates uh to this logic of ours which will tell us whether logic of ours which will tell us whether that point lies on the circle that point lies on the circle outside the circle or inside the circle outside the circle or inside the circle we'll keep on doing that we'll keep on doing that till the time we don't find the point till the time we don't find the point that lies inside the circle that lies inside the circle that's it that's pretty much it and as that's it that's pretty much it and as soon as we find such a point soon as we find such a point we abort the process and return those x we abort the process and return those x and y coordinates and y coordinates so let's quickly move on to the coding so let's quickly move on to the coding part part let me just define three variables a let me just define three variables a stands for the x coordinate stands for the x coordinate double b stands for the y coordinate of double b stands for the y coordinate of the center the center so these two correspond to the center so these two correspond to the center and double and double r stands for the radius we will also r stands for the radius we will also generate generate a random helper class and let's call it a random helper class and let's call it random means like this random means like this null and let's move on to the null and let's move on to the constructor part constructor part this dot a equals to this dot a equals to x enter this dot b equals to buy center pretty simple and this dot also we'll initialize rand equals to new also we'll initialize rand equals to new random so everything that we need to random so everything that we need to initialize has to be done initialize has to be done in the constructor and all the private in the constructor and all the private uh helper methods should be uh helper methods should be uh in initialized null or their default uh in initialized null or their default values values basic rule of java basic rule of java and let's just write the and let's just write the method to generate x and y coordinates method to generate x and y coordinates in that range in that range so get so get random coordinate and what we will pass it r and so let's write this helper method first so let's write this helper method first [Applause] [Applause] generate random coordinate and it will generate random coordinate and it will accept two accept two double variables first is the radius double variables first is the radius and second one is the x or the y center and second one is the x or the y center coordinate coordinate so let me just call it c and what we so let me just call it c and what we need to return need to return r minus c plus r minus c plus rand dot next double into 2 into r so let me just explain this part to next double gives us floating values next double gives us floating values between the range of between the range of 0 till 1 and when we multiply it with 2r 0 till 1 and when we multiply it with 2r we get numbers floating numbers within we get numbers floating numbers within the range from 0 the range from 0 till 2r this is what i have done here till 2r this is what i have done here and and once we have written this let's just once we have written this let's just generate generate the y-coordinate get the y-coordinate get random coordinate r comma random coordinate r comma b and while b and while get distance and what will pass get distance and what will pass x comma y comma r x comma y comma r if it's greater than or equal to r if it's greater than or equal to r square r into r square r into r if that is the case then we'll have to if that is the case then we'll have to keep on generating such random numbers otherwise we'll return our answer and these x and y coordinates are those coordinates of a random point to completely this let's write the last method private double get distance double x and double y we don't need r here so let me just remove that and the distance would be given to us using the formula of distance between two points x minus a into x minus a plus y minus b pretty straightforward way of calculating the distance actually the square of the distance and i have not used square root therefore i multiplied it with r into r other than keeping r then otherwise otherwise i would have done a square root here not an issue or you can go for either ways and let's just revise this code once yeah this looks fine we generated the numbers get distance and get random coordinates oh this should be c minus r so though in this slideshow you saw a minus r plus 2 random of 2r so using the same logic i have written it here so this is c minus rather than a minus r accept it thanks for watching the video accept it thanks for watching the video hope you enjoyed it hope you enjoyed it please don't forget to like share or please don't forget to like share or subscribe and subscribe to the channel
2024-03-18 11:09:13
478
https://i.ytimg.com/vi/0…Q9rp0Ou0t6-Vnrvw
Generate Random Point in a Circle | Leetcode 478
X01DHnncDfs
hi guys how are you i hope all you are doing good welcome to the learn code easily so today we will solve one more question that is medial well question and the question is insertion list it's it is a very easy question actually this is coming from the insertion sort if you know the insertion sort then you have to then you can do it very well if you do not know then first you have first you need to learn if you go on the internet and you if you write on insert some sort then there there are some good explanation out there you can re you can read it [Music] [Music] uh uh yeah so as in this yeah so as in this with the help of graph with the help of graph everything is given here everything is given here if you if you want to learn how the if you if you want to learn how the insertion insertions are work then it is insertion insertions are work then it is graphically represented here you can see graphically represented here you can see from here from here this is the same process now you have to this is the same process now you have to follow the same process as it is as follow the same process as it is as given in the picture given in the picture so first i will tell you uh already it so first i will tell you uh already it is is written in the three points written in the three points insertion sort i create consuming one insertion sort i create consuming one input element each repetition and input element each repetition and growing a sorted output list at each growing a sorted output list at each each iteration insertion sort removes each iteration insertion sort removes one element from the input data one element from the input data find its location as you can see it is find its location as you can see it is finding its location so the location of finding its location so the location of three is here three is here belong within sorted list and insert it belong within sorted list and insert it there it repeats until no input remains there it repeats until no input remains no input elements remain so no input elements remain so we have started from here now when we we have started from here now when we will go till four so four will be will go till four so four will be resetted here so the list is sorted resetted here so the list is sorted so the three points have been described so the three points have been described in the in the in the pictorial form in the pictorial form so if i take that one example so if i take that one example so how we will do it as you can as you can see if you if you compare you have to compare you have to compare every time you have you have to start from here and your and you have to start from here and your and your second pointer is this one your second pointer is this one like like this one this one now you have to compare now you have to compare the previous element is greater than the the previous element is greater than the current element so we will current element so we will swap so it will become five comma six swap so it will become five comma six now the remaining list is three one now the remaining list is three one eight eight seven two four seven two four now now now uh we have uh we are done with this now uh we have uh we are done with this element we will element we will move towards the next element move towards the next element now 3 is greater than 5 5 is greater now 3 is greater than 5 5 is greater than 3 yes so let's sort it than 3 yes so let's sort it so it will become 3 so it will become 3 6 6 now now uh the 5 will come 5 will come here 18 uh the 5 will come 5 will come here 18 7 to 4 7 to 4 so this is the first step this is the second step but this is not this is the second step but this is not yet uh in indeed why because yet uh in indeed why because the because we have the initial pointer the because we have the initial pointer is here now i will go there is here now i will go there i will go for the next position i will go for the next position and i will check 6 is greater than 5 yes and i will check 6 is greater than 5 yes so it will become so it will become 3 comma 5 comma 6 18 3 comma 5 comma 6 18 comma says 7 comma 2 comma 4 now comma says 7 comma 2 comma 4 now i am i am at this position now if you will move at this position now if you will move there there then your current current pointer and then your current current pointer and the previous pointer will come at the the previous pointer will come at the same point so we cannot do anything same point so we cannot do anything so so so the second step is done now we will again move from starting and now your next current pointer is at this point you have to compare again one and six then you have to compare this element with one and you have to compare with so if you compare then it will become 1 so if you compare then it will become 1 comma 5 comma 3 comma 6 comma 8 comma 7 comma 5 comma 3 comma 6 comma 8 comma 7 comma 2 comma 4 now it is still not in comma 2 comma 4 now it is still not in that that and now and now you you are there now now you will reach you you are there now now you will reach at this position at this position at this position okay at this position okay now now you are done with you are done with first like this element now you will first like this element now you will come at this point your current pointer come at this point your current pointer is this you have to compare both one is this you have to compare both one five is greater than six no five is greater than six no okay so this will okay so this will be like same as be like same as given given [Music] [Music] now you are you are done with now you are you are done with uh one you are done with 5 now your uh one you are done with 5 now your pointer will move to 3 and you will pointer will move to 3 and you will compare one is less than i have done something wrong here when your pointer will come at this point one so one will go there six will come here five three now six you have to compare with this this is also less than you have to compare with three as well [Music] no something is wrong i have done so five six is correct now you will come at three now you have to it will become three five six okay now you will come at 18 this is like this is a team now when you will come at this point you now when you will come at this point you have to one have to one five five six six it it will be three it it will be three now you have to compare three bit five now you have to compare three bit five so three will come here five will come so three will come here five will come here here and it will be six now you will compare and it will be six now you will compare with five and three with five and three so so it will be three and now you have to it will be three and now you have to compare with six and five so five will compare with six and five so five will come here come here 6 6 8 7 2 4 now you now your pointer was 8 7 2 4 now you now your pointer was there there so the previous pointer and the current so the previous pointer and the current pointer are at the same position pointer are at the same position so you so you so you cannot do anything so you cannot do anything now you will move eight now you will move eight now you have to compare again now you have to compare again eight with one eight with one eight with eight with one eight with one eight with three so all are sorted three so all are sorted now you will go for seven now you will go for seven you will compare with every element one you will compare with every element one three five are less than 6 is also less three five are less than 6 is also less than than when you will reach at this point then when you will reach at this point then you can see that previous element is you can see that previous element is greater than the current element greater than the current element so i am doing i am doing directly so i am doing i am doing directly so it will be 6 now now 8 and 7 will be so it will be 6 now now 8 and 7 will be swiping will be swap so it will become 7 swiping will be swap so it will become 7 8 8 2 4 2 4 now you will move at 2 now you will move at 2 now you will compare with 2 and 1 okay now you will compare with 2 and 1 okay it is less than now you will compare it is less than now you will compare with 3 and 2. so it will become one two five six seven eight three and four now [Music] your pointer will come at at this point at this position you will compare for three and five so three will go there five will come here now your next pointer will come here and you will again compare so this will become six and this will become five okay this is also done now you will go for next position so seven and six see the previous element is rather than the current one so we will swipe it so this will become okay so now your current pointer will come here you will swipe it so it will become seven and it now your now your current pointer will come at four current pointer will come at four now you will compare one is less than now you will compare one is less than four two is less than four three is less four two is less than four three is less than four five is not less than four so than four five is not less than four so i will swap i will swap these two element okay six is these two element okay six is less than five no let's type it less than five no let's type it say one is less than six no let's type say one is less than six no let's type it it [Music] [Music] okay okay uh it is less than seven no let's type uh it is less than seven no let's type it it as you can see as you can see my my my current list is sorted and we have to my current list is sorted and we have to follow the same step i hope you have follow the same step i hope you have understood the process let's begin with understood the process let's begin with the implementation so it is eight minute the implementation so it is eight minute already done so let's implement as quick already done so let's implement as quick as possible as possible [Music] so let's take the two pointer that is the current pointer that is my head dot next what is my previous pointer previous pointer is head okay so if head is equals to none so if head is equals to none or or head head dot next dot next is equals to none is equals to none and head does not equals to none we have and head does not equals to none we have to return to return head head so so while while uh my uh my current pointer current pointer then equals to none let's run for another loop when my previous does not equals to current and if my previous dot val is greater than it means that my previous value is so let's sep it and move my previous pointer towards the next one uh uh it is my current it is my previous it is my current it is my previous yeah it's correct yeah it's correct now what i will do now what i will do every time my previous would start from every time my previous would start from beginning beginning and i will move my current to and i will move my current to current.next current.next and we have to okay so if my head is none if my head of okay so if my head is none if my head of next is none but head is not and still next is none but head is not and still we have to return here because one we have to return here because one element we cannot sort a single element element we cannot sort a single element so this is my previous this is my so this is my previous this is my current so current as you can see current so current as you can see i'm increasing my current every time i'm increasing my current every time so the previous is all again is uh so the previous is all again is uh always start from the beginning so always start from the beginning so that's why i have so that's why i have again slicing my previous with the help of it because head is at the starting value it is the starting head is always point to the starting node i am starting my current i'm fixing i'm moving my current towards the next value and also the previous towards the next value as well okay so previous current current current previous dot file okay i think it is done now let's directly try to submit it and see that whether it would submit or oh it is taking time okay oh it is taking time okay so we have done in a single strike so i so we have done in a single strike so i hope you understood how we are doing we hope you understood how we are doing we are we are just following the same step are we are just following the same step as as i have described you as as i have described you so if you do not know please go to some so if you do not know please go to some articles some documentation articles some documentation of insertion sort you will learn it then of insertion sort you will learn it then you can implement it very well you can implement it very well so i hope you understood guys so i hope you understood guys i will okay so there are some similar type of question you can solve this as well so i will meet in the next video with the next video till then bye bye take care bye bye guys
2024-03-21 12:57:12
147
https://i.ytimg.com/vi/X…axresdefault.jpg
147. Insertion Sort List | Medium Level Interview Question Full Explanation in Python
vr9DNalvThQ
welcome to july third sleep code challenge challenge maximum sum max sum of rectangle maximum sum max sum of rectangle no larger than k given an m by n matrix no larger than k given an m by n matrix matrix matrix entry k return the maximum entry k return the maximum sum of the rectangle and the matrix such sum of the rectangle and the matrix such that its sum is no larger than k that its sum is no larger than k it's guaranteed that there will be a it's guaranteed that there will be a rectangle with the sum rectangle with the sum larger than k so given this matrix here larger than k so given this matrix here uh 1 0 1 0 negative 2 3 um uh 1 0 1 0 negative 2 3 um you would think that uh using the uh you would think that uh using the uh well i'll explain first well i'll explain first so let's say if you were to add this so let's say if you were to add this rectangle here ly in blue rectangle here ly in blue it'll give you the sum of two which is it'll give you the sum of two which is um um no larger than k which is two no larger than k which is two so let's think about this for a bit so so let's think about this for a bit so first thing you think of is that brute first thing you think of is that brute force approach force approach um uh since it's uh um uh since it's uh negative numbers it's probably not a negative numbers it's probably not a good way of doing this good way of doing this but uh if you were to enumerate all all but uh if you were to enumerate all all the possible rectangles to get the best the possible rectangles to get the best solution solution uh time complexity probably like uh yeah uh time complexity probably like uh yeah m squared n times n squared so that m squared n times n squared so that might not be the most best might not be the most best way of doing it because it's not very way of doing it because it's not very clever clever and takes a very long time however you and takes a very long time however you seek a little seek a little example here using a one dimensional example here using a one dimensional array here so you have array here so you have two two negative one since we're always two two negative one since we're always guaranteed with some guaranteed with some larger than k um if we were to sum all larger than k um if we were to sum all these together we'll get these together we'll get uh equal output three and our case three uh equal output three and our case three so let's kind of work with this kind of so let's kind of work with this kind of idea working with our one-dimensional idea working with our one-dimensional array first array first and uh seeing how that works out and uh seeing how that works out so um let's see so um let's see so we're going to use this idea so we're going to use this idea um let's see um let's see called uh let's see if we have an array called uh let's see if we have an array of uh negative one negative two of uh negative one negative two and four let's put that space there and four let's put that space there and we want to develop this thing called and we want to develop this thing called a um a um let's call a look up where it's gonna be let's call a look up where it's gonna be a uh an array that's gonna store our a uh an array that's gonna store our something called a prefix something called a prefix um uh p sum um uh p sum so first we're going to use that to so first we're going to use that to start perfect sum so the first thing start perfect sum so the first thing it's going to have is it's going to have is 0 because there's nothing summing it and 0 because there's nothing summing it and we're going to move through our first we're going to move through our first index here which is index here which is going to be negative 1. so perfect sum going to be negative 1. so perfect sum is going to be is going to be a running sum of negative one right here a running sum of negative one right here so we're gonna have negative one so so we're gonna have negative one so first we're gonna first we're gonna have zero here so i'm gonna put have zero here so i'm gonna put whatever's in the perfect sum into whatever's in the perfect sum into our lookup and then we're gonna sum it our lookup and then we're gonna sum it again and i'm going to add that to our again and i'm going to add that to our lookup lookup so we're going to have a running sum so we're going to have a running sum as we're going along and putting it into as we're going along and putting it into our lookup our lookup so then we move our um we move to the so then we move our um we move to the second right here which is negative 2 second right here which is negative 2 negative 2 negative 2 plus negative one would be negative plus negative one would be negative three let's store negative three right three let's store negative three right here and our lookup here and our lookup and then lastly we're gonna move to and then lastly we're gonna move to four so four plus negative three is four so four plus negative three is gonna be one and we store one gonna be one and we store one into our lookup so we're gonna have this into our lookup so we're gonna have this however however it's uh we're gonna actually rearrange it's uh we're gonna actually rearrange this and put this and put put this negative one at the end here put this negative one at the end here but uh i haven't decided yet but uh i haven't decided yet so i'm gonna use this idea for one so i'm gonna use this idea for one dimensional array and how we're going to dimensional array and how we're going to develop that towards develop that towards working towards a harder solution we're working towards a harder solution we're using using not just one dimensional but two or not just one dimensional but two or three or even more dimensions right a three or even more dimensions right a two-dimensional array two-dimensional array so um let's see let's see for each so um let's see let's see for each time we run this algorithm let's time we run this algorithm let's updating our prefix sum updating our prefix sum in a one-dimensional array we're in a one-dimensional array we're probably gonna do it for probably gonna do it for each uh row each uh row each row and then we're gonna do the each row and then we're gonna do the same same thing with then this thing with then this the entire the global so we're going to the entire the global so we're going to sum these two together as well sum these two together as well uh the the columns together and i'm uh the the columns together and i'm going to do it for each going to do it for each each row that way as well each row that way as well so it's um let's see if this approach so it's um let's see if this approach or kind of background kind of works um or kind of background kind of works um let's get to it so there's there's many let's get to it so there's there's many ways of this is a hard solution i mean ways of this is a hard solution i mean yeah a hard question uh challenge so yeah a hard question uh challenge so let's let's let's first divide our uh dimension so m let's first divide our uh dimension so m by n is going to be the length of the matrix and then length of the matrix at position zero so yep so we're gonna first make our rows uh so for e for row and matrix we are going to uh start um um uh for i in uh for i in range let's see range let's see n minus one what we're going to do is uh n minus one what we're going to do is uh make our row so row at make our row so row at index plus one index plus one will be incremented to row at i will be incremented to row at i all right so um all right so um we need to uh define an output so we need to uh define an output so our output is or initialize our output i our output is or initialize our output i should say should say let's um it could be none let's um it could be none but uh that won't work for integer types but uh that won't work for integer types so let's call it the float so let's call it the float of negative infinity just uh of negative infinity just uh just to have some kind of initialization just to have some kind of initialization going on going on now we're going to loop through our now we're going to loop through our matrix so we're going to have a double matrix so we're going to have a double for loop into nested for loop here so for loop into nested for loop here so for i in range for i in range of n so that's uh for each uh so that's uh for each uh each row you're going through what do each row you're going through what do you want to do so we want one first to you want to do so we want one first to find our lookup find our lookup which is going to be our array of uh which is going to be our array of uh starting at zero starting at zero and we're gonna find our uh prefix sum and we're gonna find our uh prefix sum counter counter or perfect sum or our ongoing sum or perfect sum or our ongoing sum i guess which is going to be initialized i guess which is going to be initialized to zero so for each to zero so for each um let's say um each count now each character each element in our our in our matrix all right let's call it c in range of m for each um this is individual each cell each cell in our in our in our matrix on an array we want to be able to update our perfect sum so we're going to implement that with increment that with the increment that with the matrix cell at location matrix cell at location j and we want to if the um minus the um so if i is greater than zero so if i is greater than zero what do we want to do you want to c location at the i minus 1 c location at the i minus 1 location else location else y zero so this is the turning operator y zero so this is the turning operator here um so that's updating our prefix sum now we want to do is uh update our lookup table and we're going to do that with bisect left so um let's call this index uh or type variable i should say our lookup and our [Music] perfect sum minus k because now we have a perfect uh sum and our lookup already we're going to build that and we want to make sure the perfect sum is within the restraint within the um within the balance of k right it can't be greater than k because that's the condition and we want uh so if so first we define our index yup so if our index is greater or equal to zero and our index is less than the length of our lookup table what we want to do is update our output to be the max of the output and our prefix sum minus the lookup at the index then we want to insert so bisecting sort so we want to sort using um a sorted type of approach to the bias and sort we're going to insert lookup and the because we want to put the uh this the because we want to put the uh this the um the last sum um the last sum at the end of the lookup all right let's see this is even close all right let's see this is even close to working finished oh that doesn't look good finished oh that doesn't look good let's see first we define our m and n let's see first we define our m and n side lengths okay for each row in the side lengths okay for each row in the matrix we're going to make the columns matrix we're going to make the columns for it all right and the at and the output is going to be a float of a negative infinite number so for i in range n nested with four j in range i to n we're gonna make a lookup table and a prefix sum counter so for each cell in our matrix we're going to increment our perfect sum with the matrix at location c cell j minus our if the index if i is greater than zero we're going to have a minus the cell at matrix c in the i minus one location else we're gonna minus zero and then whenever we define an index number here which is bisect bisect left where we have to look uh look up and the perfect sum minus k because we wanna not be within our outside our bounds so if the index is greater than or equal to zero and the index is less than the length of lookup we want with max of the output and with max of the output and the prefix sum wise lookup at the index the prefix sum wise lookup at the index and then we want to sort that using and then we want to sort that using bisect insert with lookup and the bisect insert with lookup and the the prefix thumb and we want to return the prefix thumb and we want to return the output as well the output as well all right that seems to be should work all right that seems to be should work please work all right accepted so this approach is um using something uh using a prefix sum on a one-dimensional array and then we're gonna we eventually sorted it using bisect sort it's not really using a story container it's just more like using the bisect function to sort it but uh in terms of time complexity i believe that it is let's go through this so we have a nested for loop here going through um so we have this is the row which is n so n big o of n times no wait this is um m no wait this is um m this is uh let's hmm big o of m squared hmm big o of m squared times n times the times n times the log of n because for we iterate it's it's a lot uh i'm not entirely sure about that but the space complexity is a big of n because we store it in our um as a number so uh we we store we do have a lookout but we never have to return it so yeah i could be taught at wrong in terms of i could be taught at wrong in terms of space and space complexity and time space and space complexity and time complexity but complexity but that's a hard question so uh that's that's a hard question so uh that's pretty much all i got pretty much all i got have a good one
2024-03-24 11:27:01
363
https://i.ytimg.com/vi/v…axresdefault.jpg
July 3/2021 LeetCode Challenge: Max Sum of Rectangle No Larger Than K
MCPhGg_vedE
hey hey everybody this is larry this is me going over q1 of the bi-weekly me going over q1 of the bi-weekly contest 52 contest 52 52nd sorting the sentence so 52nd sorting the sentence so 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 this prom what you think about this prom so this one could be it could be a so this one could be it could be a little bit more tricky i think little bit more tricky i think but the key thing and it took me a but the key thing and it took me a little bit of a while little bit of a while uh is to notice that there are no more uh is to notice that there are no more than nine words than nine words meaning that you don't you only have to meaning that you don't you only have to care about the last character and that's care about the last character and that's it it um and that's basically what i did i i um and that's basically what i did i i look at the string i split it up word by look at the string i split it up word by word word and then i sorted by the last character and then i sorted by the last character um and um and then i joined it back together removing then i joined it back together removing the last character and that's it the last character and that's it um this is going to be n log n where n um this is going to be n log n where n is the number of words is the number of words uh which i guess roughly is almost the uh which i guess roughly is almost the number of characters but number of characters but like number characters over three or like number characters over three or something like that uh but yeah something like that uh but yeah um in terms of space we don't really i um in terms of space we don't really i mean we mean we it's linear space we can reconstruct it's linear space we can reconstruct everything i suppose everything i suppose um but yeah uh you're not going to do um but yeah uh you're not going to do more than that so yeah more than that so yeah that's what i have for this problem i that's what i have for this problem i solved it during the contest in about a solved it during the contest in about a minute and 22 seconds minute and 22 seconds uh yeah uh let me know what you think uh yeah uh let me know what you think and you could watch me stop it live and you could watch me stop it live during the contest uh hey yeah uh thanks for watching hit uh hey yeah uh thanks for watching hit the like button to subscribe and join me the like button to subscribe and join me in discord let me know what you think in discord let me know what you think about this contest about this contest um yeah i hope y'all just have a great um yeah i hope y'all just have a great week week good contests and yeah stay good stay good contests and yeah stay good stay healthy to good mental health and i will healthy to good mental health and i will see you later see you later bye bye
2024-03-25 11:15:11
1,859
https://i.ytimg.com/vi_w…xresdefault.webp
1859. Sorting the Sentence (Leetcode Easy)
H216IGvo5JQ
hey hey everybody this is Larry this is me trying to do a bonus prom that me trying to do a bonus prom that haven't done before hit the like button haven't done before hit the like button hit the Subscribe button join me on hit the Subscribe button join me on Discord let me know what you think about Discord let me know what you think about this one on February 20th 20 24 I almost this one on February 20th 20 24 I almost forgot the year a second all right we forgot the year a second all right we have a hard problem today so hopefully have a hard problem today so hopefully not too hard hopefully it's still not too hard hopefully it's still solvable uh 805 spread away with the solvable uh 805 spread away with the same average you are given an integer same average you are given an integer array nums you should move each element array nums you should move each element nums into one to two arrays A and B such nums into one to two arrays A and B such that a and B A non empty and average of that a and B A non empty and average of a is equal to average of B return Tru a is equal to average of B return Tru it's possible to achieve that in force it's possible to achieve that in force otherwise no death run away otherwise no death run away okay uh so basically this so hm that's a okay uh so basically this so hm that's a interesting one so the first thing is interesting one so the first thing is noticing that the order doesn't matter noticing that the order doesn't matter so so yeah yeah [Music] um yeah so basically okay H the the thing to notice is that and is is dirty so what does that mean that means that we can do some funky algorithms um obviously um you know two to the 30 is going to be too slow so so what can we do right I mean to be honest two to 30 um as uh spit in the middle or meat in um as uh spit in the middle or meat in the middle but that's kind of like a I don't know I and this is just a like a little bit meta it's just that it's it's a very hard thing to expect people to know so on an interview that would be ridiculous let me give it a little bit of a DOT to kind of think about um it's kind of hard to say I mean the other way that I would think about it is that because nums of I is 10 to the fourth the other possibility is um dynamic programming right that may be probably the easier way to think about it I mean that way to meet in the middle um if we have to maybe we can do fine fine yeah uh this is kind of still tricky yeah uh this is kind of still tricky with dynamic programming I mean it's not with dynamic programming I mean it's not it's actually that not that bad I think it's actually that not that bad I think I could do dynamic programming it's just I could do dynamic programming it's just tricky for me to explain it I'm trying tricky for me to explain it I'm trying to figure out way to figure out way uh the queen way to explain it um but I uh the queen way to explain it um but I think it should be okay to be honest right so all right I mean I think we could just do uh BR force or not brof force but memorization but with the idea Bo Force so let right so then now we can do something like um and for this one because it is a hard um and for this one because it is a hard I don't know how many people watch as a I don't know how many people watch as a beginner let me know in the comments beginner let me know in the comments because I I kind of struggle sometimes because I I kind of struggle sometimes about like how how much to um or like about like how how much to um or like the level to explain these problems um the level to explain these problems um so and for today given that this is a so and for today given that this is a dynamic program problem I'm not going to dynamic program problem I'm not going to do the dynamic Pro I'm not going to do the dynamic Pro I'm not going to explain memorization b or rather I'm not explain memorization b or rather I'm not going to explain explain basic going to explain explain basic memorization I do that a lot on my daily memorization I do that a lot on my daily videos already at least in the past so videos already at least in the past so this time today I'm just going to be a this time today I'm just going to be a little bit lazy and not focus on that little bit lazy and not focus on that because that's not the interesting part because that's not the interesting part about this problem I think but yeah but about this problem I think but yeah but maybe I will I don't know we'll see how maybe I will I don't know we'll see how that goes but basically if you want to that goes but basically if you want to write Pro Force you might have something write Pro Force you might have something like uh possible I don't know uh the like uh possible I don't know uh the index of the number like basically how index of the number like basically how many I used um the current total and then the number of items that right now used to say and in that case right now used to say and in that case uh let's kind of think about this for a uh let's kind of think about this for a second right index could be 30 obviously second right index could be 30 obviously total can be uh like we said um 30 * 10 total can be uh like we said um 30 * 10 what it what it 10,000 well this is just 10,000 sorry 10 10,000 well this is just 10,000 sorry 10 to 4 and use this also up to 30 so then to 4 and use this also up to 30 so then that means that this can go up to 9 that means that this can go up to 9 million million um oh wait wait wait this I'm really um oh wait wait wait this I'm really wrong total is way than that right total wrong total is way than that right total is the sum of 30 numbers so it's is the sum of 30 numbers so it's actually that's why I said it that way actually that's why I said it that way but then I kind of confused but then I kind of confused myself uh is that yeah so it's this myself uh is that yeah so it's this right though not all of them is possible right though not all of them is possible so in theory in so in theory in actuality actuality um is that now all of them are kind of um is that now all of them are kind of possible because you have dir numbers possible because you have dir numbers then you can just have um you know you get I'm just all the powers of twos then that would be the summation of 1 + 2 + three or 1 2 4 to 300,000 and then 300,000 times like 10 20 uh because then it'll be doubling until um well until 3 200,000 what is until um well until 3 200,000 what is that that is that that is basically 20 doublings no no no it's basically 20 doublings no no no it's like s 16 doublings so then it's 16 * like s 16 doublings so then it's 16 * 300,000 um or 17 * 300,000 because of 300,000 um or 17 * 300,000 because of the doubling so then it the doubling so then it is a lot right but anyway but yeah so this actually comes up to be a lot so this would actually not be a reasonable way to do this right because now yeah do I have to really do meat in the yeah do I have to really do meat in the middle for this one maybe I do I kind of missed a cuz in my head missed uh timesing this by Dirty I think when I first finish and then I also missed the used part a little bit but cuz I was thinking about it up bottom top but maybe we have to do um meet in the right how would meat in the middle work it's not a easy meet in the middle um we also double check two to the 15 um we also double check two to the 15 what's two to the 15 again like 32,000 I what's two to the 15 again like 32,000 I guess that should be guess that should be okay I mean no me me in the middle would okay I mean no me me in the middle would work if I could figure out how it works work if I could figure out how it works exactly with exactly with averages it it h is there another DP that's not h is there another DP that's not napsack that was my first intuition but I okay maybe I have to play around a I okay maybe I have to play around a little bit with what the average means a little bit with what the average means a little bit because I think I have some little bit because I think I have some in my head right so basically average is in my head right so basically average is just equal to sum of a over count of a just equal to sum of a over count of a obviously obviously right um and then you have sum of B is right um and then you have sum of B is over count of B so then basically you over count of B so then basically you have sum of a time count of have sum of a time count of B is equal to sum of B time count of a right and then basically we can convert this to n minus count of a right something like that does that help um so this fun this thing should be um so this fun this thing should be equal to the other equal to the other thing and of course sum of B is just thing and of course sum of B is just equal to Total sum equal to Total sum minus sum of a does that minus sum of a does that help don't help don't know let's multiply that out right so know let's multiply that out right so sum of a * n minus sum of a * count of a sum of a * n minus sum of a * count of a is equal to Su total sum minus sum of a is equal to Su total sum minus sum of a * count of a um I think the sum of a * count of a um I think the sum of a times count of am I doing this right oh times count of am I doing this right oh uh this actually times count of a on uh this actually times count of a on this side oops this side oops um but in any case I think this part um but in any case I think this part kind of cancels out right so let me just kind of cancels out right so let me just write on the next line so I write on the next line so I don't I don't know I'm really bad at don't I don't know I'm really bad at doing this on here I'm usually better at doing this on here I'm usually better at paper so maybe I'm just confusing this paper so maybe I'm just confusing this but okay this I mean now it is kind of clear what this I mean now it is kind of clear what that means right that means right oh I oh I mean I mean this is a property that to mean I mean this is a property that to be honest I did not realize when I be honest I did not realize when I started writing this so it just means started writing this so it just means that the average is equal to well the that the average is equal to well the average of the entire frame which is a average of the entire frame which is a property that I did not think property that I did not think about because basically it's just saying about because basically it's just saying that the average of a is equal to that the average of a is equal to average of B then there average of the average of B then there average of the entire frame so that means that now we entire frame so that means that now we have an idea of what we want the Tet to have an idea of what we want the Tet to be be right so then now it becomes a different right so then now it becomes a different thing right because then now we have sum thing right because then now we have sum is equal or you know let's just say is equal or you know let's just say total equal sums of nums then now what total equal sums of nums then now what does that mean that means that we can does that mean that means that we can try we could Pro there's only dir try we could Pro there's only dir numbers right so we can try if this is numbers right so we can try if this is one then we know what sum a needs to be one then we know what sum a needs to be if this is two we know what sum a needs if this is two we know what sum a needs to be so forth right because then now so to be so forth right because then now so then we can prove for or we can like like basically we can say is there one number with the the average total Over N is there two numbers with the and right and here you can rewrite this as right and here you can rewrite this as one number with this as the sum one number with this as the sum right this and two numbers is this times right this and two numbers is this times two as the two as the sum sum right that's sum so then now we don't right that's sum so then now we don't have to deal with the average anymore well I mean one number obviously is just one but you get the idea okay this is actually a fun problem and you know I did not know how to solve this before I had some ideas in my head obviously of some Impressions but I didn't think about doing it this way so this is a fun Evolution for sure kind of right and that's pretty much it then right and that's pretty much it then right because then now this becomes a right because then now this becomes a really really straightforward it sorry I got stuck in my head uh a it sorry I got stuck in my head uh a straightforward nap thing right that we straightforward nap thing right that we kind of had before um with fewer States kind of had before um with fewer States well one is pretty straightforward I'm trying to convince myself that I I'm trying to make sure that what I'm saying is true I think that's what I'm doing now um so dirty choose I mean this is dirty choose two is pretty straight for D choose three is pretty straight for what's What's d choose 15 again I guess that's a big one do choose I guess I need Google choose 15 is uh you do choose 15 is only 155 million which actually is a little bit slow so we won't do it that way but but inferior is almost close enough to um the meat in the middle is actually pretty straightforward as well I I mean see but so okay so the other thing I see but so okay so the other thing I want to point out is that it stops at is want to point out is that it stops at is there n/ two numbers sums to average there n/ two numbers sums to average total time n time n / two because then total time n time n / two because then after this um if if one number sums to after this um if if one number sums to average of n it also implies that um n average of n it also implies that um n minus one other numbers sums to dot dot minus one other numbers sums to dot dot dot right so so we only have to Loop dot right so so we only have to Loop this to n /2 which is to say that now if this to n /2 which is to say that now if we look at we look at our earlier thing we only have to go to our earlier thing we only have to go to 15 so we only have to sum to 15 numbers 15 so we only have to sum to 15 numbers right so then now basically if we had right so then now basically if we had our thing earlier of possible uh index our thing earlier of possible uh index total count or something like this I total count or something like this I forget or used um now we reduced it to forget or used um now we reduced it to index is equal to well still up to 30 uh index is equal to well still up to 30 uh total it you only some 15 numbers so total it you only some 15 numbers so then now it's instead of uh so it's this then now it's instead of uh so it's this times 15 instead oftimes 30 and then times 15 instead oftimes 30 and then used only goes up to 15 so then now what used only goes up to 15 so then now what is this fast enough time 15 * 15 is this fast enough time 15 * 15 times 10,000 all right so that is 67 times 10,000 all right so that is 67 million so still a little bit too much million so still a little bit too much even though a lot of them are not as even though a lot of them are not as possible and because we go up to possible and because we go up to 150,000 um a lot of them are not should 150,000 um a lot of them are not should not be possible so it could I think it not be possible so it could I think it probably is more probably is more borderline even though it's possible uh borderline even though it's possible uh was it 60 what did I say 67 million or was it 60 what did I say 67 million or something uh so this is you know 67 something uh so this is you know 67 million States um but lazy math right million States um but lazy math right because technically speaking it's going because technically speaking it's going to be like the summation of all these to be like the summation of all these things so um so it's actually a little things so um so it's actually a little bit bit less so it's or a lot less really less so it's or a lot less really because it only goes up to 15 um you because it only goes up to 15 um you choose a power of two choose a power of two FR then it kind of saturates pretty FR then it kind of saturates pretty quickly or pretty um like the first 10 quickly or pretty um like the first 10 doesn't do anything really I don't know I mean I think maybe we can YOLO and go for this but uh but let's think about divide it in the middle right so uh divide in the middle we have two to the 15 possible things um and then we can B research so that should be like probably the way we want to do it 2 to the 15 is 32,000 and then log base is like times 15 maybe and that should be good so I think that's the way we'll do it um but yeah really annoying prom uh not something that you would do in an interview I mean it's me about 16 minutes to kind of come to this conclusion this is a very fun observation to make to be honest uh and so so I don't know it's kind of fun I like it I dig it um but yeah let's do the the so if you want to go I'm not going to talk about this too much um I'm just it's more of a it doesn't it's not that interesting of an algorithm it's so limited in use but it comes up um randomly like here but uh um I don't even Advocate learning it just because it just like when when is it ever going up not much to explain it's just doing up not much to explain it's just doing it in a way such that basically instead it in a way such that basically instead go two to the power you go two to the power you two make two sets of enters and then fin two make two sets of enters and then fin a resarch on them so that you can yeah yeah okay so here use maybe not yeah I'm just going to use use maybe not yeah I'm just going to use the B Mas but please my my note level but still I gu have sure anyway all right I'm going to use bit mask I'm not going to explain it in this video there's already enough conversation problem um if you don't know it you should not work on this I hope that that doesn't come off as I just mean like you could work on others that kind of because this is not that for you but watch and basically yeah now we do for right I and basically yeah now we do for right I guess this is the for way of course if guess this is the for way of course if you put in the entire way it's going to you put in the entire way it's going to that's then what you want to do and out yeah out yeah basically now it's 16 and half two three basically now it's 16 and half two three four and then it just possible possible four and then it just possible possible and this is the dictionary of the count and this is the dictionary of the count and then and then and they're not I don't think they are and they're not I don't think they are in order I mean in this case it is just in order I mean in this case it is just because it is another lucky okay right so then now we have this okay right so then now we have this thing and basically what the idea here thing and basically what the idea here is is okay so for um I don't okay so for um I don't know for I in range of at and then now Bally z i gu they could be they can't both be z i gu they could be they can't both be basically you're just combining basically just piing I from the left and J from the right side so so now what is the target goal right so the now what is the target goal right so the target goal here have we have n over total sorry total Over N is what we fin reach um it's equal to some some sum some number right i j on the other side and basically I X is the sum that we're looking for I X is the sum that we're looking for just like right so yeah have to do a just like right so yeah have to do a couple things basically a whole number couple things basically a whole number so if possible that's number we're searching possible that's number we're searching for then now for left values and now for then now for left values and now we're going to search from J we're going x it's no oh okay so the same way that this cannot oh okay so the same way that this cannot be zero it cannot be be zero it cannot be that's and um not a super fast solution pretty okay solution uh yeah this is in the middle everybody take this form but actually to okay I don't I wonder like in the past okay I don't I wonder like in the past the B are tighter or like less tight the B are tighter or like less tight because I don't know because I don't because I don't know because I don't know how work yeah I don't think because know how work yeah I don't think because we did the analysis I mean and like we did the analysis I mean and like maybe I now know I mean this part is part that I see I mean this is basically the same I see I mean this is basically the same way that we have I don't know well I mean no no no the way that is is don't I yeah I don't think I don't know what the yeah I don't think I don't know what the intended to intended to hon it seems like a lot of people did DC but but that me in the middle require all this sometimes yeah finding this part is maybe I don't think I mean we did it a little bit all right uh that's what I have for this all right uh that's what I have for this one I actually like this Farm it's kind one I actually like this Farm it's kind of fun but I also think it's not a good of fun but I also think it's not a good interview farm interiew farm I don't think in the middle is an want to learn comes that's all I have for this that's all I have for this one let me know what you one let me know what you think very good so help to the mental think very good so help to the mental health have a great recipe health have a great recipe we
2024-03-22 14:03:18
805
https://i.ytimg.com/vi/H…axresdefault.jpg
805. Split Array With Same Average (Leetcode Hard)
yiUjLay-ocI
hello everyone welcome back here is vanamsen today we are diving into a vanamsen today we are diving into a super interesting coding problem number super interesting coding problem number 250 key largest element in an array so 250 key largest element in an array so it's a daily lead code Challenge and it's a daily lead code Challenge and also its classic problem very common on also its classic problem very common on uh coding interview so make sure to uh coding interview so make sure to stick around till the end okay so uh stick around till the end okay so uh here is the test guide we need to find here is the test guide we need to find the key largest element in an unsorted the key largest element in an unsorted array so sounds simple right but there array so sounds simple right but there are multiple ways to solve this problem are multiple ways to solve this problem and today we'll focus on the most and today we'll focus on the most straightforward one the sort and select straightforward one the sort and select approach all right approach all right so so app if we are given for example this Ri app if we are given for example this Ri so from 3 to yep three two one five six so from 3 to yep three two one five six four four and and key is to so task is really simple key is to so task is really simple because we need to Output the key uh because we need to Output the key uh largest element so key largest element largest element so key largest element so second largest in this case is a five so second largest in this case is a five so it's second largest and the first so it's second largest and the first largest is obviously six largest is obviously six so we'll return five okay so really so we'll return five okay so really simple test and implementation could be simple test and implementation could be also really simple so return also really simple so return sorted num reverse through key minus one sorted num reverse through key minus one so this is implementation one line of so this is implementation one line of code we are sorting and picking a key code we are sorting and picking a key number and because all right is zero number and because all right is zero indexed we are picking key minus one so indexed we are picking key minus one so as you can see for this array and key as you can see for this array and key two output is 5 so all good so uh now two output is 5 so all good so uh now let's break this down step by step so let's break this down step by step so the core idea here is quite simple uh the core idea here is quite simple uh all we are going to do is sorting the all we are going to do is sorting the number in the standing order and then number in the standing order and then just picking the key element so it's just picking the key element so it's super intuitive and starting with the super intuitive and starting with the python built in a sources function we python built in a sources function we sort the list num in reverse order that sort the list num in reverse order that means the largest element will be at the means the largest element will be at the front of our list front of our list and then the magic happened with a and then the magic happened with a last line or last part of one line code last line or last part of one line code so key minus one and remember in so key minus one and remember in programming our indices start from zero programming our indices start from zero so to get the key largest element we so to get the key largest element we need a index key minus one so basically need a index key minus one so basically the second largest number for example the second largest number for example when a key is two is on index when a key is two is on index one so this way key minus one so uh one so this way key minus one so uh so it's really a simple and time wise we so it's really a simple and time wise we are looking at are looking at n log n time complexity which is typical n log n time complexity which is typical time complexity for sourcing a list of n time complexity for sourcing a list of n elements and space so space complexity elements and space so space complexity is just oh one so constant space is just oh one so constant space complexity so that's because we are complexity so that's because we are merely sorting the original list without merely sorting the original list without using any extra space so all right let's using any extra space so all right let's give give the test for unsynthesis cases as well the test for unsynthesis cases as well uh so hopefully uh so hopefully it will work so yeah as you can see it it will work so yeah as you can see it worked all good and our implementation worked all good and our implementation uh still bit 98 uh still bit 98 other runtime so 99 other runtime so 99 88 and 84 with respect to Mineral but uh 88 and 84 with respect to Mineral but uh it's thanks to built-in uh sort in it's thanks to built-in uh sort in Python uh Python uh so yes uh that's the beauty of this so yes uh that's the beauty of this approach real Simplicity uh combined approach real Simplicity uh combined with efficiency of course there are with efficiency of course there are other methods to solve this and if you other methods to solve this and if you are interested check out the description are interested check out the description below where I have provided code in below where I have provided code in multiple languages including C plus plus multiple languages including C plus plus Java rust and go and much more and also Java rust and go and much more and also I will cover other implementation I will cover other implementation with hip with hip so if you found this video helpful make so if you found this video helpful make sure to hit the like button and share it sure to hit the like button and share it with your friends and subscribe for more with your friends and subscribe for more uh coding challenges and tutorials and uh coding challenges and tutorials and as always keep practicing happy coding as always keep practicing happy coding and
2024-03-22 10:38:41
215
https://i.ytimg.com/vi_w…xresdefault.webp
Secret Sorting LeetCode 215. Kth Largest Element in an Array - Easy Python
s8p8ukTyA2I
everyone welcome back and let's write some more neat code today so today let's some more neat code today so today let's solve the problem task scheduler one of solve the problem task scheduler one of you suggested this problem and i think you suggested this problem and i think it's a pretty good one so we're given an it's a pretty good one so we're given an array of tasks it's a character array array of tasks it's a character array and it's going to be limited to the and it's going to be limited to the characters from uppercase a to uppercase characters from uppercase a to uppercase z so 26 characters each of the z so 26 characters each of the characters represents a task and the characters represents a task and the task is something that the cpu needs to task is something that the cpu needs to process and the tasks could be processed process and the tasks could be processed in any order each task takes exactly one in any order each task takes exactly one unit of time to process so that's good unit of time to process so that's good because it makes things simple for us because it makes things simple for us and for each unit of time the cpu could and for each unit of time the cpu could either process an entire task or it either process an entire task or it could be idle and the reason it would be could be idle and the reason it would be idle is because we're also given idle is because we're also given non-negative integer input n that non-negative integer input n that represents the cooldown period between represents the cooldown period between the two same tasks and the same task is the two same tasks and the same task is represented by the same letter the same represented by the same letter the same character in the array and to understand character in the array and to understand this let's take a look at an example and this let's take a look at an example and by the way what we actually want to by the way what we actually want to return is the minimum number of units of return is the minimum number of units of time that the cpu will take to finish time that the cpu will take to finish all of the tasks let's take a look at all of the tasks let's take a look at this example we're given these tasks this example we're given these tasks right three a tasks and three b tasks right three a tasks and three b tasks and the idle time we're given is two and the idle time we're given is two units of time so basically let's say we units of time so basically let's say we processed an a task right that takes us processed an a task right that takes us one unit of time to process now we one unit of time to process now we process a b task and now we know that process a b task and now we know that before we process another a task we have before we process another a task we have to wait two units of time so you know to wait two units of time so you know let's say we process an a we can't let's say we process an a we can't process another a we have to wait two process another a we have to wait two units of time before we can process units of time before we can process another a so what are we gonna do in the another a so what are we gonna do in the meantime well there's a b as well so meantime well there's a b as well so let's process one of the b's and now for let's process one of the b's and now for this b we know we actually have to wait this b we know we actually have to wait two units of time before we can process two units of time before we can process another b another b so the next time we can process another so the next time we can process another b will be at this point in time after we b will be at this point in time after we have processed our second a so now the have processed our second a so now the question is can we fill this spot with question is can we fill this spot with anything or are we gonna have to be idle anything or are we gonna have to be idle at this point in time and there aren't at this point in time and there aren't any other characters right we had one a any other characters right we had one a and one b now we have two a's and two and one b now we have two a's and two b's remaining so we can't do anything b's remaining so we can't do anything this has to be idle we process an a a this has to be idle we process an a a second a and a second b uh that means second a and a second b uh that means that before we can process another a is that before we can process another a is gonna be two units of time so this b and gonna be two units of time so this b and then another uh unit of time and then then another uh unit of time and then another a and we also process the b the another a and we also process the b the next time we can process a b will be at next time we can process a b will be at this point in time so at this point this point in time so at this point again we are going to have to be idle again we are going to have to be idle but the good thing is that this is the but the good thing is that this is the entire um like all the tasks we were entire um like all the tasks we were looking for three a's and three b's so looking for three a's and three b's so as you can see it took us one two three as you can see it took us one two three four five six seven eight units of time four five six seven eight units of time to do this so our output is going to be to do this so our output is going to be a so now let's think about a general a so now let's think about a general approach that we could come up with to approach that we could come up with to solve this problem so let's say we had solve this problem so let's say we had this as our input first thing to notice this as our input first thing to notice is we're going to be given characters a is we're going to be given characters a through z doesn't really make sense to through z doesn't really make sense to worry about which character we're worry about which character we're looking at right there's not really not looking at right there's not really not a big difference between a b and a c but a big difference between a b and a c but we should keep track of how many of each we should keep track of how many of each character there is so we know there's character there is so we know there's three a's two b's and two c's right we three a's two b's and two c's right we don't even have to worry about the don't even have to worry about the characters anymore we can just focus on characters anymore we can just focus on the numbers we know that there's three the numbers we know that there's three of one character there's two of a of one character there's two of a different character and then two of different character and then two of another character we know that the idol another character we know that the idol time in this case is one what order time in this case is one what order should we uh process the characters in should we uh process the characters in it's probably better to process the more it's probably better to process the more frequent character first the more frequent character first the more frequent task first because we know frequent task first because we know there's going to be some idle time and there's going to be some idle time and processing the more frequent one first processing the more frequent one first basically gives us more time to not be basically gives us more time to not be idle and i'll show you the intuition idle and i'll show you the intuition behind that let's say we did a c first behind that let's say we did a c first right we do c uh we know that idle time right we do c uh we know that idle time is just one right so then let's say we is just one right so then let's say we do b and we're allowed to do another c do b and we're allowed to do another c right away let's say we do that right we right away let's say we do that right we do another c and uh then we do another b do another c and uh then we do another b because we the idle times only one right because we the idle times only one right so now we've already processed all the so now we've already processed all the the c's and the b's and all we're left the c's and the b's and all we're left with is three a's okay let's process one with is three a's okay let's process one of the a's okay great but now we have an of the a's okay great but now we have an idle time we have no other characters idle time we have no other characters available for us so we have to wait available for us so we have to wait and then we can process another a and and then we can process another a and then we wait and then process another a then we wait and then process another a so in this case this was one way but did so in this case this was one way but did this minimize the total time that it this minimize the total time that it took us to process all the tasks a took us to process all the tasks a different way would have been to start different way would have been to start with the most frequent character right a with the most frequent character right a and now there's only two a's left so now and now there's only two a's left so now what's the most frequent well you could what's the most frequent well you could say a again but we know that there is an say a again but we know that there is an idle time of at least one so at this idle time of at least one so at this point in time a is not available to us point in time a is not available to us so we have to process a different so we have to process a different character let's say a b then a is character let's say a b then a is actually going to be available for us actually going to be available for us again so we could process the a or we again so we could process the a or we could process the c in this case it could process the c in this case it doesn't really make any difference doesn't really make any difference because there's two of each of these so because there's two of each of these so we could do either one let's just do c we could do either one let's just do c so then there will be two a's one b and so then there will be two a's one b and one c then we'll of course want to do one c then we'll of course want to do the more frequent character the a and the more frequent character the a and then there's gonna be one a remaining we then there's gonna be one a remaining we can't process another a without at least can't process another a without at least one unit of idle time so let's do b and one unit of idle time so let's do b and then do c and then we can do a right then do c and then we can do a right this this also is a valid way and this one also is a valid way and this one actually minimizes the idle time rather actually minimizes the idle time rather than than this one and what is the idle time in this one and what is the idle time in this case it's about uh not the idle this case it's about uh not the idle time the total time in this case is time the total time in this case is about seven as opposed to nine in the about seven as opposed to nine in the other case so that's kind of the other case so that's kind of the intuition why we're going to intuition why we're going to try to do the more frequent task first try to do the more frequent task first and then the less frequent task how and then the less frequent task how we're going to be doing this is by using we're going to be doing this is by using a data structure called a max heap which a data structure called a max heap which will allow us to continuously figure out will allow us to continuously figure out which task is the most frequent one and which task is the most frequent one and the max heap can actually allow us to the max heap can actually allow us to determine that in log n time right if we determine that in log n time right if we have a bunch of these we could figure have a bunch of these we could figure out which is the most frequent in log in out which is the most frequent in log in time which is good but in this case time which is good but in this case actually it's even better than that it's actually it's even better than that it's about log 26 since we only have 26 about log 26 since we only have 26 different characters this is kind of a different characters this is kind of a constant time operation anyway but i constant time operation anyway but i will say that the overall time will say that the overall time complexity is still going to be big o of complexity is still going to be big o of n one because we are gonna have to you n one because we are gonna have to you know count the occurrences of each task know count the occurrences of each task so we're gonna have to go through the so we're gonna have to go through the entire uh input and we're going to be entire uh input and we're going to be you know popping every value from our you know popping every value from our max heap and adding every value to our max heap and adding every value to our max heap so the time complexity is going max heap so the time complexity is going to be big o of n that's also going to be to be big o of n that's also going to be the memory complexity but now to the the memory complexity but now to the actual algorithm itself we're actually actual algorithm itself we're actually going to use one other data structure aq going to use one other data structure aq it's not required but i think it makes it's not required but i think it makes the problem a little bit more organized the problem a little bit more organized so let's start off with the max heap so let's start off with the max heap right we have three integers we're going right we have three integers we're going to be adding integers to our max heap to be adding integers to our max heap not the characters we're going to be not the characters we're going to be taking the counts of each task and taking the counts of each task and adding that to the max heap so we're adding that to the max heap so we're going to have a three and a two and a going to have a three and a two and a another two and by the way when i another two and by the way when i actually code this up in python we don't actually code this up in python we don't have a native max heap so the way to we have a native max heap so the way to we only have a min heap so the way i get only have a min heap so the way i get around that is basically by taking each around that is basically by taking each of these values and making it negative of these values and making it negative you know in a max heap we want to pop you know in a max heap we want to pop the maximum and we can do that in log n the maximum and we can do that in log n time so in this case we'd pop the 3 time so in this case we'd pop the 3 which is the maximum but in python we're which is the maximum but in python we're actually going to do it the opposite way actually going to do it the opposite way all of these are going to be negative so all of these are going to be negative so we're going to end up popping the we're going to end up popping the minimum which is going to be negative 3 minimum which is going to be negative 3 but we're going to you know assume that but we're going to you know assume that it's a positive 3. but yeah so that's it's a positive 3. but yeah so that's the idea first we're going to pop the 3 the idea first we're going to pop the 3 or the negative 3. you can think about or the negative 3. you can think about it however you want that's the most it however you want that's the most frequent but now we want to change the frequent but now we want to change the count from being a three to now being a count from being a three to now being a two right because we just processed one two right because we just processed one of the tasks so you know if you have a of the tasks so you know if you have a negative you'll have to add one if you negative you'll have to add one if you have a positive you can decrement it to have a positive you can decrement it to one in my case when i write the code i'm one in my case when i write the code i'm going to be adding one to this but now going to be adding one to this but now we're actually going to be taking this we're actually going to be taking this and adding it to our queue data and adding it to our queue data structure because we know that there's structure because we know that there's some amount of idle time for this task some amount of idle time for this task at the current point in time we are at at the current point in time we are at initially we were at time equals zero initially we were at time equals zero but we just processed the task so now but we just processed the task so now we're at time equals one and we're going we're at time equals one and we're going to add this integer 2 or negative 2 to to add this integer 2 or negative 2 to our q our q but we're also going to be adding but we're also going to be adding another value to the queue and that's at another value to the queue and that's at what time is this task going to be what time is this task going to be available for us to process once again available for us to process once again basically at what point can we take this basically at what point can we take this and add it back to our max heap right and add it back to our max heap right what's the idle time that is going to be what's the idle time that is going to be remaining well right now we're at time remaining well right now we're at time equals one and our idle time for each equals one and our idle time for each task is n equals one so basically we're task is n equals one so basically we're gonna take n gonna take n and add it to our current time so it's and add it to our current time so it's gonna be two basically at time equals gonna be two basically at time equals two this task is gonna be available for two this task is gonna be available for us to add to the heap again so that's us to add to the heap again so that's what the second value in this case means what the second value in this case means and once again we're going to pop from and once again we're going to pop from our max heap we're going to pop the our max heap we're going to pop the negative 2 and that means we have negative 2 and that means we have processed the task so now our time is processed the task so now our time is actually going to be time equals 2. actually going to be time equals 2. we're going to take that task it was a we're going to take that task it was a negative 2. we're going to add 1 to it negative 2. we're going to add 1 to it which is going to make it a negative 1. which is going to make it a negative 1. so then we're going to take that so then we're going to take that negative 1 and add it to our q negative 1 and add it to our q and at what time is that task going to and at what time is that task going to be available to add back to our max heap be available to add back to our max heap well it's going to be 2 plus 1 because n well it's going to be 2 plus 1 because n is 1 in our case so at time equals 3 is 1 in our case so at time equals 3 this task can be added back to our max this task can be added back to our max heap but now that we're at time equals 2 heap but now that we're at time equals 2 we see that this task actually is we see that this task actually is available now to add back to our heap so available now to add back to our heap so let's pop it from our q and take the let's pop it from our q and take the negative 2 and add it back to our max negative 2 and add it back to our max heap and at this point you're probably heap and at this point you're probably starting to get the idea so i'll just starting to get the idea so i'll just kind of fast forward through this we're kind of fast forward through this we're going to pop this again set our time now going to pop this again set our time now equal to 3. we're going to take that equal to 3. we're going to take that negative 2 add 1 to it so it'll be a negative 2 add 1 to it so it'll be a negative 1. we'll add that to our heap negative 1. we'll add that to our heap at time equals 4 it's going to be at time equals 4 it's going to be available for us to add back to the heap available for us to add back to the heap this value can be popped from our queue this value can be popped from our queue we can add a negative 1 here and then we can add a negative 1 here and then start the cycle over so let's pop this start the cycle over so let's pop this value over here uh add it to our q we're value over here uh add it to our q we're running out of space so let's add a running out of space so let's add a little bit more space uh that negative little bit more space uh that negative two will become a negative one the time two will become a negative one the time now will actually be four so the time now will actually be four so the time that this can be popped it's going to be that this can be popped it's going to be at time five we see it's time for so at time five we see it's time for so this can now be popped so we add that this can now be popped so we add that back to our uh heap negative one and now back to our uh heap negative one and now it's time equals four so i'm really it's time equals four so i'm really going to fast forward through this it'll going to fast forward through this it'll take one more unit of time to process take one more unit of time to process this task but now this task as you can this task but now this task as you can see we're going to pop it it's a see we're going to pop it it's a negative 1 we're going to add 1 to it so negative 1 we're going to add 1 to it so now it's going to be 0 right 0 once a now it's going to be 0 right 0 once a task becomes 0 we know that we don't task becomes 0 we know that we don't have to process it anymore right so when have to process it anymore right so when it's 0 we're not going to add it to our it's 0 we're not going to add it to our q because it doesn't have to be idle q because it doesn't have to be idle it's never going to be added back to the it's never going to be added back to the max heap once it's zero we're not going max heap once it's zero we're not going to do anything with it so uh you know we to do anything with it so uh you know we pop it from our max heap and there's pop it from our max heap and there's nothing left but we see that this value nothing left but we see that this value over here and right now it's going to be over here and right now it's going to be time equals five actually so time is time equals five actually so time is five this can be added back to our max five this can be added back to our max heap heap let's add that negative one sorry if let's add that negative one sorry if it's getting a little bit messy but next it's getting a little bit messy but next we're gonna pop this from our max heap we're gonna pop this from our max heap it's gonna become zero so we don't add it's gonna become zero so we don't add it to our queue now it's gonna be time it to our queue now it's gonna be time equals six after we process that task equals six after we process that task and lastly we have one task remaining we and lastly we have one task remaining we pop it we process it it becomes zero we pop it we process it it becomes zero we don't add it to the queue so now after don't add it to the queue so now after processing that task our time is seven processing that task our time is seven so we can return seven in this case and so we can return seven in this case and that's pretty much the entire algorithm that's pretty much the entire algorithm so that's what i'm going to be following so that's what i'm going to be following even though popping and pushing to a max even though popping and pushing to a max heap is usually a login operation in heap is usually a login operation in this case it's really going to be a log this case it's really going to be a log 26 operation so the overall time 26 operation so the overall time complexity in this case is really just complexity in this case is really just big o of n because we have to just go big o of n because we have to just go through every single task okay now let's through every single task okay now let's write the code okay so now let's code it write the code okay so now let's code it up and you can see i have a couple up and you can see i have a couple comments just to kind of help simplify comments just to kind of help simplify things for us and i usually don't do things for us and i usually don't do this but we want to count the this but we want to count the occurrences of each character in the occurrences of each character in the input it's a list of strings we could input it's a list of strings we could just you know run through that loop just you know run through that loop through that and add it to a hash map through that and add it to a hash map but you can actually do that with a but you can actually do that with a built-in way in python just using a built-in way in python just using a counter which is literally a hash map counter which is literally a hash map it'll just do that for us so we don't it'll just do that for us so we don't have to write the code but now we have to write the code but now we actually want to create our max heap actually want to create our max heap using those counts themselves uh we can using those counts themselves uh we can do that in python with one line of code do that in python with one line of code we're just going to iterate through each we're just going to iterate through each count in count in the the hashmap that we just created but we want hashmap that we just created but we want to only iterate through the values so to only iterate through the values so count.values and we want to add that to count.values and we want to add that to our hashmap but in python's case we our hashmap but in python's case we can't have a max heap this is actually a can't have a max heap this is actually a min heap after we heapify it so i'm min heap after we heapify it so i'm actually going to take the negative of actually going to take the negative of the count and add it so this is just the count and add it so this is just creating an array with every negative creating an array with every negative count that we computed but to actually count that we computed but to actually turn it into a heap turn it into a heap we can do we can do heapq.heapify in python and to that max heapq.heapify in python and to that max heap and it'll basically order it it'll heap and it'll basically order it it'll take this array and order it in such a take this array and order it in such a way that it is a max heap basically for way that it is a max heap basically for us to efficiently get the maximum value us to efficiently get the maximum value from from the heap whenever we want it we're also the heap whenever we want it we're also going to declare a variable to keep going to declare a variable to keep track of what time it is initially we'll track of what time it is initially we'll set that to zero and we'll also have a q set that to zero and we'll also have a q in this case a double ended queue and in this case a double ended queue and the double ended queue is gonna actually the double ended queue is gonna actually contain a pair of values and the pair of contain a pair of values and the pair of values are gonna be that negative count values are gonna be that negative count that we had up above and for that uh you that we had up above and for that uh you know task that count know task that count the corresponding idle time at what time the corresponding idle time at what time is it going to be available for us to is it going to be available for us to add back to the add back to the max heap okay so with that said we're max heap okay so with that said we're gonna continue uh our loop we're gonna gonna continue uh our loop we're gonna continue processing these tasks while continue processing these tasks while the max heap is non-empty but end or not the max heap is non-empty but end or not and but or the and but or the cue is not empty right as long as one of cue is not empty right as long as one of these is not empty that means we have these is not empty that means we have more tasks that we need to process more tasks that we need to process so as we process so as we process each iteration of the loop is just going each iteration of the loop is just going to increment the time by exactly one and to increment the time by exactly one and actually before i even forget i actually before i even forget i mentioned that the time complexity of mentioned that the time complexity of this whole algorithm is going to be big this whole algorithm is going to be big o of n but that's not entirely correct o of n but that's not entirely correct let's say n is the size of our tasks we let's say n is the size of our tasks we can add one more variable let's call it can add one more variable let's call it m where m actually represents what the m where m actually represents what the idle time is because in the worst case idle time is because in the worst case you know we have to go through that idle you know we have to go through that idle time for each task that we have write time for each task that we have write suppose that the tasks was just an array suppose that the tasks was just an array of all a's of all a's in that case we'd have to you know go in that case we'd have to you know go through the idle time for each task but through the idle time for each task but the idle time is actually a pretty small the idle time is actually a pretty small constant i think it's less than 100 in constant i think it's less than 100 in our case but just wanted to mention that our case but just wanted to mention that in case but okay now let's continue with in case but okay now let's continue with the algorithm so at each iteration of the algorithm so at each iteration of loop we're going to increment the time loop we're going to increment the time by one if the max heap is non-empty we by one if the max heap is non-empty we are going to pop from it and we can do are going to pop from it and we can do that with heap q dot heap pop from the that with heap q dot heap pop from the max heap and from it we're gonna get the max heap and from it we're gonna get the count and as we uh pop from the heap count and as we uh pop from the heap that means we're processing this task so that means we're processing this task so to the count itself we can actually add to the count itself we can actually add one to it because remember we're one to it because remember we're actually using negative values for the actually using negative values for the counts if you were using positive values counts if you were using positive values you'd probably subtract one from it but you'd probably subtract one from it but in our case we're going to be adding one in our case we're going to be adding one to it and if this count is non-zero we to it and if this count is non-zero we can check that uh like this if count is can check that uh like this if count is non-zero then we want to go ahead and non-zero then we want to go ahead and append it to our queue and we can do append it to our queue and we can do that like this we're gonna append a pair that like this we're gonna append a pair of values the count itself and the time of values the count itself and the time that it's going to be available again that it's going to be available again and we can get that by taking our time and we can get that by taking our time our current time adding to it the idle our current time adding to it the idle time n so at this time we can once again time n so at this time we can once again add it to our maxi okay that's great we add it to our maxi okay that's great we process a task we remove it from the max process a task we remove it from the max heap but remember we also have to take heap but remember we also have to take care of our queue if our queue is care of our queue if our queue is non-empty and the first value in our non-empty and the first value in our queue at index 0 queue at index 0 the idle time for it which is also the idle time for it which is also it was actually going to be at index one it was actually going to be at index one because it's the second value in the because it's the second value in the pair so if this time has just been pair so if this time has just been reached so if this is equal to the reached so if this is equal to the current time that means you know we can current time that means you know we can actually pop this from our queue so actually pop this from our queue so we're going to say q dot popped left and we're going to say q dot popped left and so this is actually going to pop that so this is actually going to pop that pair of values and from that pair of pair of values and from that pair of values we care about the first one which values we care about the first one which is the count so we're going to get an is the count so we're going to get an index of zero but actually that value index of zero but actually that value itself what do we want to do we just itself what do we want to do we just want to add it back to our max heap so want to add it back to our max heap so we can do that with heap cue.heat push we can do that with heap cue.heat push we're going to take it add it to our max we're going to take it add it to our max heap so let's just copy and paste this heap so let's just copy and paste this and uh move it up above so the only and uh move it up above so the only thing left for us to do is once thing left for us to do is once everything has been processed for our everything has been processed for our max heap and our queue we can just go max heap and our queue we can just go ahead and return the time that it took ahead and return the time that it took us to do all that work let's just clean us to do all that work let's just clean this up a little bit that's the entire this up a little bit that's the entire code so now let's just run it to make code so now let's just run it to make sure that it actually works and as you sure that it actually works and as you can see on the left yes it does work and can see on the left yes it does work and it's pretty efficient i do want to it's pretty efficient i do want to mention there actually is a different mention there actually is a different solution for this that's actually a solution for this that's actually a little bit more of a true linear time little bit more of a true linear time solution but i think it's a lot less solution but i think it's a lot less intuitive and i think this solution is intuitive and i think this solution is perfectly fine for interviews and perfectly fine for interviews and because it's more of an intuitive because it's more of an intuitive solution i think this is solution i think this is more or less what interviewers would more or less what interviewers would expect you to come up with so i really expect you to come up with so i really hope that this was helpful if it was hope that this was helpful if it was please like and subscribe it really please like and subscribe it really supports the channel a lot consider supports the channel a lot consider checking out my patreon where you can checking out my patreon where you can further support the channel and further support the channel and hopefully i'll see you pretty soon hopefully i'll see you pretty soon thanks for watching
2024-03-20 12:31:18
621
https://i.ytimg.com/vi_w…xresdefault.webp
Task Scheduler - Leetcode 621 - Python
Re056WGtFRU
hello everyone welcome back here is Van Amazon and today we are diving into a Amazon and today we are diving into a fascinating problem on uh lead code the fascinating problem on uh lead code the frog jump problem so you will understand frog jump problem so you will understand the logic behind the solution and how to the logic behind the solution and how to implement it in Python and for those of implement it in Python and for those of you who prefer other languages don't you who prefer other languages don't worry I will provide implementation in worry I will provide implementation in the description below so all right let's the description below so all right let's quickly go over the problem statement so quickly go over the problem statement so the task here is simple we have a river the task here is simple we have a river divided into units and at each unit divided into units and at each unit there might be a stone and our frog can there might be a stone and our frog can only jump on Stones not in water and the only jump on Stones not in water and the Frog starts on the first stone and Frog starts on the first stone and the initial jump is always one unit and the initial jump is always one unit and after that if the Frog last jump was a after that if the Frog last jump was a key units its next jump could be a key key units its next jump could be a key -1 key or key plus uh one so the goal is -1 key or key plus uh one so the goal is to determine if the Frog can cross the to determine if the Frog can cross the river by landing on the last uh Stone so river by landing on the last uh Stone so let's take some examples so example let's take some examples so example number one we are given a stand position number one we are given a stand position so it's zero one three five six eight so it's zero one three five six eight twelve and Seventeen and our frog starts twelve and Seventeen and our frog starts at position 0 and it first jump one unit at position 0 and it first jump one unit to position one then two two three and to position one then two two three and two two you need five and so on and the two two you need five and so on and the Frog eventually lands on the last stone Frog eventually lands on the last stone at position at position 70. so the answer here is 70. so the answer here is true so now that we got a grasp on the problem let's start coding our solution so uh the approach I'm taking here is using dynamic programming so for each Stone position we'll keep track of all possible jump distance that can land the frog on that stone so at the beginning of our frog is at position zero and can only jump one unit so we initialize our DP dictionary with the first stone position as set containing the value 1. DP and 4 Stone DP and 4 Stone in stones in stones DP Stone will be set DP Stone will be set and DP and DP at zero at zero at one at one so and now for istan in our list we will so and now for istan in our list we will iterate through all possible Jam iterate through all possible Jam distance record in our DP dictionary and distance record in our DP dictionary and for each possible jump distance we will for each possible jump distance we will calculate the next Stone position so if calculate the next Stone position so if this next Sun exists in our list we will this next Sun exists in our list we will add the possible jump distance to its add the possible jump distance to its set in the DP dictionary so for stone set in the DP dictionary so for stone in in stones stones for key in DP Stone next Stone will be and if next Stone and if next Stone in DP if key minus 1 greater than zero DP next turn at Key minus 1 and DP next turn key and DP next turn and and return line of the Piston greater than a return line of the Piston greater than a zero admin minus one so zero admin minus one so the final step is to check if there are the final step is to check if there are any jump distance recorded for the last any jump distance recorded for the last Stone so if there are it means our Vlog Stone so if there are it means our Vlog can reach the last tone so let's run can reach the last tone so let's run this implementation this implementation so hopefully it will so hopefully it will work okay so type for stone in Stones so yeah all good and now uh let's submit it for unsynthesis cases as well so it's running and yep as you can see uh it bit 80 with respect to random and also 81 with respect to a memory and work for all test cases and uh it's a beautifully combination of both dynamic programming and set operation and time complexity is quite acceptable so it's all n square and for the problem constraint and at this wrap up our solution for the frog jump problem and I hope you found this session insightful and for those of you looking for implementation in other programming languages uh Link in the description below and if you enjoyed this session don't forget to hit the like button sure eat with your friends and of course subscribe for more coding content and leave your thoughts and question in the comment section below and as always keep practicing happy coding and see you next
2024-03-21 18:43:59
403
https://i.ytimg.com/vi_w…xresdefault.webp
Master Dynamic Programming LeetCode 403. Frog Jump Problem! 🐸 | Must-Watch for Coding Interviews
7pOzP9m_bX8
all right so this leap code question is called Pascal's triangle it says given a non-negative integer num rows generate the first num rows of Pascal's triangle in Pascal's triangle each number is the sum of the two numbers directly above it so if you take the number two it's the combination of 1 and 1 if you take the number 3 it's the combination of 1 and 2 if you take the number 6 it's the combination of 3 and 3 so the example is an input of 5 and what we get is a triangle made up of arrays with 5 rows with as we said before each number being the sum of the two elements above it all right so this is Pascal's triangle it's just a series of numbers where each row is made up of numbers that are themselves made up of the two numbers in the row above them so when I first try to solve this problem I try to come up with some crazy formula but it turns out a lot of it is just manual and I'll show you what I mean so let's start with the first row with the first row all we have to do is manually add an array with the number 1 in it and then with every row from then on the ones that we're seeing they're all gonna be added manually let me just undo all that so with this row what do we do we manually add the number 1 another thing to note is that the number of elements between the ones is always 1 less than the row count above it so let's take this number 2 there's one element between these ones and the row above it is row 2 two minus one is one let's go to the next row which row is above the row with the 3s in it it's row three so how many elements are in between the ones in this row 3 minus 1 which is 2 and let's go to the final row which row is above this through a 1 2 3 4 so how many elements are between the ones in this row 4 minus 1 which is 3 all right let me undo a bunch of that to not make it messy knowing that how many elements are going to be between the ones in this row the row above it is Row 1 what's 1 minus 1 0 so they're going to be 0 elements in between the ones in this row so like I said all the ones we're seeing are manually added so when we're done doing the calculation we just did we just manually add a 1 at the end of this row now let's go to the next row remember the first thing to do is to just manually add a 1 now how do we get the next element let's see if we can find a pattern we know the next element is going to be a combination of these two numbers the indices of these two numbers are 0 & 1 the index for the number we need is 1 so we know that the elements that we need to add are always the elements in the row above with the indices of 1 less than the index we're on so right now we're on index 1 so we need index 0 and the element with the same index so the elements 0 & 1 add up to 2 now what do we do we manually add the number 1 let's do it one more time so new row manually add the number 1 which has an index of 0 how many elements do we need between to number ones in this row the row above it is Row three so you subtract one from that which means you need two elements between the ones so we're going to need an element at index one and an element at index two and as we know now we look at the elements in the previous row with an index one less than the index were on and an index of the same index were on so we're on index one so we need indices zero and one and that'll be three same logic for the next one we're at index two so what do we need to add up we need to add up the index of 1 1 less than we're on + 2 which is the index we're on what does that come out to it also comes out to the number 3 and then finally since we've added all the elements between the ones we now just manually add the last number 1 so let's clean this up a bit so this is what our array would look like so far all right so let's start out with what lead code has given us it's a function called generate and it accepts a variable called num rows which represents the number of rows our Pascal's triangle needs to have all right let's start out this way the way our triangle is represented is actually just an array so that's what we're going to return at the end what we have to do with this array is push in arrays inside of it and each array we push in can be so in the end this is what it actually so in the end this is what it actually looks like but more in the Pascal's looks like but more in the Pascal's triangle form this array would have a triangle form this array would have a row count of two ignore the opening and row count of two ignore the opening and closing brackets alright so now that closing brackets alright so now that we've said that will create a new we've said that will create a new variable called triangle and we'll make variable called triangle and we'll make it the empty array next we'll check the it the empty array next we'll check the numbers variable that's passed in and if numbers variable that's passed in and if it's zero then we'll just return the it's zero then we'll just return the triangle as it is now which is empty so triangle as it is now which is empty so if num rows is zero then the triangle if num rows is zero then the triangle has no rows has no rows so we'll just return the empty array so so we'll just return the empty array so return triangle all right now we'll do return triangle all right now we'll do our first manual step which is to our first manual step which is to manually create the first throat so what manually create the first throat so what we'll do is we'll say triangle dot push we'll do is we'll say triangle dot push and what are we pushing the first row and what are we pushing the first row the first row only has one element in it the first row only has one element in it of the number one all right let me do of the number one all right let me do some cleanup before we move on at this some cleanup before we move on at this point this is what our triangle looks point this is what our triangle looks like alright now we need a for loop to like alright now we need a for loop to populate each row so we'll say for let I populate each row so we'll say for let I equal 1 usually we started I equals 0 equal 1 usually we started I equals 0 but we already have our zeroth row and but we already have our zeroth row and that's just the number 1 that's that's just the number 1 that's represented to the left so we'll do i is represented to the left so we'll do i is less than numbers and then i plus plus a less than numbers and then i plus plus a pretty standard for loop now remember pretty standard for loop now remember one of the keys to solving this problem one of the keys to solving this problem is to look at the row in front of us so is to look at the row in front of us so we would need a reference to that row so we would need a reference to that row so let Prevot equal triangle i minus 1 let Prevot equal triangle i minus 1 right now this is the previous row so right now this is the previous row so this is the row we're talking about all this is the row we're talking about all right and now we have to create a new right and now we have to create a new row so let new row equal an empty array row so let new row equal an empty array this is what we have so far all right this is what we have so far all right now comes another manual step remember now comes another manual step remember we are manually adding the number one at we are manually adding the number one at the beginning and at the end of each row the beginning and at the end of each row so we need to add the one at the so we need to add the one at the beginning so new Rho dot push the number beginning so new Rho dot push the number one so that'll be this now we need to one so that'll be this now we need to populate the interior of each row and populate the interior of each row and the way we do that is with another for the way we do that is with another for loop so for let and we'll create a loop so for let and we'll create a variable J this time equal one why is it variable J this time equal one why is it one when we usually start at zero it's one when we usually start at zero it's one because we already have an element one because we already have an element at the 0th position of our new row and at the 0th position of our new row and that element is always the number 1 so that element is always the number 1 so now we just stop when J is less than the now we just stop when J is less than the length of the previous row and then we length of the previous row and then we do J plus plus another pretty standard do J plus plus another pretty standard for loop in the row we're on now this for loop in the row we're on now this loop actually isn't going to do anything loop actually isn't going to do anything it's going to be skipped why is that it's going to be skipped why is that because J is 1 and we're saying we go because J is 1 and we're saying we go until J is less than the previous rows until J is less than the previous rows length the previous rows length is 1 so length the previous rows length is 1 so we can never enter this loop and will we can never enter this loop and will only enter if J is more than 1 but we only enter if J is more than 1 but we still have to populate it for future still have to populate it for future rows so remember we said that every rows so remember we said that every element in this step is just a sum of element in this step is just a sum of the two elements above it one being the the two elements above it one being the one with the index one less than it and one with the index one less than it and one with the same index as it so that'll one with the same index as it so that'll look like neuro dot push the previous look like neuro dot push the previous row row J minus 1 plus previous row J so again J minus 1 plus previous row J so again let's pretend real quick that the let's pretend real quick that the previous row was I don't know 1 2 1 the previous row was I don't know 1 2 1 the indices are 0 1 2 the array below it indices are 0 1 2 the array below it would need the indices 0 1 2 3 index 1 would need the indices 0 1 2 3 index 1 will be made up of index 0 & 1 above it will be made up of index 0 & 1 above it and index 2 would be made up of index 1 and index 2 would be made up of index 1 & 2 above it so it's always the index & 2 above it so it's always the index were on minus 1 plus the index were on were on minus 1 plus the index were on ok so let's just get rid of that to make ok so let's just get rid of that to make it cleaner ok so now we're done with it cleaner ok so now we're done with that for loop what do we do next this is that for loop what do we do next this is just another manual step we already just another manual step we already pushed in the number 1 at the beginning pushed in the number 1 at the beginning so now we have to finish it off by so now we have to finish it off by pushing in the one at the end so a new pushing in the one at the end so a new row dot push the number 1 so that'll be row dot push the number 1 so that'll be this and the final step in this for loop this and the final step in this for loop is even though I've drawn it so far to is even though I've drawn it so far to make it look like our tray fits into the make it look like our tray fits into the outer array it actually hasn't so far outer array it actually hasn't so far it's really been like this with our it's really been like this with our array not being inside of it yet so the array not being inside of it yet so the final step is to push our array into the outer array so that'll be triangle which is the outer array push the new row we just created alright so now that for loop would go for as many times as the rows that we've passed in and what's the final step it's to just return the triangle array which would be this whole thing okay let's test the code oh I missed parenthesis try it again looks good alright so the answer was accepted it alright so the answer was accepted it was faster than about 19 percent of was faster than about 19 percent of JavaScript submissions as usual the code JavaScript submissions as usual the code and written description are linked down and written description are linked down below if you like the video just give it below if you like the video just give it a like and subscribe to the channel see a like and subscribe to the channel see you next time
2024-03-21 11:01:23
118
https://i.ytimg.com/vi/7…axresdefault.jpg
Pascal’s Triangle | LeetCode 118 | Coding Interview Tutorial
Id_tqGdsZQI
everyone welcome back and let's write some more neat code today so today let's some more neat code today so today let's solve the problem baseball game even solve the problem baseball game even though this has practically nothing to though this has practically nothing to do with baseball maybe that's why it has do with baseball maybe that's why it has so many dislikes because other than that so many dislikes because other than that i think it's a pretty good problem it's i think it's a pretty good problem it's very logical there's no crazy tricks very logical there's no crazy tricks behind it but i'm just gonna skip the behind it but i'm just gonna skip the first paragraph because it's pretty first paragraph because it's pretty useless if this problem teaches you useless if this problem teaches you anything it's basically how to kind of anything it's basically how to kind of filter out the unnecessary information filter out the unnecessary information when you're reading a problem which is when you're reading a problem which is actually a somewhat useful skill so at actually a somewhat useful skill so at the beginning of the game we start with the beginning of the game we start with an empty record we're given a list of an empty record we're given a list of operations where each of the operation operations where each of the operation could be one of the four following it could be one of the four following it could be some integer could be some integer given in the form of a string as you can given in the form of a string as you can see they don't really mention that but see they don't really mention that but yes it's given as a string in this case yes it's given as a string in this case there's five there's two now they there's five there's two now they mention at the bottom of the problem mention at the bottom of the problem that the integer itself could be i think that the integer itself could be i think a value somewhere between negative a a value somewhere between negative a thousand and positive a thousand so it thousand and positive a thousand so it might not just be one digit so you have might not just be one digit so you have to kind of keep that in mind but the to kind of keep that in mind but the other three operations are one is a plus other three operations are one is a plus symbol what that means is we're going to symbol what that means is we're going to add the two previous scores that we were add the two previous scores that we were given in operations together and we're given in operations together and we're guaranteed that there are going to be at guaranteed that there are going to be at least two previous scores so one thing least two previous scores so one thing we're kind of learning is that we're we're kind of learning is that we're going to need to kind of memorize what going to need to kind of memorize what the previous scores were at least two of the previous scores were at least two of them and the third one is a d that means them and the third one is a d that means we're gonna double the previous score we're gonna double the previous score the single previous score and it's the single previous score and it's guaranteed that there will be at least guaranteed that there will be at least one previous score the last one is going one previous score the last one is going to be the letter c which means we're to be the letter c which means we're gonna invalidate the previous score gonna invalidate the previous score basically removing it from the record basically removing it from the record now what this means is we can't just now what this means is we can't just keep track of the two previous scores we keep track of the two previous scores we have to keep track of all of them have to keep track of all of them because what if we have a ton of c's in because what if we have a ton of c's in a row that means we have to invalidate a row that means we have to invalidate the previous one then the next one then the previous one then the next one then the next one and keep doing that this the next one and keep doing that this kind of hints to us since we're going to kind of hints to us since we're going to be adding scores and removing scores a be adding scores and removing scores a data structure to do that data structure to do that is going to be a stack because as we add is going to be a stack because as we add we're going to be adding to the end of we're going to be adding to the end of the stack as we remove in this case the stack as we remove in this case we're also going to be removing from the we're also going to be removing from the end of the stack so a stack data end of the stack so a stack data structure we can do both of those structure we can do both of those operations in big o of one time after operations in big o of one time after we've gone through every operation what we've gone through every operation what we want to do at the end is just take we want to do at the end is just take the sum of all of the scores and return the sum of all of the scores and return it so if you couldn't tell before yes we it so if you couldn't tell before yes we definitely need to keep track of every definitely need to keep track of every single score so that we can at least sum single score so that we can at least sum it at the end so now let's just quickly it at the end so now let's just quickly run through this example and then let's run through this example and then let's code it up so first we're just going to code it up so first we're just going to iterate through all of the operations iterate through all of the operations starting at the beginning so this time starting at the beginning so this time we have a five what we can do in the we have a five what we can do in the code is first just check is it a plus code is first just check is it a plus nope is it a d nope is it a c nope so nope is it a d nope is it a c nope so that must mean it's an integer that's that must mean it's an integer that's probably the easiest way for us to probably the easiest way for us to detect that otherwise we could use some detect that otherwise we could use some kind of built-in function to check if kind of built-in function to check if it's an integer but it's easier to just it's an integer but it's easier to just have this be the else case so it's a have this be the else case so it's a five so what we do is keep track of it five so what we do is keep track of it we're gonna record it we have a five we're gonna record it we have a five next we get another integer two let's next we get another integer two let's record it and then move on next we get record it and then move on next we get ac what do we do when we get a c we ac what do we do when we get a c we invalidate the previous score so to do invalidate the previous score so to do that we're going to do a very simple pop that we're going to do a very simple pop operation on our stack so we're operation on our stack so we're invalidating the last one so as so at invalidating the last one so as so at the end when we sum all of the scores the end when we sum all of the scores we're not going to include this one next we're not going to include this one next we get to a d d means we're going to we get to a d d means we're going to double the previous score now the double the previous score now the previous score is not 2 because we previous score is not 2 because we invalidated it the previous one is going invalidated it the previous one is going to be 5. we'll know that because we're to be 5. we'll know that because we're just going to take the top of our stack just going to take the top of our stack which is gonna be five so we're gonna which is gonna be five so we're gonna take double five and we're gonna add 10 take double five and we're gonna add 10 to the stack last we have is a plus plus to the stack last we have is a plus plus means we're going to take the sum of the means we're going to take the sum of the two previous scores we're guaranteed to two previous scores we're guaranteed to have them and we do have them we have a have them and we do have them we have a 5 and we have a 10 we take the two 5 and we have a 10 we take the two previous ones add them together we get previous ones add them together we get 15 and then we add 15 to the stack now 15 and then we add 15 to the stack now and that's it we went through every and that's it we went through every single one of these so this is our stack single one of these so this is our stack we have three values what we're going to we have three values what we're going to do is add all three of the values do is add all three of the values together we're going to get a total of together we're going to get a total of 30 and then that's what we're going to 30 and then that's what we're going to return and that's exactly what they return and that's exactly what they expected so now let's code it up okay so expected so now let's code it up okay so now let's code it up first we're going now let's code it up first we're going to just initialize our stack it's going to just initialize our stack it's going to be empty initially and then we're to be empty initially and then we're just going to go through every single op just going to go through every single op in the input array and then just kind of in the input array and then just kind of write out the if statements we know that write out the if statements we know that one is a plus another one is if we have one is a plus another one is if we have a d a d and another one is if we have a capital and another one is if we have a capital c and then the last one is just going to c and then the last one is just going to be the else case where we have a number be the else case where we have a number so if we had a positive that means we're so if we had a positive that means we're going to take the sum of the two going to take the sum of the two previous scores and add them together so previous scores and add them together so we're guaranteed that they exist in we're guaranteed that they exist in python you can get the last value in an python you can get the last value in an array or a stack by taking the negative array or a stack by taking the negative one index or we could take the length of one index or we could take the length of the stack minus one and to get the the stack minus one and to get the second to last one we can take a second to last one we can take a negative two index or we could just take negative two index or we could just take the length of the stack minus two either the length of the stack minus two either way you can do it but this is easier in way you can do it but this is easier in python we're gonna take the sum of those python we're gonna take the sum of those and then append that to the stack so and then append that to the stack so that covers that case if we have a d that covers that case if we have a d we're going to take double the previous we're going to take double the previous value so to get the previous value value so to get the previous value similarly we're just going to take the similarly we're just going to take the negative one index and then we're going negative one index and then we're going to double it so two times that and then to double it so two times that and then we're going to append that to our stack we're going to append that to our stack so also not too bad and then the last uh so also not too bad and then the last uh the c case is where we're invalidating the c case is where we're invalidating the previous one so we're not adding to the previous one so we're not adding to the stack this time we're popping we're the stack this time we're popping we're popping the last value that was added to popping the last value that was added to the stack and then the last case is the stack and then the last case is suppose that op happens to be a number suppose that op happens to be a number so this time we're actually using off so this time we're actually using off we're going to take up and we're going we're going to take up and we're going to come uh convert it from being a to come uh convert it from being a string into being an actual integer string into being an actual integer somewhere between negative a thousand somewhere between negative a thousand and positive a thousand and then we're and positive a thousand and then we're gonna append that to our stack after gonna append that to our stack after we've gone through every operation and we've gone through every operation and done that all we need to do is take the done that all we need to do is take the sum of our stack so now let's run it to sum of our stack so now let's run it to make sure that it works and as you can make sure that it works and as you can see on the left yes it does and it's see on the left yes it does and it's pretty efficient so the overall time pretty efficient so the overall time complexity was big o of n because we're complexity was big o of n because we're just iterating through every single just iterating through every single input and yes we might be adding to the input and yes we might be adding to the stack and we might also be popping but stack and we might also be popping but we're only going to pop as many values we're only going to pop as many values that we could have added to the stack so that we could have added to the stack so it's going to be big o of n where n is it's going to be big o of n where n is the size of the input array and of the size of the input array and of course we're taking the sum of the stack course we're taking the sum of the stack at the end but that's also a big of n at the end but that's also a big of n time operation so the overall time time operation so the overall time complexity is bigger of n the memory complexity is bigger of n the memory complexity is also bigger of n because complexity is also bigger of n because we have the stack and the stack could be we have the stack and the stack could be of size that's the same as the input of size that's the same as the input array so i really hope that this was array so i really hope that this was helpful if it was please like and helpful if it was please like and subscribe it really supports the channel subscribe it really supports the channel a lot consider checking out my patreon a lot consider checking out my patreon where you can further support the where you can further support the channel and hopefully i'll see you channel and hopefully i'll see you pretty soon thanks for watching
2024-03-20 16:05:05
682
https://i.ytimg.com/vi_w…xresdefault.webp
Baseball Game - Leetcode 682 - Python
fM4L_dIKA1c
yo yo whatsapp vyas going students should be given all circulars question which question which is the read and tagged as given read is the read and tagged as given read most loudly okay what is this is like and he is give give a video a video liquid liquid liner liner person subscribe - Abdominal Total and Guys So - Abdominal Total and Guys So - Abdominal Total and Guys So Lutab Lutab Skin Thing Examples Click subscribe and subscribe and don't forget to subscribe this channel and don't forget to subscribe this channel and my channel hotspot of account hotspot of account wounded the value from the end poor 500 wounded the value from the end poor 500 99999 likes for 99999 likes for creative they creative they can can can my favorite song new kya hai and number five I will clear like total number of but if they continue it is 0.1 total this is fixed total number of but if video 9th step people rule swine flu and should You should delete and You should delete and You should delete and ok that agar noida will calculate deactivate eligible account for advertisement bhavya help does not matter if they compare account to man - that sorry point no what do it i will benefit my distemper active valley that i plus channel that i plus channel Lots of total Lots of total plus it is exempted a taboo plus it is exempted a taboo 548 not seen in defiance of water and 548 not seen in defiance of water and of the lambs of the lambs pet services pet services replacement for replacement for play subscribe that if source code so what is due to have adopted in under temple run ok in over her mistake is Press Club At Its Okay Press Club At Its Okay Press Club At Its Okay Subscribe Abs Who Is Is The Value Of Subscribe And Kidar Hai Kidar Hai A Boom Help 200r In This Question Time A Boom Help 200r In This Question Time Complexity Of Complexity Of Android My Space Complexities Of Android My Space Complexities Of Saunf This Question Saunf This Question Screamed Use Channel To Screamed Use Channel To Subscribe Take Care See You Subscribe Take Care See You Subscribe Take Care See You Video Song
2024-03-21 13:33:31
157
https://i.ytimg.com/vi/f…axresdefault.jpg
LEETCODE - 157 || Read N Characters Given Read4 || LeetCode Plus Question || Easy solution
RRSItF-Ts4Q
in this video we'll go over Lee code question number 141 link list cycle question number 141 link list cycle given the head to a linked list we need given the head to a linked list we need to return true if there is a cycle in to return true if there is a cycle in the linked list or return false if there the linked list or return false if there isn't one so what exactly is a cycle in isn't one so what exactly is a cycle in a linked list well a linked list a linked list well a linked list consists of nodes and pointers to the consists of nodes and pointers to the next node in the list and normally the next node in the list and normally the last pointer points to a null value to last pointer points to a null value to Signal the end of the list but if Signal the end of the list but if instead of pointing to null the last instead of pointing to null the last pointer points back at some other node pointer points back at some other node in the linked list there is now a cycle in the linked list there is now a cycle and if you try to Traverse this linked and if you try to Traverse this linked list you could keep traversing it list you could keep traversing it forever and never reach the end so now forever and never reach the end so now the question is how can we detect a the question is how can we detect a cycle in a linked list to solve this cycle in a linked list to solve this we'll be using an algorithm commonly we'll be using an algorithm commonly known as The Tortoise and hair algorithm known as The Tortoise and hair algorithm here's how it works we start by here's how it works we start by initializing two pointers a slow pointer initializing two pointers a slow pointer and a fast pointer the slow pointer will and a fast pointer the slow pointer will Traverse the linked list one node at a Traverse the linked list one node at a time while the fast pointer will time while the fast pointer will Traverse the linked list two notes at a Traverse the linked list two notes at a time then if the two pointers and end up time then if the two pointers and end up on the same node at some point then that on the same node at some point then that means that a cycle exists so why does means that a cycle exists so why does this work well think of two people this work well think of two people running on a track with no Cycles if we running on a track with no Cycles if we let them run the faster one will let them run the faster one will eventually reach the end which for a eventually reach the end which for a linked list is the null value and we linked list is the null value and we would know that there are no Cycles but would know that there are no Cycles but if we put them on a circular track that if we put them on a circular track that does have a cycle then at some point the does have a cycle then at some point the faster person would catch up to the faster person would catch up to the slower one which means that they would slower one which means that they would be back at the same position again and be back at the same position again and so this is what we're looking for and so this is what we're looking for and it's how we know that a cycle exists now it's how we know that a cycle exists now you may be saying this is an example of you may be saying this is an example of two things moving continuously but two things moving continuously but linked lists are made up of discrete linked lists are made up of discrete nodes isn't it possible that the faster nodes isn't it possible that the faster pointer could pass the slower one by pointer could pass the slower one by skipping over it so that they never land skipping over it so that they never land on the same node well let's take a on the same node well let's take a closer look at a few different scenarios closer look at a few different scenarios to figure this out to figure this out the first scenario here is that the fast the first scenario here is that the fast pointer has made its way around and is pointer has made its way around and is now one node behind the slow one then at now one node behind the slow one then at the next step both pointers would land the next step both pointers would land on the same node and we're done the on the same node and we're done the second scenario is that the fast pointer second scenario is that the fast pointer is two nodes behind the slow one then at is two nodes behind the slow one then at the next step the fast pointer would be the next step the fast pointer would be one node behind the slow one and now one node behind the slow one and now we're back to the first scenario where we're back to the first scenario where both pointers meet on the next step and both pointers meet on the next step and it's the same idea no matter how far it's the same idea no matter how far back you move the fast pointer at each back you move the fast pointer at each step the distance gets reduced by one step the distance gets reduced by one node until eventually both pointers land node until eventually both pointers land on the same node now let's look at the on the same node now let's look at the code and see how we can do this in code and see how we can do this in Python we'll be using this definition of Python we'll be using this definition of a linked list here each list node has a linked list here each list node has two attributes Val which is the number two attributes Val which is the number you see inside each node and next which you see inside each node and next which is a pointer to the next node in the is a pointer to the next node in the linked list we are given a pointer to linked list we are given a pointer to the head of the linked list which I'll the head of the linked list which I'll represent with this green label here represent with this green label here so the first thing we'll do is create so the first thing we'll do is create another pointer called Fast which I'll another pointer called Fast which I'll represent with this orange label so head represent with this orange label so head will be the slow pointer and fast will will be the slow pointer and fast will be the fast pointer now we'll enter a be the fast pointer now we'll enter a loop that will move these pointers loop that will move these pointers forward as long as both fast and forward as long as both fast and fast.next are not null in other words we fast.next are not null in other words we keep looping until we reach the end of keep looping until we reach the end of the linked list so now let's move the the linked list so now let's move the pointers up first we'll set head equal pointers up first we'll set head equal to head.next so we're moving it up one to head.next so we're moving it up one node then we'll set fast equal to node then we'll set fast equal to fast.net.next so to break this down this fast.net.next so to break this down this would be moving it up to fast dot next would be moving it up to fast dot next and then we have to do another dot next and then we have to do another dot next so now we've moved it up two nodes then so now we've moved it up two nodes then after moving up both pointers we check after moving up both pointers we check if they point to the same node right now if they point to the same node right now they do not so we'll loop again they do not so we'll loop again head gets moved up one node and fast head gets moved up one node and fast gets moved up two nodes then we check gets moved up two nodes then we check again now I need to emphasize here that again now I need to emphasize here that even though both nodes have a value of 5 even though both nodes have a value of 5 this condition is still false because this condition is still false because remember when you compare two objects remember when you compare two objects using the is operator it checks if both using the is operator it checks if both objects are located in the same place in objects are located in the same place in memory in other words we are checking to memory in other words we are checking to see if they are the exact same object in see if they are the exact same object in this case they are two different objects this case they are two different objects that happen to have the same value of that happen to have the same value of five so this is still false and we loop five so this is still false and we loop again heady gets moved up one node and again heady gets moved up one node and fast is moved up two nodes and for the fast is moved up two nodes and for the last iteration head gets moved up one last iteration head gets moved up one more and now fast has caught up to head more and now fast has caught up to head now when we check this condition head now when we check this condition head and fast both point to the exact same and fast both point to the exact same object in memory so we return true and object in memory so we return true and we are done now if this had been a we are done now if this had been a linked list without a cycle at some linked list without a cycle at some point fast would have reached the end of point fast would have reached the end of the linked list and either fast or fast the linked list and either fast or fast dot next would have been null so we dot next would have been null so we would have broken out of this Loop and would have broken out of this Loop and just returned false which means that just returned false which means that there was no cycle
2024-03-21 12:32:06
141
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode #141: Linked List Cycle | Floyd's Tortoise and Hare Algorithm
7DdD-YXn0J8
[Music] hey coders hey coders so today we will look at this problem so today we will look at this problem number 336 balance bears number 336 balance bears which says given a list of unique words which says given a list of unique words return all the pair of distinct indices return all the pair of distinct indices i j in the given list so that i j in the given list so that the concatenation of the two words word the concatenation of the two words word i and word j is a bad intro i and word j is a bad intro right so okay so this is a palindrome right so okay so this is a palindrome sort of question sort of question so if we have abcd so if we have abcd we need to go through whole array we need to go through whole array and check which word if we concatenate and check which word if we concatenate forms of palindrome right so here dcba forms of palindrome right so here dcba and abcd ic forms a piling room and abcd ic forms a piling room zero and one is a solution for that so zero and one is a solution for that so these are all the these are all the solutions which we can get and solutions which we can get and okay so see the naive way okay so see the naive way will not work because as we can see the will not work because as we can see the word length is of word length is of words length like the arrays length is words length like the arrays length is all five thousand all five thousand uh and five thousand times five thousand uh and five thousand times five thousand is like 25 is like 25 10 times 10 raised to past six right 10 times 10 raised to past six right and for the each word we need to check and for the each word we need to check them too them too so multiply them by 300 itself so multiply them by 300 itself so it's going way off the charts so the so it's going way off the charts so the naive way will not work most probably naive way will not work most probably so now let's go to the solution and see so now let's go to the solution and see how we're going to achieve how we're going to achieve an optimized way of doing it okay this will be our example array which we will be solving so the very first thing we need to do is we need to pre-process this array and form a dictionary right or a hash map with individual positions as their value and the words will be their key right so dictionary would look something like this so dcba will be at the very first position or you can say it has position zero so here this this these all words are just reversed right cbs reverses abc this this this this and that right clear so next thing is we need to take a individual word we need to go word by word and we'll form the operations right let's pick abcd so what are all the words which when concatenated with it forms a paragraph those words are dcba cba and dcb of course so the next thing is what we will do we'll form a prefix postfix expression for the same word let's say here we have the word abcd let's say here we have the word abcd right right so first of all in the prefix we have so first of all in the prefix we have nothing nothing in the ball switch we have the entire in the ball switch we have the entire world we will check if world we will check if postfix is spread this prefix is present postfix is spread this prefix is present in our array in our array we say no it is not so we won't do we say no it is not so we won't do anything yet anything yet uh next thing is we will check if abcd uh next thing is we will check if abcd is present inside is present inside our array we can see it is present and our array we can see it is present and we will also check we will also check if of a post fix if our prefix if of a post fix if our prefix is a palindrome it is but here's a catch is a palindrome it is but here's a catch the element right so it must be the element right so it must be at least one time partition for at least one time partition for the postfix to be considered right or the postfix to be considered right or else else we will have duplicating it right we we will have duplicating it right we will see this will see this further so further so next thing is we move a to the left and next thing is we move a to the left and we'll check if a is present then no a is we'll check if a is present then no a is not not is bcd present ah no it's not is bcd present ah no it's not then we'll move ahead we'll check is a b then we'll move ahead we'll check is a b present no it's not is present no it's not is ct present no it's not moving ahead ct present no it's not moving ahead with abc is abc present you find yes with abc is abc present you find yes abc is there so abc is there so check right okay abc is there so check right okay abc is there so is our postfix a balance room is our postfix a balance room yeah it is a parallel drone a single yeah it is a parallel drone a single letter is a palindrome letter is a palindrome our current position right which was our current position right which was zero zero and the position of this abc which is and the position of this abc which is like 0 1 2 and thus add that like 0 1 2 and thus add that to our answer okay simple to our answer okay simple moving ahead we'll check again is our moving ahead we'll check again is our postfix postfix inside our area no it's not so inside our area no it's not so it doesn't make any point moving ahead it doesn't make any point moving ahead we again check is abcd we again check is abcd inside our array inside our array [Music] [Music] yeah it is right it is present but yeah it is right it is present but is is this position same as our current is is this position same as our current position position no it is not so we will count this no it is not so we will count this this as our answers right this as our answers right and put them in our resultant array so and put them in our resultant array so here you must have gotten here you must have gotten a little gist of what is actually a little gist of what is actually happening here in the next step happening here in the next step we will discuss its code and how we will we will discuss its code and how we will implement it implement it using python so let's make the using python so let's make the pre-processed pre-processed area we are using a dictionary area we are using a dictionary comprehension comprehension so bear with me now let's make prefix and postfix now we make another check where we now we make another check where we change if j change if j is greater than zero right this was the is greater than zero right this was the part where part where we avoid the duplicacy we avoid the duplicacy and we check if the post fixed right and we check if the post fixed right is no no we made a mistake over here is no no we made a mistake over here it should be post now we check if pose is in our dictionary d and the current position i p it works so far just run all the test it works so far just run all the test cases okay it's working
2024-03-24 10:49:00
336
https://i.ytimg.com/vi/7…axresdefault.jpg
Leetcode 336. Palindrome Pairs
oQMEhi1nzpE
all right so let's talk about the reverse Source in the string too so reverse Source in the string too so you're giving the charter radius and you're giving the charter radius and then reverse the order of the word so then reverse the order of the word so this is going to be pretty much it right this is going to be pretty much it right so you have to reverse the original so you have to reverse the original chart right so again so little sky is chart right so again so little sky is blue right so you blue put it in it blue right so you blue put it in it first is put it as a second Sky uh on first is put it as a second Sky uh on the following and then another will be the following and then another will be at the end at the end so this question is pretty so this question is pretty straightforward you need what you need a straightforward you need what you need a reverse function reverse function so I uh when I want to reverse right I so I uh when I want to reverse right I want to reverse the entire string first want to reverse the entire string first so I will be like this e u l p and then so I will be like this e u l p and then you have a space then space and is I you have a space then space and is I space right y k s space e h t right so space right y k s space e h t right so once I reverse the entire entire string once I reverse the entire entire string right I can right I can I can now reverse the chart array I can now reverse the chart array before the space so blue I mean eulb I before the space so blue I mean eulb I don't know how to pronounce but when you don't know how to pronounce but when you reverse you will become blue s i c when reverse you will become blue s i c when you reverse will it will become is right you reverse will it will become is right and then y k s and then it's k y y e t h and then y k s and then it's k y y e t h t then you'll become low so this is the t then you'll become low so this is the entire uh idea right so I need a entire uh idea right so I need a helper function for reverse right so helper function for reverse right so Char s in I in J so while Char s in I in J so while I less than equal to J right I less than equal to J right so you need the 10 equal to what uh Sai so you need the 10 equal to what uh Sai and s a i equal to S A J and s a i equal to S A J CJ equal to 10 and CJ equal to 10 and now you increment your counter right so now you increment your counter right so I plus plus I plus plus and then you should be J minus minus and then you should be J minus minus five so uh you are given the position right and then later on you just uh you know so I need to say reverse entire screen and then it's starting from zero and any from what the the value in this which is a star length minus one all right so all right so you have to uh so you have to have I and J pointer right so in I okay go to zero energy is also J is also and then you need to have a condition to and then you need to have a condition to Traverse right so while I listen to Traverse right so while I listen to insta lens and then also J is less than insta lens and then also J is less than equal to external try equal to external try is the lens is the lens because s is sorry right and because s is sorry right and you want to what so in the beginning uh here's it in the beginning there there might be have a space right so you probably can have a space low something like this right and then you uh you want to get rid of what you want to get rid of the space so I enjoy what's selling from here and I you want to get rid of the space right so you want to say if you want to study from I at least position right and then one and then when you know your current position I'm going to assign my J equal to I and then I Traverse my trip uh J index When J it when J Char is now what is not a space so I need to reach a position which is a space after the alert right between I and J minus one I and J minus between I and J minus one I and J minus one I need to swap right I need to one I need to swap right I need to reverse sorry reverse sorry and then here we go so uh and then here we go so uh so while I listening is the lens and [Music] um the current the current chart is is AI is equal to space right I need to increment my eye so I need to initialize re-initial my I uh so J is equal to I and then while J is less than it's the lens and also sha is not equal to space and J plus plus and then you want to reverse a s a i h a minus one and then once you reverse uh once you reverse the entire stuff right J is actually at a space position right then you want to initialize your eye so this is how the idea work right so uh reverse what zero oh this is Charlie all right so let's talk about the time all right so let's talk about the time and space and for the time this is and space and for the time this is definitely all the plan right definitely all the plan right uh you Traverse every single you know uh you Traverse every single you know sorry in this one in this one you sorry in this one in this one you reverse the entire screen right so it's reverse the entire screen right so it's definitely all offend and then in this definitely all offend and then in this value in this value you are actually value in this value you are actually what breaking the all of an into the what breaking the all of an into the small part so this is still all of them small part so this is still all of them if you want to say it right so if you if you want to say it right so if you want to just confirm if you're just want to just confirm if you're just concern while there are concern while there are a value inside a value a value inside a value uh you probably would ask like you know uh you probably would ask like you know you should be unscripted right but it's you should be unscripted right but it's not uh it's definitely not not uh it's definitely not so the worst case is going to be at so the worst case is going to be at least the reverse full entire chart least the reverse full entire chart right so it's all open right so it's all open and the space is constant so I'm going and the space is constant so I'm going to put some breakpoint to put some breakpoint and then you know something like this I and then you know something like this I don't know don't know and you you can pause it any second so and you you can pause it any second so look at the left window uh if you notice like the original rate thank you thank you all right so this is pretty much it so all right so this is pretty much it so if you have any questions leave a if you have any questions leave a comment below subscribe if you want it comment below subscribe if you want it alright peace out bye
2024-03-21 14:16:08
186
https://i.ytimg.com/vi/o…axresdefault.jpg
LeetCode 186 | Reverse Words in a String II | 2 Pointers | Debugger | Java
xH3fgc8Q7Xc
[Music] hey guys welcome back to another video hey guys welcome back to another video and today and today we're going to be solving the lead code we're going to be solving the lead code question largest number question largest number all right so in this question we're all right so in this question we're given a list of non-negative integers given a list of non-negative integers and we want to arrange them and we want to arrange them in such a way that they form the largest in such a way that they form the largest number so what does that mean so let's number so what does that mean so let's say over here we're given the values 10 say over here we're given the values 10 and 2. and 2. so over here we can form two numbers so so over here we can form two numbers so one of the possibilities one of the possibilities is coming up with the number 102 so 10 is coming up with the number 102 so 10 and then two so one zero two 102 right and then two so one zero two 102 right and the other option we have is and the other option we have is we rearrange it so instead of ten and we rearrange it so instead of ten and two we have two and ten two we have two and ten and that gives us the value of two and that gives us the value of two hundred and ten so two and then one zero hundred and ten so two and then one zero hundred 0 210 okay and which one between hundred 0 210 okay and which one between those two is bigger obviously 210 is those two is bigger obviously 210 is bigger bigger so that's what we're going to end up so that's what we're going to end up outputting so now we want to see outputting so now we want to see how do we exactly solve this question so how do we exactly solve this question so now the first thing that came to my mind now the first thing that came to my mind when thinking about how to solve it was when thinking about how to solve it was to just sort the list and then join to just sort the list and then join everything together everything together so let's say that i sorted and just to so let's say that i sorted and just to make sure i'm going to be sorting it in make sure i'm going to be sorting it in descending order so if i sort this in descending order so if i sort this in descending order it's going to end up descending order it's going to end up giving me 102. giving me 102. a better example actually is to look at a better example actually is to look at this over here so if i sort it in this over here so if i sort it in descending order descending order i would get 34 first but obviously i would get 34 first but obviously that's not going to be the biggest that's not going to be the biggest number number but the biggest number will be when nine but the biggest number will be when nine comes in the beginning comes in the beginning right so sorting it is actually not the right so sorting it is actually not the best way to do it so we want to make a best way to do it so we want to make a small small other changes to it in order to get the other changes to it in order to get the best and so best and so let's see how we can do this and one let's see how we can do this and one more thing that we're outputting this as more thing that we're outputting this as a string a string so let's just go through the step by so let's just go through the step by step and see how that looks like step and see how that looks like so this is the exact same question as so this is the exact same question as our example our example 3 30 34 5 and 9. and this is how we're 3 30 34 5 and 9. and this is how we're going to be solving this going to be solving this so we're going to have two pointers and so we're going to have two pointers and i'll just represent each pointer by its i'll just represent each pointer by its color color so one of them is going to be in green so one of them is going to be in green color and the other color and the other is going to be in red so the green is going to be in red so the green pointer starts off pointer starts off always at the zeroth index and the red always at the zeroth index and the red pointer is going to start off pointer is going to start off from the next index so if green starts from the next index so if green starts at index one at index one red starts at index two so currently red starts at index two so currently this is where our red pointer is gonna this is where our red pointer is gonna start start so now what we're gonna do is we're so now what we're gonna do is we're gonna form two different numbers gonna form two different numbers so one number that we're gonna form so one number that we're gonna form we're just gonna take between green and we're just gonna take between green and red red is going to be taking the green value is going to be taking the green value and adding that to the right value and adding that to the right value so three and by adding i don't mean so three and by adding i don't mean doing three plus 30 giving us 33. doing three plus 30 giving us 33. by adding i mean taking three and just by adding i mean taking three and just putting the putting the next two values so three and then three next two values so three and then three zero and that ends up giving us a value zero and that ends up giving us a value of 330. of 330. and one more thing if you noticed um so and one more thing if you noticed um so since we're adding it like this since we're adding it like this converting these values to a string converting these values to a string makes it a lot easier makes it a lot easier okay so now we have 330 and what is the okay so now we have 330 and what is the other combination other combination so over here we took green first and so over here we took green first and then we took red so now let's take then we took red so now let's take red first so if we take red first we end red first so if we take red first we end up with 30 up with 30 and then let's take green so now let's and then let's take green so now let's put three so these are the two values put three so these are the two values that we possibly have that we possibly have so which one over here is bigger so so which one over here is bigger so obviously 330 obviously 330 is the bigger value so since 330 is the is the bigger value so since 330 is the bigger value bigger value so that's basically saying the same as so that's basically saying the same as so first we have green so first we have green and then we have red and that is exactly and then we have red and that is exactly the pattern that we have the pattern that we have green first and then red so we can green first and then red so we can ignore this and we're ignore this and we're done with it as of now so now what's done with it as of now so now what's going to happen is that the green going to happen is that the green pointer is going to stay the same pointer is going to stay the same but what's going to change is the red but what's going to change is the red pointer is now going to go on pointer is now going to go on to the next value so now our red pointer to the next value so now our red pointer is over here is over here and again we're going to end up forming and again we're going to end up forming two different values so two different values so we take green first giving us three and we take green first giving us three and then red then red giving us 34. so now we have 334 now the giving us 34. so now we have 334 now the other number is taking red first other number is taking red first so 34 and then adding green so in this so 34 and then adding green so in this case which one is bigger so this one case which one is bigger so this one over here is bigger over here is bigger and we got this by doing red first and and we got this by doing red first and then green then green so that means the red value is going to so that means the red value is going to be a better choice since it gives us a be a better choice since it gives us a bigger value bigger value so what we're going to do is we're going so what we're going to do is we're going to swap these two values to swap these two values with each other so let's just do that with each other so let's just do that real quickly so get rid of this real quickly so get rid of this okay so that gives us 34 now since we're okay so that gives us 34 now since we're swapping it and over here we're going to swapping it and over here we're going to have three have three and one more thing is that we're and one more thing is that we're currently done with this and we're going currently done with this and we're going to move our red pointer again to move our red pointer again so now our red pointer is going to go on so now our red pointer is going to go on to five and to five and we do the same steps i'll just go we do the same steps i'll just go through this a little bit faster right through this a little bit faster right now so we have now so we have 34 so 345 and then we have 534 34 so 345 and then we have 534 obviously 534 is bigger so now we end up obviously 534 is bigger so now we end up swapping those two with each other swapping those two with each other so that becomes 5 and this over here so that becomes 5 and this over here becomes 34. becomes 34. so let's just do that so 5 over here and so let's just do that so 5 over here and 34 over here 34 over here all right cool and one more thing that all right cool and one more thing that happens now since we're done with that happens now since we're done with that our red pointer is going to end up our red pointer is going to end up changing to the last value over here changing to the last value over here which is nine so now we create the next which is nine so now we create the next two numbers so that two numbers so that gives us 59 and 95 so which one is gives us 59 and 95 so which one is bigger bigger obviously 95 is bigger so again we're obviously 95 is bigger so again we're going to have to swap those two values going to have to swap those two values with each other so we swap them and now with each other so we swap them and now the green value the green value is going to now end up becoming nine so is going to now end up becoming nine so we have nine over here we have nine over here and this over here ends up becoming five and this over here ends up becoming five okay so that is going to be okay so that is going to be one complete iteration so what exactly one complete iteration so what exactly happened in that iteration happened in that iteration so if you notice or if you even go back so if you notice or if you even go back to our answer we to our answer we got our first value so this is telling got our first value so this is telling us that the first value that we're going us that the first value that we're going to have to have is for sure going to be the value nine is for sure going to be the value nine so currently we have the first value in so currently we have the first value in place we don't need to worry about it place we don't need to worry about it and nine and nine is going to be our first value so now is going to be our first value so now what's going to happen what's going to happen is that we're going to remove our green is that we're going to remove our green pointer since we reach the ending with pointer since we reach the ending with our red pointer and over here what's our red pointer and over here what's going to happen we're going to going to happen we're going to give a new green value and this is going give a new green value and this is going to be the next value to be the next value so currently we were done with 9 so 9 is so currently we were done with 9 so 9 is in its correct place in its correct place so we want to find what is going to be so we want to find what is going to be the next uh values right we're going to the next uh values right we're going to be the next digits after nine so to find be the next digits after nine so to find that again that again we're going to put a green pointer over we're going to put a green pointer over here and the red pointer is always going here and the red pointer is always going to be to be right after the green pointer so this is right after the green pointer so this is going to be our red pointer going to be our red pointer and over here we're going to be and over here we're going to be performing the exact same steps so performing the exact same steps so we'll be comparing in this case 303 with we'll be comparing in this case 303 with 330 330 and what happens over here 330 is bigger and what happens over here 330 is bigger than 303 than 303 so that means that we're going to end up so that means that we're going to end up swapping that so let's swap this over swapping that so let's swap this over here here so 3 over here and 30 over here and so 3 over here and 30 over here and similarly the red is going to change and similarly the red is going to change and it's going to move over by 1. it's going to move over by 1. so i'm pretty sure you get the point and so i'm pretty sure you get the point and by the ending of this what should be by the ending of this what should be happening is by each happening is by each iteration we should be getting the iteration we should be getting the correct value of the green spot correct value of the green spot so in the first iteration we got the so in the first iteration we got the correct value for this in the second correct value for this in the second iteration right now iteration right now we're going to get the current value for we're going to get the current value for this spot over here then we're going to this spot over here then we're going to get the correct value over here get the correct value over here and so on and so forth until we reach and so on and so forth until we reach the the last but one value and that's when we're last but one value and that's when we're going to stop going to stop with all of this so just to kind of go with all of this so just to kind of go through this i'll just go through this through this i'll just go through this and you can see what the end result and you can see what the end result looks like so at the very ending what looks like so at the very ending what happens is that we end up with this over happens is that we end up with this over here here and um if you add all of these together and um if you add all of these together into one number we're going to end up into one number we're going to end up with nine with nine five three four three three zero five three four three three zero so in other words that's just going to so in other words that's just going to be nine million five hundred thirty four be nine million five hundred thirty four thousand thousand hundred 330. so that over here is our hundred 330. so that over here is our largest number largest number i didn't go through all the steps i didn't go through all the steps because it would take quite a bit of because it would take quite a bit of time and time and i would highly recommend that you do go i would highly recommend that you do go through all the steps if you still did through all the steps if you still did not understand how this works not understand how this works so now what i'm going to do is let's go so now what i'm going to do is let's go through the code part of this and through the code part of this and understand understand how the code looks like all right so how the code looks like all right so over here we're going to start off by over here we're going to start off by changing everything inside of our nums changing everything inside of our nums so currently everything inside of a num so currently everything inside of a num instead of nums is an integer instead of nums is an integer but we want to change that to be a but we want to change that to be a string and why is that so let's say we string and why is that so let's say we have the numbers have the numbers one comma two comma three and when you one comma two comma three and when you add them so add them so you would actually be doing one plus two you would actually be doing one plus two which gives us three but instead what we which gives us three but instead what we wanna do wanna do is when we add these two values we wanna is when we add these two values we wanna be so let's say we do one and two be so let's say we do one and two instead of doing one plus two we want to instead of doing one plus two we want to get the value 12. so in order to do that get the value 12. so in order to do that converting this into a string is going converting this into a string is going to make it a lot easier to make it a lot easier so how exactly can we do that so we can so how exactly can we do that so we can do list and over here we're going to use do list and over here we're going to use the map function the map function so we're going to do map and we want so we're going to do map and we want everything to be a string so string everything to be a string so string and then for what so for the list of and then for what so for the list of nums okay so by the ending of this if nums okay so by the ending of this if you print out the you print out the if you print out any of the elements and if you print out any of the elements and nums it is going to be a string nums it is going to be a string okay so over here we're gonna check if okay so over here we're gonna check if the length of nums the length of nums is less than two so if we have something is less than two so if we have something which is uh which does not have any which is uh which does not have any length length or if we have something which has a or if we have something which has a length of one then in that case we're length of one then in that case we're just going to end up returning whatever just going to end up returning whatever we have we have so to do that we can just do if length so to do that we can just do if length of nums is less than 2 of nums is less than 2 or in other words if it's equal to or or in other words if it's equal to or less than 1 less than 1 then in that case we're just going to then in that case we're just going to return so we can use the join function return so we can use the join function so we're going to give it a string so we're going to give it a string dot join and the reason we're doing a dot join and the reason we're doing a string is because we want the output as string is because we want the output as a string a string and then we're going to give nums and and then we're going to give nums and the re and one more thing is that it's the re and one more thing is that it's important that we convert it to a string important that we convert it to a string because the dot join function only works because the dot join function only works for strings for strings so yeah so now we got our answer for if so yeah so now we got our answer for if it's a null value it's a null value or if it has a value of one number in it or if it has a value of one number in it so over here we're going to go on to our so over here we're going to go on to our next condition next condition so to do that we're going to end up so to do that we're going to end up having two of our pointers so having two of our pointers so we had red and green but in this case we had red and green but in this case i'll just call it x and y i'll just call it x and y so x and y are both going to start so x so x and y are both going to start so x is always going to start off at zero is always going to start off at zero and y is going to be one more than x so and y is going to be one more than x so in this case let's just make in this case let's just make y one and it's not going to be our final y one and it's not going to be our final code but i'll just use this to explain code but i'll just use this to explain how it works how it works so over here we're going to have a while so over here we're going to have a while statement so while statement so while and what is the statement going to be so and what is the statement going to be so while the x value while the x value is less than the length of nums is less than the length of nums and the y value is less than the length and the y value is less than the length of nums of nums so that means that we've uh we haven't so that means that we've uh we haven't gone out of the range gone out of the range of the list yet that only then we're of the list yet that only then we're going to go inside of our if statement going to go inside of our if statement so over here we're going to compare so over here we're going to compare these two values these two values so how exactly are we going to end up so how exactly are we going to end up comparing them so to do that let's make comparing them so to do that let's make a a function over here called compare so function over here called compare so this is going to take two numbers this is going to take two numbers so let's just call them x and y so x and so let's just call them x and y so x and y are going to be the two y are going to be the two numbers that we're talking about and numbers that we're talking about and actually to be more precise we get x and actually to be more precise we get x and y exactly from here y exactly from here so x and y is actually going to be the so x and y is actually going to be the index right index right so now we want to get them into the so now we want to get them into the number itself number itself so how do we convert this into the so how do we convert this into the number so over here we have number so over here we have two numbers so one of the numbers is two numbers so one of the numbers is going to be nums going to be nums x sorry nums x plus x sorry nums x plus nums y so that gives us one of the nums y so that gives us one of the numbers but currently that is a string numbers but currently that is a string so over here we're going to convert that so over here we're going to convert that string into an integer string into an integer so this is one of our numbers and the so this is one of our numbers and the other number that we're going to have we other number that we're going to have we want to convert to an integer want to convert to an integer it's just going to be the opposite so it's just going to be the opposite so num y plus num y plus num x so over here we formed two of our num x so over here we formed two of our numbers numbers so over here what we're going to do is so over here what we're going to do is we're going to return we're going to return if the statement so if nums x plus y if the statement so if nums x plus y is greater than nums y plus x then in is greater than nums y plus x then in that case we're going to return true so that case we're going to return true so if this is true if this is true we return true but if that is false we return true but if that is false we're going to end up returning false we're going to end up returning false okay so now let's see how we can add okay so now let's see how we can add this to our while loop this to our while loop so over here we're going to check if so over here we're going to check if compare so we're going to give it x compare so we're going to give it x and y values and if this is true and y values and if this is true that means that x plus y is bigger than that means that x plus y is bigger than y plus y plus x in that case we're just going to pass x in that case we're just going to pass we're not going to do anything we're we're not going to do anything we're going to let it be as it is going to let it be as it is but else so else if this is not true so but else so else if this is not true so that means that that means that y plus x is greater than x plus y y plus x is greater than x plus y and in that case if you recall we're and in that case if you recall we're going to be swapping these two values going to be swapping these two values with each other with each other so how do we do the swap so nums y and so how do we do the swap so nums y and nums nums x so nums y is going to become nums x x so nums y is going to become nums x so let's do that over here and num x is so let's do that over here and num x is going to become num going to become num y so this over here is swapping the two y so this over here is swapping the two values with each other values with each other and at the ending of this for no matter and at the ending of this for no matter what it is we're going to increase our y what it is we're going to increase our y value by one so by the ending of this value by one so by the ending of this we're going to get the value for we're going to get the value for one iteration but we don't just want one one iteration but we don't just want one iteration right we want to be doing this iteration right we want to be doing this until until the x value reaches to the last but one the x value reaches to the last but one value value so in order to make this a lot easier so in order to make this a lot easier for us we're going to put this inside of for us we're going to put this inside of a for loop a for loop so let's just remove this over here and so let's just remove this over here and over here over here let's put let's do a for loop so four let's put let's do a for loop so four x in range so we're gonna be going up to x in range so we're gonna be going up to the length of nums the length of nums minus one so the last but one value minus one so the last but one value and over here let's put our while loop and over here let's put our while loop inside of this for loop inside of this for loop and we also want to define the y value and we also want to define the y value so the y value is always going to be so the y value is always going to be x plus one it's going to be the next x plus one it's going to be the next value and each time we're going to value and each time we're going to redefine this redefine this y value and by the ending of this we y value and by the ending of this we should should get our nums in the sorted order get our nums in the sorted order according to what we want according to what we want so once we get this all we have to do is so once we get this all we have to do is return return and we want to join these two each uh and we want to join these two each uh together instead of a string so string together instead of a string so string dot join and then we're joining the nums dot join and then we're joining the nums okay okay so if i submit this over here it's so if i submit this over here it's actually not going to be correct actually not going to be correct we're going to get it wrong at this we're going to get it wrong at this condition over here condition over here so zero comma zero and we ended up so zero comma zero and we ended up outputting the value zero zero outputting the value zero zero which is actually wrong it expects just which is actually wrong it expects just one zero one zero so how exactly do we take care of this so how exactly do we take care of this uh simple uh situation over here so in uh simple uh situation over here so in order to do that we're going to be using order to do that we're going to be using the map the map method again but the way we use it is method again but the way we use it is going to be a slightly different going to be a slightly different so over here what we're going to do is so over here what we're going to do is we're going to map it according to we're going to map it according to a boolean value so how exactly does this a boolean value so how exactly does this work so let's just first do it real work so let's just first do it real quick so map quick so map we want it to be a boolean value and we want it to be a boolean value and we're going to be using the nums list we're going to be using the nums list and one more thing make sure that we're and one more thing make sure that we're doing this before we converted it into a doing this before we converted it into a string string so these numbers are still integers so so these numbers are still integers so over here over here if our numbers are equal to zero that if our numbers are equal to zero that means that means that everything is going to end up as having everything is going to end up as having a value of a value of false and if even one of these numbers false and if even one of these numbers is not a zero we're going to have is not a zero we're going to have a value of true so to check if all of a value of true so to check if all of our values are not our values are not zeros we can do any and then we can put zeros we can do any and then we can put this over here this over here and we can check if not any and then of and we can check if not any and then of this this mapped list over here so what exactly mapped list over here so what exactly does this mean so over here does this mean so over here if let's say as we had we had two zeros if let's say as we had we had two zeros right so what's going to happen once we right so what's going to happen once we put it through our map over here put it through our map over here we're going to get two false right so we we're going to get two false right so we do not have do not have any true right there's no truth inside any true right there's no truth inside of this of this so in that case what's going to happen so in that case what's going to happen we're just going to end up directly we're just going to end up directly returning the value returning the value zero and that's it we're directly zero and that's it we're directly returning the value zero returning the value zero and we're done with the function as it and we're done with the function as it is and even if one of the values is is and even if one of the values is not a zero uh basically in the fact that not a zero uh basically in the fact that not everything is a zero not everything is a zero then we're going to go past this if then we're going to go past this if condition we're not going to return condition we're not going to return anything anything and we're going to proceed on doing all and we're going to proceed on doing all of these steps of these steps so now when we submit this we have so now when we submit this we have accounted for that zero zero accounted for that zero zero um parameter and now our submission is um parameter and now our submission is accepted accepted so thanks a lot for watching guys so thanks a lot for watching guys hopefully this video helped you and hopefully this video helped you and don't forget to like and subscribe if don't forget to like and subscribe if the video helped you the video helped you thank you
2024-03-21 14:14:19
179
https://i.ytimg.com/vi_w…xresdefault.webp
Largest Number | Leet code 179 | Theory explained + Python code
k1EDQwAQlc0
welcome to january's legal challenge today's problem is today's problem is check if two string arrays are check if two string arrays are equivalent given two string arrays word equivalent given two string arrays word one and word two return true one and word two return true if the two arrays represent the same if the two arrays represent the same string so what do we mean string so what do we mean so we're given a list of strings you can so we're given a list of strings you can see though that they're going to be kind see though that they're going to be kind of of split up in different manners what we split up in different manners what we want to do is want to do is try to concatenate all these strings try to concatenate all these strings together and see if they form the same together and see if they form the same word and we can do that in python word and we can do that in python fairly easily using the join method fairly easily using the join method right right so all we need to do is try the string so all we need to do is try the string join join and say all right string join the word and say all right string join the word one one and check to see equal to string join of and check to see equal to string join of word word two and i wasn't sure if this would work two and i wasn't sure if this would work because concatenating strings in python because concatenating strings in python is pretty expensive but is pretty expensive but it does work um so there we go it does work um so there we go so that seems simple enough but this so that seems simple enough but this does use extra memory right because does use extra memory right because we're forming we're forming a new string out of our list of strings a new string out of our list of strings so could we do this in o of one space so could we do this in o of one space well well yes but it's not necessarily going to be yes but it's not necessarily going to be faster might save memory faster might save memory let's see how we might do that so we let's see how we might do that so we would have to have would have to have two pointers per each of the work are two pointers per each of the work are two indexes we would need the two indexes we would need the index for the item list or the string index for the item list or the string inside of the list inside of the list as well as a index number for the as well as a index number for the character inside of this character inside of this string so let's see what we do we have string so let's see what we do we have say word one index zero uh and we'll have word two index as and both of these will start with zero and both of these will start with zero then we'll also have a character one then we'll also have a character one index index as well as a character two index as well as a character two index and again these will start at zero now and again these will start at zero now while we while we have the ward one index is have the ward one index is less than the length of word one less than the length of word one uh i should say and word uh i should say and word two dot index is less than the length of two dot index is less than the length of word two we're going to check something here first we want to get the character of what we're pointing at so this would word one index and character one and we can do the same thing for the second word now uh once we do this we want to check to see if they are equal to one another and if they are we can continue our loop so if c1 does not equal c2 then return false immediately because we know that these words can't possibly be the same but we have to make sure that we want to check to see if we're at the end of the word or yeah the end of the string inside of this index number right so if let's see word1 dot index or i should say charact [Music] character one index greater or equal to the length of greater or equal to the length of word one word word one word uh let's see that's the case um but yeah that's the case um but yeah if that's the case then we want to if that's the case then we want to increase our increase our uh word one index and reset our character one index to otherwise we're just going to increase the character index right uh and i believe that actually comes before here character one so we'll have character two do the same and finally that would be it and finally that would be it we just need to go up to the end and one we just need to go up to the end and one thing to note is we can't just return thing to note is we can't just return true here because true here because we could possibly have um one part be we could possibly have um one part be like abc and the other one be like a b c like abc and the other one be like a b c d so we want to check to make sure that d so we want to check to make sure that the lengths the lengths of the word one equaling the length of of the word one equaling the length of word one word one is true i should say word index all right so let's see if this works and there we go accepted so this would and there we go accepted so this would be all one space be all one space it's a lot more uh verbose and wordy it's a lot more uh verbose and wordy uh and the truth is i don't think it's uh and the truth is i don't think it's any faster in fact any faster in fact here looks like it's being slower and here looks like it's being slower and for some reason in lee code it says we for some reason in lee code it says we use the same amount of memory i'm not use the same amount of memory i'm not totally sure why that's the case totally sure why that's the case uh it's probably something to do with uh it's probably something to do with leak code leak code itself but i'm fairly certain itself but i'm fairly certain technically this is all one space technically this is all one space so both solutions are fine uh i just so both solutions are fine uh i just want to go through this in case want to go through this in case um you want to try to better so um you want to try to better so thanks for watching my channel and thanks for watching my channel and remember do not trust me i know nothing
2024-03-20 10:22:12
1,662
https://i.ytimg.com/vi/k…c0/sddefault.jpg
Leetcode - Check If Two String Arrays are Equivalent (Python)
ABVvTxH0qsw
So if Video Inderpreet Kaur Degree Holder Problem Max India Of Ireland Holder Problem Max India Of Ireland Surya Giver Great And Basically Ireland Surya Giver Great And Basically Ireland Group-1 Connected For Directions Where Is Group-1 Connected For Directions Where Is The Number Of The Return Of The Volume To A Silent During A Silent During And Size Of Four Again And And Size Of Four Again And And Size Of Four Again And a dasha languages ​​have enough size of which you have a silent silence the maximum number look at its leaders take this look at its leaders take this software into a titillating first software into a titillating first sidesteps appeared first on me to two to sidesteps appeared first on me to two to two to the celebration two to the celebration two to the celebration and contributed for the volume to check my name is a plus together and derived from the group which can contribute to form the maximum area from this to record from exactly so many years just call the function and Good Cause It's Good Cause It's Good Cause It's Neighbors 151 Deposit And One More Step Number Neighbors 151 Deposit And One More Step Number Three And Validation Important And Will U Can Three And Validation Important And Will U Can Be So To-Do List Start Doing So Be So To-Do List Start Doing So You All Subscribe 2014 You All Subscribe 2014 Porn Wash With Used Lubricating Water And Water Porn Wash With Used Lubricating Water And Water Until You All It's Neighbors Until You All It's Neighbors Will Return To first person bigg boss ne very happy first person bigg boss ne very happy new year new year so what to do when will again calls never saw it will enter so what to do when will again calls never saw it will enter into the function of into the function of is right but they cold see the middle of is right but they cold see the middle of nowhere else will return Return Back to the Function subscribe this Subscribe to YouTube Channel Now to Take Off OK Se 10 Particulars Sale Subject Information in Toilet You Will Reach and Write Rural Schools from the Beginning Night Sweet Dreams Different from this Particulars In and What Happened Now And And And Happiness Not Destroy Justice Am Happiness Not Destroy Justice Am Officer You Can Observe A Very Carefully Very Carefully What Will Happen Officer You Can Observe A Very Carefully Very Carefully What Will Happen In This In This Particular Say This Is To Make A Call To Make A Particular Say This Is To Make A Call To Make A Call To College College First Name * Was Okay Is Call To College College First Name * Was Okay Is Right Depend Investigate Right Depend Investigate Cold Water Proof Brightness Brightness Cold Water Proof Brightness Brightness Cold Water Proof Brightness Brightness A Call To Everyone Like It Surya Itne Barun Macrame Quite Right Never Stop Never Will Never Left Labels Brightness But Will Also Called Again Seervi And Understand What Is Happening Okay Subscribe To * All Its Neighbor Once Again For The Will The First Will The First Will The First Subscribe School Fees Time And Situation Subscribe School Fees Time And Situation Second Tax School Say Never And You Will Keep Falling He Second Tax School Say Never And You Will Keep Falling He Changed Gil Se Quality Never Say Never Been Stuck Changed Gil Se Quality Never Say Never Been Stuck In A Slack Poor In A Slack Poor Twist Very-Very Important This To Consider What Do Twist Very-Very Important This To Consider What Do You Mean To Look Back 2018 For Defense Can You Make A Is 2018 For Defense Can You Make A Is Dynasty This Visit Something Vitamin Value Dynasty This Visit Something Vitamin Value 112-jazz 102 Important Sydney Morning 112-jazz 102 Important Sydney Morning Herald To Finally Bigg Boss Liter Herald To Finally Bigg Boss Liter Maximum Area So Let's Go For This So Let's Maximum Area So Let's Go For This So Let's Start Hydrating Over All The Sense Start Hydrating Over All The Sense Point Equal To Zero Oil A Point Equal To Zero Oil A Point Equal To Zero Oil A Side Ko Lamba Not Declared When Is The Value Is Is Value Is Is Unit To Do The Function Points What Is How Did The Unit To Do The Function Points What Is How Did The Various One Simple A Grade Of Various One Simple A Grade Of Held Is Equal To What You Can Held Is Equal To What You Can Held Is Equal To What You Can Give A Brief Come 10 B Positive Number To To To To To Do Do Do Do Do Do Do Do Do Do Do Do Do You Live Windows 8 Khesari Value One Switch Account Has To Be Given Minimum And Variable In Which We Can Day and finally no no no no Day and finally no no no no Day and finally no no no no the function of account and function subscribe to the Page if you liked The Tera Dushman written in and water into this Tera Dushman written in and water into this they want to write definition in this they want to write definition in this function notification aa simply is with in function notification aa simply is with in function notification aa simply is with in subscribe to 10000 is greater than two years old is gold channel of side this is 2030 waste time toxins waste time toxins nor to contribute towards nor to contribute towards it's now a specific count of verbs setting it's now a specific count of verbs setting function very function very function very Make The Great Friday Or Will Run Into The Time Limit Straight Problem Run Into Infinity Recessive Calls With Features And Logic What Do We Call The Animals And Share Helpful And Not Withdrawn It's Just What Do Now Now That Now Now That Now Now That If A Good Qualities And Millet Jewelry If A Good Qualities And Millet Jewelry Means I Am Not Want To See The Question Pass Means I Am Not Want To See The Question Pass Control Of Which Never Used Oil Jewelry Control Of Which Never Used Oil Jewelry Middle Name And Don't Give Me Give Winners Will Leave You Know All This Today We Just Cords One One One Time I Today We Just Cords One One One Time I Today We Just Cords One One One Time I One Time He Plus One Upon Time I Will Give 6 - One N One Time Will Give Way Do Subscribe For This Is For Liberty And Share Subscribe Button Positive How Will Tree To Avoid You Can Give Water Subscribe To Yes Yes Yes ok hai vent all govt s well s ok hai vent all govt s well s eminent aur please give dot subscribe The eminent aur please give dot subscribe The Channel subscribe dot size notification aa Channel subscribe dot size notification aa ko switch final lakshmi jism intensive ko switch final lakshmi jism intensive king up king up ko switch marking not really 201 time ko switch marking not really 201 time output description of this video also what output description of this video also what is happening unfortunately in this coming is happening unfortunately in this coming Account It Is The Side Chile That Give This In Size Bracket Dead Skin Problem Solve Important Sisters Under The Thank You
2024-03-20 17:18:52
695
https://i.ytimg.com/vi/A…axresdefault.jpg
695. Leetcode Max Area of Island|| Code + Explanation + Example Walkthrough || June1 Daily Challenge
BS3PJLi4BYU
Ajay Ko Hello Hi Everyone Welcome To My Channel It's Hello Hi Everyone Welcome To My Channel It's All The List Problem 304 Ransomware Redeem Your All The List Problem 304 Ransomware Redeem Your Troubles For This Problem Is Very Troubles For This Problem Is Very Famous Interview Problem Anycut Aaj In Famous Interview Problem Anycut Aaj In Amazon Google Microsoft Interview subscribe to the Page if you liked The Indian Ginger Indian Ginger Indian Ginger square feet thing 09 element witch some lemon and misses 128 like date for everyone call me to the solution subscribe problem example for middle thursday morning all elements witch rectangle 12345 and green square end subscribe to Exit Exit Exit Unlimited Picture Ko Dot Approach Which Is Very Unlimited Picture Ko Dot Approach Which Is Very Straightforward You Can For The Video And Straightforward You Can For The Video And Implement Your Say Say What Is The Implement Your Say Say What Is The Time Complexity Of Dissolution Show In Time Complexity Of Dissolution Show In Constructor Members Switch Off But Not Do Anything Which Is Copying Constructor Members Switch Off But Not Do Anything Which Is Copying Changing Reference Changing Reference 19th Shri-Samriddhi Width And - - 19th Shri-Samriddhi Width And - - - Call We Roman Reigns We All Subscribe - Call We Roman Reigns We All Subscribe Can We Make Every Constitution College Of Know How Make Very Very Very Easy The President To Power For It's Us In This President To Power For It's Us In This Time Complexity Vikram Time Power Time Complexity Vikram Time Power Point When Is The Maximum Given In This Problem Point When Is The Maximum Given In This Problem In 210 Suresh Oberoi Time In 210 Suresh Oberoi Time Complexity Rebellion Like Him To Complexity Rebellion Like Him To Deposit Near Ride Point To The Power This Update Will Deposit Near Ride Point To The Power This Update Will Be Timeout And Very Poor Performance In Be Timeout And Very Poor Performance In Terms Of Time Complexity Software Must Be Terms Of Time Complexity Software Must Be Follow Nutrition How Will Improve Time Follow Nutrition How Will Improve Time Complexity Of This Solution From Being Complexity Of This Solution From Being Of Lemon To Be Of This Constitution Of Lemon To Be Of This Constitution Of Lemon To Be Of This Constitution Call 100 How To Do This Point Gas Recently That Solve This Problem Running Some Of Money Are In The Challenges Of Life Se Sure Patience Na Urgent Need To Join The Return Of Life 1364 Me To The Newspaper Chennai Express Which Takes You Into Every One That Unwanted Mutton Interviews Pet That Unwanted Mutton Interviews Pet That Unwanted Mutton Interviews Pet Something 2516 Elements of Something 2516 Elements of Obscurism Half Inch Subscribe Obscurism Half Inch Subscribe Problems Which Helps Improve Time Problems Which Helps Improve Time Complexity from Expansion of Words Complexity from Expansion of Words Related to the Same Approach Will You Can Also Saw This Will Create Related to the Same Approach Will You Can Also Saw This Will Create Content by Pressing the Subscribe Button Content by Pressing the Subscribe Button Cleaner Lots of Cases Subscribe Cleaner Lots of Cases Subscribe in This Element Forces and in This Element Forces and in This Element Forces and hair in wave super discus throw is similar to bhiwandi soft will take this rosary and will feel overhead so initially envisioned in 307 323 plus plus one plus one but will need a glittering subscribe Video over what will Evil From This Evil From This Evil From This Is Like 251 Switch On Subscribe Subscribe Shubhesh Like This San Still Here From Starting From Zero Basically From 2002 Dual Air And Attracting Someone From This Sunidhi Shedding After Reading This Issue Seriously Edit To Time Isko Man Read Subscribe Shoot Subha Sector 110 Vikram Thriller 0 Plus - 08 Till Currency Value Which Is Point Vishisht This Is Vikram And Saunf In Terms Of Digestive Want To Right Member Vikram Sum Of The System Of View From A Plus B Plus B Plus B Plus We That I Plus One That I Plus One A For B A For B A For B Sudesh Water Something This Point To 4 Plus Some Of Social Media Point Subscribe And A 8 - SBI Two Times Adjustment Compelling Jain11 8 - SBI Two Times Adjustment Compelling Jain11 Video Matrix Of I Will Take Care Of All Video Matrix Of I Will Take Care Of All They Know How To Draw Water From Sorrow Subscribe Now To Receive That And Have Been Included As One Is Our R1 And C1 Share This Vacancy With Map Dish 218 ISRO Ro Two Billion Plus One And C Two And Sunao And Sunao 's Members One 's Members One 's Members One Samsuddin Civil V I one second switch off 419 Udyam 500 Us 512 305 Shift Row End Column Sudesh One is our biggest mistake also level this point All also points lines in this crime area from this point Sudhir and Subscribe 16 December On Max Bhi Neetu Subject On Max Bhi Neetu Subject On Max Bhi Neetu Subject Arts Chuckle This Is Wrong No Duty 828 Arts Chuckle This Is Wrong No Duty 828 So Here And Next They Will Spread So Here And Next They Will Spread Difficult Swift Nodded In The Happy Returns Of The Day Happy Returns Of The Day Tapasya Avsar Vansham Media Can Verify And Tapasya Avsar Vansham Media Can Verify And Quotes Flirty Ridhead And Pradesh Ko Quotes Flirty Ridhead And Pradesh Ko Quotes Flirty Ridhead And Pradesh Ko Video subscribe and subscribe the same will go to plus two plus minus blue blue green T&C 130 will guide accepted your details on record accept what is the time complexities of this solution so edit can see beer building this matrix over it will Of Cost Of Consideration While We Of Cost Of Consideration While We Of Cost Of Consideration While We All Were Born In This Is The Time All Were Born In This Is The Time Complexity subscribe thanks for Complexity subscribe thanks for watching
2024-03-24 10:03:44
304
https://i.ytimg.com/vi/B…axresdefault.jpg
Range Sum Query 2D Immutable | Leetcode 304 | Google Amazon Microsoft | Matrix
UbqttH0rSBc
hi guys welcome to algorithms made easy in this video we will see the question in this video we will see the question get maximum in generated array get maximum in generated array you are given an integer n and an array you are given an integer n and an array numbers of length n plus 1 numbers of length n plus 1 is generated in the following way is generated in the following way numbers of 0 becomes 0 numbers of 0 becomes 0 nums of 1 becomes 1 and for any nums nums of 1 becomes 1 and for any nums 2 into i it becomes nums of i 2 into i it becomes nums of i and for any nums 2 into i plus 1 becomes and for any nums 2 into i plus 1 becomes numbers of numbers of i plus numbers of i plus 1. from these i plus numbers of i plus 1. from these two conditions we can say that if the two conditions we can say that if the number is even we can rewrite the value number is even we can rewrite the value for it in the nums array as for it in the nums array as nums of i by 2 and if it is an nums of i by 2 and if it is an odd number we can write its value as the odd number we can write its value as the sum of numbers of i by 2 sum of numbers of i by 2 plus nums of i by 2 plus 1. at the end plus nums of i by 2 plus 1. at the end we need to return the maximum integer we need to return the maximum integer that is occurring in the array nums that is occurring in the array nums so this is a pretty straightforward so this is a pretty straightforward question we'll just be using these question we'll just be using these conditions that are mentioned over here conditions that are mentioned over here and we can get the answer easily from and we can get the answer easily from that so let's go ahead and write some that so let's go ahead and write some code for it code for it so the base case here would be if the so the base case here would be if the number is 0 or 1 we can just give the number is 0 or 1 we can just give the number itself as an output number itself as an output so if n is less than 2 so if n is less than 2 return n otherwise we take an int array return n otherwise we take an int array that would be of size n plus 1 and we that would be of size n plus 1 and we write write nums of 1 equal to 1 as it is given to nums of 1 equal to 1 as it is given to us us after this we'll run a for loop after this we'll run a for loop the for loop will start from 2 as we are the for loop will start from 2 as we are already returning already returning the answer in case of 0 and 1. in here the answer in case of 0 and 1. in here if if i mod 2 is equal to 0 which is this i mod 2 is equal to 0 which is this condition condition our nums of i becomes numbs of our nums of i becomes numbs of i by 2 else i by 2 else numbers of i becomes numbers of i by 2 numbers of i becomes numbers of i by 2 plus numbers of i by 2 plus numbers of i by 2 plus 1 with this will update a variable plus 1 with this will update a variable max that would be our result max that would be our result so initially max would be 0 so initially max would be 0 and here we can update max and here we can update max math dot max of max comma nums of i math dot max of max comma nums of i lastly return max let's try to run this lastly return max let's try to run this code for all the sample test cases that code for all the sample test cases that are given to us are given to us and it gives a perfect result let's try and it gives a perfect result let's try to submit this code to submit this code and it got submitted the time complexity and it got submitted the time complexity for this approach is o of for this approach is o of n and the space complexity is also o of n and the space complexity is also o of n n so that's it for today guys thanks for so that's it for today guys thanks for watching the video see you in the next watching the video see you in the next [Music]
2024-03-19 18:06:25
1,646
https://i.ytimg.com/vi_w…xresdefault.webp
Get Maximum in Generated Array | Live Coding with Explanation | Leetcode #
MU703aLvNVY
hello welcome to my channel today let's talk about lead coder 1096 the number of talk about lead coder 1096 the number of weak characters in the game weak characters in the game so so um um it will give you a 2d array it will give you a 2d array called properties and called properties and then each then each each element of the properties is a two each element of the properties is a two are two are two uh uh length of two length of two integer array uh the first one is called integer array uh the first one is called attack the second one is called defense attack the second one is called defense so so one there is another character which has one there is another character which has both higher attack and a higher defense both higher attack and a higher defense this character is called weak character this character is called weak character and the question asks you to output the and the question asks you to output the number of weak characters number of weak characters so uh fight uh we can look at the so uh fight uh we can look at the example in the first example there is no example in the first example there is no weak character weak character uh in the second example uh in the second example uh character tutu uh character tutu is a weak character because the is a weak character because the character the second character has both character the second character has both a higher a higher attack and a higher defense attack and a higher defense the third the third example example character 4 3 is a weak character character 4 3 is a weak character because the because the second character second character has a 10 as a attack which is higher has a 10 as a attack which is higher than 4 and has a 4 as a defense which is than 4 and has a 4 as a defense which is higher than 3. higher than 3. so so this question this question um um the blue force approach the blue force approach is a is a you you compare each character with all you you compare each character with all the other characters the other characters and the time complex is an n square and the time complex is an n square but uh because the constraint uh here is but uh because the constraint uh here is a 10 to the power 5 a 10 to the power 5 so it will get a tle the second approach we we can think of is uh to firstly to of the properties by um um so then so then after sorting we can actually iterate after sorting we can actually iterate the the array array from end to the beginning and uh keep a count keep a counter of keyboard variable called uh max defense uh then we we compare uh the current character with as a defense with max defense and if it's uh uh it's if it's smaller than max defense we might have a weak character here so but this approach actually has a still have a slightly problem so let's uh look so assume we have this three character so assume we have this three character one two one three and one four one two one three and one four so now it's sorted by so now it's sorted by attack but they actually have duplicated attack but they actually have duplicated the attack value the attack value then then when we go back uh go when we go back uh go integrated array from back from end to integrated array from back from end to the beginning then we actually firstly the beginning then we actually firstly we have max we have max defense as four defense as four then we compare three with four then we compare three with four and we actually have a three smaller and we actually have a three smaller than max defense than max defense then we might increment this counter but then we might increment this counter but actually we shouldn't actually we shouldn't because the attack value is uh identical because the attack value is uh identical so so total solver walk around there is a array array by attacker by attacker in ascending order in ascending order and and by defense by defense in in descending order then though we will have a for this situation we will have one four one three and one two so now we actually go if we go from the back to the front uh we can we get a max defense firstly assigned another two so max defines as a three and a max defense so so actually we will not uh increment the counter for any of this character which is correct so uh let i have an explained approach let's uh um so i will so i will uh solder this array by using this lambda lambda expression so when the attack is uh the same we we actually can compare the defense so the this is the sort of the descending order then if a tag is different we send we saw that by a tiger by uh in ascending order so um we get the length um we get the length and we need to have a max defense we can and we need to have a max defense we can actually initialize as a zero because at least one at least one and also we need a counter and also we need a counter called als called als so what we can do is we so what we can do is we go backwards go backwards so uh so uh iterate iterate and so now is we need to compare so if produce defense is a smaller than max difference so we actually need to increment the corner otherwise uh we don't need to increment counter but we need to next defense and then we just return sponsor so this basically does that let's test the uh some myth uh some myth voila voila so fast so fast uh let me know if you uh let me know if you have any question and you can comment have any question and you can comment and if you like the video and if you like the video please please subscribe subscribe or click like button or click like button thank you thank you for watching see you thank you thank you for watching see you next time
2024-03-25 12:28:15
1,996
https://i.ytimg.com/vi/M…axresdefault.jpg
Leetcode 1996. The Number of Weak Characters in the Game (Weekly Contest 257 Q2)
2QqkNEx9tzM
hey everyone in this video let's go to question 253 meeting rooms 2 on leak question 253 meeting rooms 2 on leak code this is part of a blind 75 list of code this is part of a blind 75 list of questions so let's begin questions so let's begin so this question is actually a premium so this question is actually a premium question and that's why we're doing it question and that's why we're doing it on this lint code website that's why the on this lint code website that's why the number here is different but otherwise number here is different but otherwise the question and the test case is the question and the test case is solution will be the same so let's go solution will be the same so let's go ahead and begin ahead and begin in this question we're given an integer in this question we're given an integer or given an array of meeting time or given an array of meeting time intervals consisting of start and end intervals consisting of start and end time so S1 E1 has to be better where s i time so S1 E1 has to be better where s i is less than e i and we want to find the is less than e i and we want to find the minimum number of conference rooms minimum number of conference rooms required we can see here that required we can see here that additionally 0 8 and 810 is not a additionally 0 8 and 810 is not a conflict which means that a meeting can conflict which means that a meeting can end and another one can start at the end and another one can start at the same time we essentially want to find same time we essentially want to find the minimum number of conference rooms the minimum number of conference rooms required now we've done question a required now we've done question a question similar to this meeting rooms question similar to this meeting rooms one and in that one essentially we just one and in that one essentially we just had to figure out if one conference room had to figure out if one conference room could fit every single meeting and so in could fit every single meeting and so in that one we just looked for an overlap that one we just looked for an overlap and if there was any sort of overlap we and if there was any sort of overlap we understood that we could not have the understood that we could not have the scenario in this one we'll have scenario in this one we'll have something similar but but instead we something similar but but instead we want to find the minimum number of want to find the minimum number of conference rooms required so if there is conference rooms required so if there is an overlap we'll basically add in an overlap we'll basically add in another conference room and then we can another conference room and then we can see based on that how we can arrive at see based on that how we can arrive at the solution okay so let's take a look the solution okay so let's take a look at the examples here to better at the examples here to better understand and again this website is understand and again this website is used for premium prompts so we will use used for premium prompts so we will use it anytime we have a premium problem on it anytime we have a premium problem on lead code let's take a look at what we lead code let's take a look at what we have here have here so in this one what we have is we have a so in this one what we have is we have a couple of meeting rooms right or meeting couple of meeting rooms right or meeting like times zero to thirty five to ten like times zero to thirty five to ten fifteen to twenty and what is one thing fifteen to twenty and what is one thing we we want to do right so if you think we we want to do right so if you think about it like these times mean something about it like these times mean something right this means that we must start off right this means that we must start off at time zero this means that we must at time zero this means that we must start off at like time five this means start off at like time five this means we must start off at time 15. maybe you we must start off at time 15. maybe you can think of this as like 12 o'clock can think of this as like 12 o'clock this is like 1205 maybe this is like 12 this is like 1205 maybe this is like 12 15 or like whatever right but basically 15 or like whatever right but basically meetings have to happen in a certain meetings have to happen in a certain order be like similar to real life order be like similar to real life meetings have to happen in a certain meetings have to happen in a certain order so one thing we might want to do order so one thing we might want to do and we did this in made in rooms one is and we did this in made in rooms one is kind of like sort this list right kind of like sort this list right because this list isn't actually sorted because this list isn't actually sorted um based on anything but what we did in um based on anything but what we did in meeting rooms one is we sorted it based meeting rooms one is we sorted it based off of the starting time why does this off of the starting time why does this make sense well this makes sense because make sense well this makes sense because in real life you want to take in in real life you want to take in meetings based on the starting time meetings based on the starting time right like you want to pick the earliest right like you want to pick the earliest meetings first so that's one thing we'll meetings first so that's one thing we'll have to do so we'll have to sort the have to do so we'll have to sort the meetings based off the starting time and meetings based off the starting time and really if you think about it right it really if you think about it right it kind of makes sense right if I'm just kind of makes sense right if I'm just going through this and I want to see going through this and I want to see um how many like first of all if there's um how many like first of all if there's any overlapped but then I would I would any overlapped but then I would I would take a look at this one and then I can take a look at this one and then I can see it starts at zero ends at 30. and see it starts at zero ends at 30. and then this one definitely there is an then this one definitely there is an overlap because this last meeting hasn't overlap because this last meeting hasn't finished yet right and so finished yet right and so if you think about it so we we if you think about it so we we definitely need to do that right so we definitely need to do that right so we definitely need to sort based on start definitely need to sort based on start times okay so what else well in this times okay so what else well in this question we're asked to figure out the question we're asked to figure out the minimum number of meeting rooms that are minimum number of meeting rooms that are required like the conference rooms that required like the conference rooms that are required so how can we do this well are required so how can we do this well we know that like it the initial the we know that like it the initial the initial meeting roommate process right initial meeting roommate process right that's going to have like its own room that's going to have like its own room that's gonna have its own room okay so that's gonna have its own room okay so we know that and what we also know is we know that and what we also know is that this room is going to be used until that this room is going to be used until this time 30 right so for example if I this time 30 right so for example if I process this one and then I go on to process this one and then I go on to this one this one I basically have to understand that like I basically have to understand that like currently there's only one meeting room currently there's only one meeting room and that meeting room is ending at time and that meeting room is ending at time 30. so there's no way that I can process 30. so there's no way that I can process this one in the same room so this one this one in the same room so this one has to come inside it's other room this has to come inside it's other room this one has to come inside another room Okay one has to come inside another room Okay so we've done that now what about this so we've done that now what about this last one over here well this last one I last one over here well this last one I kind of have two options right I could kind of have two options right I could either choose from this meeting room I either choose from this meeting room I could choose from this meeting room or could choose from this meeting room or maybe like I'd have to create my own maybe like I'd have to create my own meeting room what can we do well when meeting room what can we do well when we're on this one over here we have to we're on this one over here we have to essentially determine that okay there's essentially determine that okay there's a meeting room that has a Time ending of a meeting room that has a Time ending of 30. there's a meeting room that has a 30. there's a meeting room that has a Time ending at 10. now what can we Time ending at 10. now what can we understand from this well you can understand from this well you can understand that from the meeting room understand that from the meeting room that has a Time ending at 10 then I can that has a Time ending at 10 then I can actually take its place right because my actually take its place right because my start time is 15 and because we've start time is 15 and because we've sorted based off the start time it means sorted based off the start time it means that I can essentially like take this that I can essentially like take this meeting room's place because this meeting room's place because this meeting is done and I can take its place meeting is done and I can take its place and so after I do that meeting two room and so after I do that meeting two room two will just have these two meetings two will just have these two meetings here so what does this kind of like here so what does this kind of like remind us of right like if you think remind us of right like if you think about it on any specific meeting we need about it on any specific meeting we need to know all of the ending times right to know all of the ending times right that are available and we want to that are available and we want to essentially pick the smallest ending essentially pick the smallest ending time right maybe this Maybe This Time time right maybe this Maybe This Time ended at like time like um you know ended at like time like um you know maybe nine or something and so we would maybe nine or something and so we would actually go ahead and pick this time it actually go ahead and pick this time it would evict this one and we would would evict this one and we would replace room one with this thing over replace room one with this thing over here right so what is this kind of here right so what is this kind of remind us of when we want to pick the remind us of when we want to pick the smallest time well if you think about it smallest time well if you think about it the the solution is a heap right we can the the solution is a heap right we can use a heap data structure so how make use a heap data structure so how make the Heap work well the Heap work well basically what we could do is that if basically what we could do is that if the Heap is empty then we know that the Heap is empty then we know that there are no meeting rooms so we add to there are no meeting rooms so we add to the Heap what do we add or we want to the Heap what do we add or we want to sort based off of or we want to extract sort based off of or we want to extract based off of the minimum ending time based off of the minimum ending time right if I'm over here I need to figure right if I'm over here I need to figure out which one of the rooms essentially out which one of the rooms essentially ended first right like which one which ended first right like which one which one of the rooms like doesn't have any one of the rooms like doesn't have any meetings anymore and that's determined meetings anymore and that's determined by the ending time right that's by the ending time right that's determined by the ending time it's not determined by the ending time it's not determined by the starting time because determined by the starting time because the starting time might be like a super the starting time might be like a super high value but if the if the meeting high value but if the if the meeting ends in like one minute well that's her ends in like one minute well that's her main focus right so if you think about main focus right so if you think about it what we can do is once we sort based it what we can do is once we sort based off the start time then off the start time then add element to Heap add element to Heap based on ending time and then based on ending time and then when adding new elements when adding new elements check if check if we can pop from Heap we can pop from Heap meaning meaning old meeting has finished right so what old meeting has finished right so what does this mean let's maybe take a look does this mean let's maybe take a look in the code to kind of see what I'm in the code to kind of see what I'm saying here but hopefully this step that saying here but hopefully this step that we have over here can we have over here can easily explain it but okay so what do we easily explain it but okay so what do we need well we need a heap right so we can need well we need a heap right so we can do like uh from Heap queue import he pop do like uh from Heap queue import he pop and hit push okay What else do we need and hit push okay What else do we need well we need our Heap which I just call well we need our Heap which I just call this and then I need to go through my this and then I need to go through my intervals right so I need to go through intervals right so I need to go through my intervals I will do four interval my intervals I will do four interval in intervals okay so now I'm processing in intervals okay so now I'm processing this first one now what do I understand this first one now what do I understand well I understand in the first one well I understand in the first one actually first thing actually we need to actually first thing actually we need to do is sort it based off at the start do is sort it based off at the start times right so maybe we can do intervals times right so maybe we can do intervals is sorted intervals and what the key is is sorted intervals and what the key is based off of dot start right and it's based off of dot start right and it's because of the list of intervals so because of the list of intervals so intervals is actually a class over here intervals is actually a class over here so you can see we have the start and the so you can see we have the start and the end so that's why we have that okay so end so that's why we have that okay so after I've done that I can go ahead and after I've done that I can go ahead and loop through my intervals and now what loop through my intervals and now what well this first interval that I have I well this first interval that I have I have no like meeting rooms right you can have no like meeting rooms right you can think of this Heap as storing the think of this Heap as storing the amounting the amount of meeting rooms amounting the amount of meeting rooms that we can have at any specific time so that we can have at any specific time so this Heap over here if you think about this Heap over here if you think about it if Heap is empty so if not Heap then it if Heap is empty so if not Heap then no meetings no meeting rooms no meetings no meeting rooms create one so we can do is we can increase our count so maybe we'll start off our count at zero and then we'll return our count in the end this is the count of meeting rooms and then what what then we need to go ahead and we need to add how do I turn off autocomplete can I do that because it turn it off getting annoying yeah so if if we if we're going to be using a meeting room well then we have to add it to our Heap so I can do Heap push H and then what do I need to add well remember we want to pop based off of the earliest the smallest ending time so we will pop based off the ending time so I'll do interval.e and then interval.s so what is this going to do well to the Heap what it's going to add essentially it's going to add in the value 30 and then zero and for example if we go into if we go ahead and we process this element here right so maybe if Heap does if Heap is not empty then check if any items on if check if any items finished right so how do I determine that well I can check if heat adds zero right heaped zero will essentially be the item that has a smallest ending time has the smallest ending time if this item if this item that we have right if this item if this is so this is the ending right time right this is the ending time ending and starting so if the ending time of the meeting if this is somehow less than or equal to the starting time of my current meeting right so this character listen to this carefully if the ending time of this meeting which is based off of this first element here if this meeting has ended before our meeting has started well then I can go ahead and use this room right so what I can do is I could just do heat pump and I will pop a heap up and I'll pop from the Heap and I don't actually care about the value but then what I could do is I could append to the Heap I'll do he push H and what do I want to append well I want to append this same thing over here I will append the starting time and the ending time based off of my information here now in this case we actually won't go ahead and and actually here um if you think about it here we don't need to increase the res right because we're using the same meeting room so we don't need to do that but let's just kind of take a look at like what this might look like in the first case our Heap just has this value here right he just has this and so what we do is we check to see if the ending time is less than our starting time which in this case is 5 it's not so what we're going to do is we're going to append 5 and 10 to the list to the Heap but we're append it in reverse order and so now we have two meeting rooms right and so I guess here if if it's else right if it's else this means we cannot use existing meeting room so create own actually uh we we need this and we need actually uh we we need this and we need it over here as well but here we will it over here as well but here we will actually append to Res right here we'll actually append to Res right here we'll append to rest so what we're doing here append to rest so what we're doing here is like we're pushing regardless we're is like we're pushing regardless we're pushing regardless right because maybe pushing regardless right because maybe in this case I'll replace it maybe in in this case I'll replace it maybe in this case I have to add it but we're this case I have to add it but we're pushing regardless but if I have to add pushing regardless but if I have to add it then I want to increase my res okay it then I want to increase my res okay so what happens at this point res is so what happens at this point res is equal to two and then when I go to equal to two and then when I go to process this element here this meeting process this element here this meeting room over here I can see that Heap at room over here I can see that Heap at zero will actually be reordered the Heap zero will actually be reordered the Heap will be reordered to something like this will be reordered to something like this why because it's ordered based off of why because it's ordered based off of the ending time and the ending time here the ending time and the ending time here is 10 and so when I look at this I can is 10 and so when I look at this I can see that 10 is less than or equal to 15. see that 10 is less than or equal to 15. and so what this means is that this room and so what this means is that this room over here can be replaced by 15 and then over here can be replaced by 15 and then 20. and so that's why this will actually 20. and so that's why this will actually give us the minimum amount of room that give us the minimum amount of room that we need and so you can keep doing this we need and so you can keep doing this but in the end whatever solution let's but in the end whatever solution let's take a look at the test cases to see take a look at the test cases to see that they passed so this should be end that they passed so this should be end alert alert start and then end keep is not defined keep is not defined um um where am I doing the heaped zero so I where am I doing the heaped zero so I guess I should be H at zero guess I should be H at zero and between Tuple and int yeah and between Tuple and int yeah um each had zero oh I guess H at zero refers to the actual like Heap itself right so like this value here so we actually need H at zero at zero so that will give us the start time right and so then we can go ahead and submit it and then we can arrive at the solution perfect so don't really worry about the percentage Beast beat this is actually like the efficient solution here so what is the time here well if you think about it for the time and space we we have to concern ourselves with the Heap itself right so in the worst case I need to add in everything to the Heap right because there's an overlap every single time so if I add in everything to a heap then I'm doing a heat push that is a log end time and essentially like um I would also maybe I don't need to do a heat pop but assuming like I do need to do hip-hop then it would be like n log n right and actually like by sorting here it is also n log n so really it's still dominated by the sword over here but in terms of the space you can kind of think of the space as o of n because at the worst like we will add in all of the items onto the Heap the time is n log n the space is O of n
2024-03-22 12:08:11
253
https://i.ytimg.com/vi/2…axresdefault.jpg
Meeting Rooms II - Leetcode 253 - Python
Uuy2TpDFu2o
Going to question check double exists a simple exists whose double is also in the same array as in this example punch is a number whose double i.e. 10 remaxists from this what does it mean I will What What What is 317? There is no number is 317? There is no number whose double is present in this array so we will whose double is present in this array so we will return false. What is the first method? The return false. What is the first method? The first method is pick this number and check whether it has first method is pick this number and check whether it has double or not. Pick this number and check whether double or not. Pick this number and check whether it has double or not. it has double or not. it has double or not. in these squares. Okay, what is the other way? Sort it because it is not sorted, then it will be sorted in N people, then what to do, what are we doing now? Right now, we are doing linear search So what will we So what will we So what will we do now, pick it, apply binary search on the rest, do now, pick it, apply binary search on the rest, i.e. whether 2i accesses or not, i.e. whether 2i accesses or not, okay, so sort in n people okay, so sort in n people and why do binary search in only n people, and why do binary search in only n people, because what will be searched first, there will be a loop and more because what will be searched first, there will be a loop and more people will search. people will search. people will search. N people in. What is the third way? The third way is to use the set. How do I explain the use of the set? As you are iterating, keep moving it around in the set, Then Then Then in the second loop, check whether it is in the second loop, check whether it is accessing double the current element or not. So accessing double the current element or not. So what to do in the first loop is to what to do in the first loop is to put it in the set and look in the second one. put it in the set and look in the second one. Grab each element and see whether the Grab each element and see whether the double access of the current element is done. double access of the current element is done. double access of the current element is done. What is happening in it? It is time for Big Off N. It is time for Big Off N but you are the fourth and last driver. We will use the set only but take one 10253. See what is happening in it. 10253. See what is happening in it. In this, as soon as I see the element, I will In this, as soon as I see the element, I will add it to my set, okay, and I will check add it to my set, okay, and I will check whether we have added its double in my set, whether we have added its double in my set, that is, it is kept in the set, okay, that is, it is kept in the set, okay, so much silence, okay, I have added it. I saw the so much silence, okay, I have added it. I saw the double of the first 10. double of the first 10. double of the first 10. in the set, it is given in the set, then it goes to two, then it is seen that four exists, it does not exist, there is no problem, it is given, this is also given, then it is seen that Alexis doubles the punch, if it loses, then return it, but I take it. This is not our list. This is our list. 5103 Now see, double of 5 exists, no problem, add 2 in your set. Double of 2 exists, doesn't. Brother, only punch is in the set, so add that Double axis of 5 does Double axis of 5 does Double axis of 5 does not do, look at that too, not do, look at that too, double of three does axis i.e. double of 3 does not double of three does axis i.e. double of 3 does not do 6. No fun. There is something wrong in this algorithm. do 6. No fun. There is something wrong in this algorithm. Double axis of 5 does, Double axis of 5 does, we can see it but the punch has already been given. we can see it but the punch has already been given. When the punch has already come and 10 will When the punch has already come and 10 will come in the future then we are already checking the double 10 of the punch come in the future then we are already checking the double 10 of the punch so if we are making a mess then we so if we are making a mess then we can do one more thing. Look carefully here can do one more thing. Look carefully here as I am adding some element. as I am adding some element. as I am adding some element. checking one thing that whether his double axis works or not, I will check another thing that his half does not adjust. Now look like Sam of the future ca n't do anything when we are Panch Dal. Don't know brother whether 10 will come or not but we can reduce it when its double comes, its possible double will come i.e. 10 will come, we will check whether 10/2 exits with us, 10 bye tu bole to If it is 5, If it is 5, If it is 5, what does it mean that there are some what does it mean that there are some elements in our list whose double exists? Well, elements in our list whose double exists? Well, then obvviesli, first we then obvviesli, first we have to see whether that number is And or have to see whether that number is And or not. If it is E1, then we will see that N/2 not. If it is E1, then we will see that N/2 exists. exists. exists. pay ten and han han 10 / 2 exists doesn't han does punch Okay so this is the algorithm let's start take the code map or take the set you will take these sets you are taking which Type Type Type Integer Type Set Name Set We will keep it equal Integer Type Set Name Set We will keep it equal You are ok Now what will we do Now we will You are ok Now what will we do Now we will put loop Forint I will check in it or its half Well for half we will first check What is I Module you equal Zero If yes then return true. If yes then return true. If yes then return true. If such condition does not come If such condition does not come then what to do in the last step. Returns false. then what to do in the last step. Returns false. Ok, let's run and see. If it is Ok, let's run and see. If it is not put in Han side then let's not put in Han side then let's put set dot add i after every iteration. put set dot add i after every iteration. After checking, we will also add it to the set. After checking, we will also add it to the set. Okay, it is accepted. Let's Okay, it is accepted. Let's submit. It is very good, so submit. It is very good, so nothing has been done. The set has been used. nothing has been done. The set has been used. Space complexity is big off and end time is also Space complexity is big off and end time is also big off. One loop is run. big off. One loop is run. big off. One loop is run. which checks whether an element is present in the set or not is an operation in the Big One, so basically we have used the word double land double this. If the question is that X does not do it, then we What to do here is to check whether the Three Eye exists or not and what to check or not. There are other ways to solve it. Obviously, as I told you, you can use binary search, but Apna
2024-03-21 00:20:55
1,346
https://i.ytimg.com/vi_w…xresdefault.webp
Check if n and its double exist LeetCode Solution in Hindi
jJMWhGKq3SM
hi guys this is khushboo and welcome to algorithms made easy algorithms made easy in this video we'll see the question n in this video we'll see the question n queens queens the n queen puzzle is a problem of the n queen puzzle is a problem of placing n placing n number of queens on an n cross n number of queens on an n cross n chessboard chessboard such that no two queens attack each such that no two queens attack each other other given an integer n return all the given an integer n return all the distinct solutions to the end queen distinct solutions to the end queen puzzle puzzle each solution contains a distinct board each solution contains a distinct board configuration of the n configuration of the n queen's placement where q represent queen's placement where q represent queen and dot will represent an empty queen and dot will represent an empty space space so we are given this example which says so we are given this example which says n equal to four so here we have got a n equal to four so here we have got a four cross four chess board four cross four chess board and we can have two combinations of and we can have two combinations of queen's placement wherein we have placed queen's placement wherein we have placed four queens on the chest board four queens on the chest board such that no queens are attacking the such that no queens are attacking the other queens other queens how do you know if a queen can attack how do you know if a queen can attack another queen or not another queen or not in chess a queen may attack another in chess a queen may attack another queen queen if it is coming into the same row if it is coming into the same row if it is coming into the same column or if it is coming into the same column or if it appears in one of the if it appears in one of the diagonals for that particular queen so diagonals for that particular queen so these are the three conditions that we these are the three conditions that we need to take care of need to take care of similarly we are given the second similarly we are given the second example and the constraint says example and the constraint says that n would be in between 1 and 9. one that n would be in between 1 and 9. one of the basic intuitions for this of the basic intuitions for this question question is that you need to iterate over each is that you need to iterate over each and every and every cell in the chess board and try to find cell in the chess board and try to find a combination a combination so it becomes a dfs solution so it becomes a dfs solution and secondly if you are unable to do so and secondly if you are unable to do so you need to backtrack it you need to backtrack it and try for another combination so this and try for another combination so this question question is going to be a combination of dfs and is going to be a combination of dfs and backtracking so let's go ahead and see backtracking so let's go ahead and see how we can how we can use it to solve this problem let's take use it to solve this problem let's take the same example the same example of 4 cross 4 chessboard so these are the of 4 cross 4 chessboard so these are the two placements that are possible for end two placements that are possible for end queen problem queen problem now let's take one of the chess board now let's take one of the chess board and see and see what other directions a queen can move what other directions a queen can move so over here we have given the path a so over here we have given the path a queen can take in different colors for queen can take in different colors for all the different queens all the different queens so if you see this queen which is having so if you see this queen which is having a path of blue dotted line will move in a path of blue dotted line will move in either either this diagonal or this column or this row this diagonal or this column or this row similarly for all the other queens similarly for all the other queens now if you notice for this particular now if you notice for this particular cell cell there are no other color dotted lines there are no other color dotted lines coming in coming in this means that no other queen can reach this means that no other queen can reach this particular cell this particular cell similarly for the green one white one similarly for the green one white one and the red one and the red one and so these are the safe placements for and so these are the safe placements for the queens the queens so the first thing that comes to the so the first thing that comes to the mind is what are the conditions that we mind is what are the conditions that we can apply to choose a safe position can apply to choose a safe position now a queen cannot be placed now a queen cannot be placed in the same row same column and same in the same row same column and same diagonal diagonal if we take this particular queen no if we take this particular queen no queen should come in the same row as it queen should come in the same row as it is falling into is falling into the same column it is falling into or the same column it is falling into or in any of the diagonal cells for this in any of the diagonal cells for this queen queen and if you see over here all the and if you see over here all the conditions are satisfied and so this is conditions are satisfied and so this is a safe position for this particular a safe position for this particular queen now how do we queen now how do we find out if the other queens are in same find out if the other queens are in same row same column or same diagonal row same column or same diagonal so for that let's start with the same so for that let's start with the same row condition if any of the other queen row condition if any of the other queen falls in the same row the absolute falls in the same row the absolute difference between the rows of both the difference between the rows of both the queens would be zero queens would be zero that is the row for this particular that is the row for this particular queen if placed here would have been row queen if placed here would have been row one one and this is also in row one so the and this is also in row one so the difference between those two rows is difference between those two rows is zero zero and that should not be the case and that should not be the case similarly for similarly for column the absolute difference of the column the absolute difference of the columns of two queens must not be zero columns of two queens must not be zero that is it should be non-zero so if this that is it should be non-zero so if this queen was queen was falling into this column the column for falling into this column the column for this particular queen would have been this particular queen would have been three three and for this queen is also three its and for this queen is also three its absolute difference would have become absolute difference would have become zero and so we can say that the queens zero and so we can say that the queens are are in the same line and one of the queen in the same line and one of the queen can attack the other can attack the other queen so we need to take care of this queen so we need to take care of this condition so we are taking d condition so we are taking d y not equal to 0 as a condition y not equal to 0 as a condition for same column third is the diagonal for same column third is the diagonal condition condition now how do you find out the diagonal now how do you find out the diagonal element element if you notice for a diagonal element if you notice for a diagonal element we are going to move the same amount in we are going to move the same amount in x x and the same amount in y and that and the same amount in y and that becomes the diagonal becomes the diagonal so the difference between the x is equal so the difference between the x is equal to the difference between the y to the difference between the y for a diagonal so we are going to say for a diagonal so we are going to say that that the absolute difference between the rows the absolute difference between the rows of the queens must not be equal to the of the queens must not be equal to the absolute difference absolute difference of the columns for the queen that is of the columns for the queen that is dx should not be equal to d y and so dx should not be equal to d y and so these are the three conditions that we these are the three conditions that we need to apply that is need to apply that is my dx should not be equal to 0 dy should my dx should not be equal to 0 dy should not be equal to 0 and not be equal to 0 and dx must not be equal to dy now let's see dx must not be equal to dy now let's see what are the different data structures what are the different data structures that we would need in order to solve that we would need in order to solve this problem this problem the first one that we are going to need the first one that we are going to need is the board the n is the board the n cross n board representation so it would cross n board representation so it would be a be a character array that would be n cross n character array that would be n cross n and dot will represent empty and q will and dot will represent empty and q will represent represent queen in that the second thing is to queen in that the second thing is to store the position of store the position of all the queens that we have placed till all the queens that we have placed till now so for that we'll need a list of all now so for that we'll need a list of all the positions and a position will be the positions and a position will be given by given by x and y coordinate so that we can take x and y coordinate so that we can take it as an integer array it as an integer array so these were the things that we would so these were the things that we would need next is what are the steps and how need next is what are the steps and how we are going to solve this problem we are going to solve this problem so the first thing is to perform dfs and so the first thing is to perform dfs and for that we'll start from zero comma for that we'll start from zero comma zero that is the first zero that is the first cell the second step is check if a queen cell the second step is check if a queen can be placed at the current position can be placed at the current position so for that we'll be checking if it is a so for that we'll be checking if it is a valid position valid position or not if it is we'll place the queen or not if it is we'll place the queen we'll fix that position we'll fix that position and we'll try adding the remaining and we'll try adding the remaining queens in the board queens in the board if not we'll backtrack and check for if not we'll backtrack and check for other combinations other combinations so like this we need to find all the so like this we need to find all the combinations combinations now one more thing that we need to note now one more thing that we need to note over here is that over here is that while repeating the process or while while repeating the process or while recursively calling the dfs function recursively calling the dfs function suppose we have placed a queen over here suppose we have placed a queen over here in row 0. in row 0. now while repeating would i need to now while repeating would i need to start with start with the next cell in the same row no i need the next cell in the same row no i need to go into the row below because to go into the row below because we know that we cannot add the queen in we know that we cannot add the queen in the same row the same row so we skip the current row and call the so we skip the current row and call the dfs function dfs function on the next row so we'll be going row by on the next row so we'll be going row by row row and we'll try to solve this problem so and we'll try to solve this problem so this was about this was about the process that is going to be involved the process that is going to be involved now let us go ahead and code this out now let us go ahead and code this out the first thing that we are going to the first thing that we are going to need over here is the result which is in need over here is the result which is in the form of the form of list of list of string list of list of string and let's initialize it the second thing and let's initialize it the second thing is the board which is going to be a 2d is the board which is going to be a 2d character array character array and its size is going to be n cross n and its size is going to be n cross n initially we will fill this board initially we will fill this board as an empty board so we are going to add as an empty board so we are going to add all the dots in it so over here we have filled it as empty cells now the other thing that we need is the positions for all the queens that we have so it would be a list and initially it would be an empty list after we have this we are going to call dfs on the board starting from the zeroth row and we will pass this queens list so this is going to take care of all the logic finally we can return the result and this is going to be our main functionality so this is our dfs function in this we so this is our dfs function in this we need to see need to see that if all the queens are placed or not that if all the queens are placed or not so that would become the exit condition so if all the queens are placed its size will be equal to if that is the case we need to construct if that is the case we need to construct our our output for constructing the output which output for constructing the output which is in the format of is in the format of list of list of string now the internal list of list of string now the internal string represents the rows string represents the rows so let's take that and we'll iterate so let's take that and we'll iterate over the board over the board for each row with this we need to add for each row with this we need to add this character array as a string this character array as a string into the rows once this is done we need into the rows once this is done we need to add to add this particular rows into our result so this particular rows into our result so we'll do we'll do result add rows and that's all our result add rows and that's all our result has been constructed result has been constructed if this is not the case then we need to if this is not the case then we need to try adding the queen try adding the queen so we'll take a loop and try adding the so we'll take a loop and try adding the queen so this is going to be iterated for a row and over here we'll take iteration on the column let's check if we can add a queen for this particular row and column given the queens that i have already added so if we can add a queen we are going to update the board with q for this particular position with this we also need to update the queen's list so queens dot add r comma c and now we need to call dfs on the next row with the updated queens list after this is done we also need to backtrack and check for other positions because we need all the combinations so for backtracking we again need to set this as dot instead of q and we need to remove the queen that we added so this is going to take care of recursively calling the function and finding the combinations now what we need is implement the can add queen method so over here we need to check the so over here we need to check the condition for row column and diagonal condition for row column and diagonal so for all the queens that we have so for all the queens that we have placed we need to check and see whether placed we need to check and see whether the current row the current row column is safe or not so let's iterate column is safe or not so let's iterate over this over this and over here we need to check dxdy and over here we need to check dxdy conditions so conditions so let's calculate dx which will be let's calculate dx which will be the difference between the rows and d y the difference between the rows and d y would be difference between the column would be difference between the column so now we need to return false if it so now we need to return false if it falls in the same falls in the same row same column or same diagonal which row same column or same diagonal which would be given by the condition would be given by the condition if dx is 0 if dx is 0 or d y is 0 or or d y is 0 or dx is equal to d y if this is there dx is equal to d y if this is there return false and if for any queen this return false and if for any queen this is not satisfied is not satisfied return true and that's it let's try to return true and that's it let's try to run this code run this code and see if we have any compile time and see if we have any compile time issues issues and this is a character array let's run and this is a character array let's run this again this again and it's giving a perfect result let's and it's giving a perfect result let's submit this and it got submit this and it got submitted so that's it for this question submitted so that's it for this question guys i hope you liked it and i'll see guys i hope you liked it and i'll see you in another one you in another one so till then keep learning keep coding
2024-03-20 09:59:53
51
https://i.ytimg.com/vi/j…axresdefault.jpg
N-Queens | Live Coding with Explanation | Leetcode - 51
Y9KLIwd6ppY
hi everyone welcome back to the channel and today we're going to solve with code and today we're going to solve with code daily challenge problem number daily challenge problem number 912 sort and array so it's a really 912 sort and array so it's a really simple and a straightforward problem in simple and a straightforward problem in which uh they want us to solve or they which uh they want us to solve or they want us to sort an array in an ascending want us to sort an array in an ascending order and just want to return that okay order and just want to return that okay and this is the condition which we have and this is the condition which we have received which is we are not allowed to received which is we are not allowed to use any inbuilt functions use any inbuilt functions and the output should have or the code and the output should have or the code should have a maximum time complexity of should have a maximum time complexity of n log n n log n okay so these this is the condition and okay so these this is the condition and this is the requirement simple and this is the requirement simple and straightforward right straightforward right so uh you know when you think of any so uh you know when you think of any sorting algorithm which can give you the sorting algorithm which can give you the result in N log n the two algorithm result in N log n the two algorithm which comes to the top is heaps or and which comes to the top is heaps or and mode sort right mode sort right and I'm gonna use a mod sort in this and I'm gonna use a mod sort in this particular for this particular problem particular for this particular problem and and if you don't know what's actually more if you don't know what's actually more sort is don't worry like uh have a you sort is don't worry like uh have a you know diagram prepared for that and let's know diagram prepared for that and let's just move to that and I'll explain you just move to that and I'll explain you what exactly we do in them also okay what exactly we do in them also okay so uh let's say this was the given array so uh let's say this was the given array with element five two three one let's with element five two three one let's say okay say okay so in more sort the aim is to Simply you so in more sort the aim is to Simply you know just divide the array in equal know just divide the array in equal halves it each time until you get halves it each time until you get single elements single elements for example we have five two three one for example we have five two three one right we divided that in five two and right we divided that in five two and three one three one still uh the elements were not still uh the elements were not individual so we for the divided that individual so we for the divided that again again then we got individual blocks of then we got individual blocks of elements right five two three one elements right five two three one now uh basically we have broken down the now uh basically we have broken down the given array into individual elements now given array into individual elements now you have to plug that back into one you have to plug that back into one array right array right and while doing that you will compare and while doing that you will compare the value of value of both these the value of value of both these elements for example two and five which elements for example two and five which one is uh smaller two of course so you one is uh smaller two of course so you will put in uh I think sorry I made a will put in uh I think sorry I made a mistake over here it's fine mistake over here it's fine so you will put 2 first and five so you will put 2 first and five okay similarly in this block for you okay similarly in this block for you will compare one entry what you'll get will compare one entry what you'll get one and then one and then three three okay then further when you know you okay then further when you know you didn't get the complete array right at didn't get the complete array right at this step so you will again merge these this step so you will again merge these two sub errors down and while doing so two sub errors down and while doing so you will compare each element you will compare each element uh with each other right so what it will uh with each other right so what it will be now so it will be one be now so it will be one two three and five so this exact this approach is called Mozart okay and it is guaranteed to get an N log it time complexity uh with this particular algorithm so it's uh and it is also really simple to implement as well so let's move post thanks for us uh I want to check post thanks for us uh I want to check like here like here so what I'll be doing is I'll be so what I'll be doing is I'll be basically calling this uh sort array basically calling this uh sort array method recursively okay and as we saw method recursively okay and as we saw like what we wanted we wanted to have we like what we wanted we wanted to have we wanted to break the elements wanted to break the elements in half at each step until we get to the in half at each step until we get to the individual element so if individual element so if length of length of nouns nouns is greater than one nums is the array is greater than one nums is the array which we are getting right which we are getting right if yes then we'll perform some if yes then we'll perform some operations otherwise I'll just simply operations otherwise I'll just simply return the return the exact same array exact same array okay okay now we want to divide that into two now we want to divide that into two halves right so what I'll be doing is halves right so what I'll be doing is I'll be taking the flow division of the length and I'll divide that into two r or left half and look right up right it's half okay so left half will have all the values till the mid okay and the right part will have everything after it so now we have divided the given array right now I wanted to call my sort array function recursively fall for left half and right half self taught sort array and in the next call passenger right half as well okay so after uh this computation you will basically get your uh sorted now uh what we need to do is we need to now uh what we need to do is we need to just merge this array light because we just merge this array light because we divided that we have done the Sorting on divided that we have done the Sorting on the individual level now we want to the individual level now we want to merge those as well right so what will you do you will need three pointers basically first one to uh point to your left half J Will point to the right half and the point of K which will basically point to your original nums area in which you will be updating the values right and we'll initialize that with all with zero okay now what I want to do is while I is less than length of left half all right J is less than length of later okay while these two conditions are true basically if we have any uh element in both the arrays because we wanted to compare those values right so we will follow this Loop if the value in the left half is the if the value in the left half is the current value in the left half is current value in the left half is smaller than the value current value of smaller than the value current value of the right half the right half excuse me then what I want I want to excuse me then what I want I want to update the value in nums a update the value in nums a at gate location with my smaller value at gate location with my smaller value left half and left half and pi pi and if you know if we have put in the and if you know if we have put in the value from laptop I do want to increment value from laptop I do want to increment the pointer as well right the pointer as well right else will do the else will do the other way down other way down we will put in the value from we will put in the value from right half right half at Jade index at Jade index and we will implement the JS pointer and we will implement the JS pointer at the end of this while loop I do want at the end of this while loop I do want to implement the K pointer as well to implement the K pointer as well okay so basically you have done the okay so basically you have done the merging but there is a catch uh it is we merging but there is a catch uh it is we are not sure that you know we will be are not sure that you know we will be able to cover all the elements of both able to cover all the elements of both these sub arrays in this file Loop so these sub arrays in this file Loop so there are chances that there will be there are chances that there will be some leftover elements in I and leftover some leftover elements in I and leftover elements in J as well which you want to elements in J as well which you want to append at the end right so for that append at the end right so for that what we'll do while I is less than like what we'll do while I is less than like this condition in in individually this this condition in in individually this condition condition I want to run a loop and what we want we I want to run a loop and what we want we want to do this want to do this this and you would like to increment K as well and we will do exactly the same for J pointer as well J is less than write half you want write out see and done so this was the complete solution this is what all you need to do uh let's check out the test okay AR is I use URL okay so the test case has got let's let's index out of range I must have let's index out of range I must have done something line number uh 28 is over here nums of uh sorry this should have been J awesome so the solution was accepted and awesome so the solution was accepted and we perform decent like we have performed we perform decent like we have performed 40.1 percent of the summary of solution 40.1 percent of the summary of solution so yeah thanks again guys for watching so yeah thanks again guys for watching out the video and stay tuned for the out the video and stay tuned for the upcoming ones don't forget to subscribe upcoming ones don't forget to subscribe to the channel thank you
2024-03-25 10:51:24
912
https://i.ytimg.com/vi/Y…axresdefault.jpg
Sort an Array - Leetcode 912 - Python
r2BtbKSAMVk
Hello hello welcome to Delhi report is required till 1658 we are in this news district so I will give till 1658 we are in this news district so I will give into strips 60 units start to-do list like example with 2GB RAM by Saurabh like example with 2GB RAM by Saurabh Singh b positive thinking simple to b b b b subscribe and subscirbe subscribe now Now To Receive New Updates Hai Ki Saugandh 300 Ko Zara Because They Had Online A Different Darkness Mein Druk Gaya Hai Main Example And Virag And Toot Saaf Main Example And Virag And Toot Saaf Birthday Correction Different Solutions For Birthday Correction Different Solutions For Class Twelfth Peeth Mixi This Update Please Class Twelfth Peeth Mixi This Update Please Please Like Share And Subscribe To Please Like Share And Subscribe To Aap ten seconds sirvi bandhu tiffin size and Aap ten seconds sirvi bandhu tiffin size and taraf india 100 list set do ki taraf india 100 list set do ki blast case where they have different blast case where they have different things but about option size shift things but about option size shift subscribe to hai subscribe to hai so lets of fixed rate so dat digital so lets of fixed rate so dat digital audio files from 0110 solid to audio files from 0110 solid to properties only properties only properties only so let's see code 's journey cases stratification this medical institute for this channel is not subscribed and then size different day discovery clock on vignal tal rock it takes care of viraval pradeep just example2 10 behave with r one one one Register Checked Programs Seervi Seervi Seervi Hai How To That When 12th Ne - District Ko 12 Finally Abhi Hotspot District Tarf Example And A Fantastic Surf Excel Size Networking Service Friend According 500 Maintenance And Different What They Are Doing Research On 1212 corruption scams during only at least 10 minutes and friends so Vijay Prakash friends questions our difference of character between minutes and boosting while to our channel like this point to and that of election 2014 155 So Let's Organization Time 155 So Let's Organization Time Complexity Of Shyam Request One Tablespoon Vikas Mishra Business Dining Table Spoon Springsteen Essay Thanks
2024-03-22 16:25:08
859
https://i.ytimg.com/vi/r…axresdefault.jpg
Buddy Strings Leetcode 859 video
0snEunUacZY
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve let's solve letter combinations of a phone number so letter combinations of a phone number so we're given a we're given a string of digits that contain string of digits that contain only two through nine so the digits are only two through nine so the digits are only going to contain the numbers only going to contain the numbers 2 through 9 and we want to return all 2 through 9 and we want to return all possible letter combinations that the possible letter combinations that the number number could represent and so basically what could represent and so basically what this problem is about this problem is about is like when you wanted to text people is like when you wanted to text people with old phones you only had with old phones you only had these digits right so in order to have these digits right so in order to have characters you'd map a number like two characters you'd map a number like two to the characters a b c to the characters a b c and you can see the reason we're doing and you can see the reason we're doing two through nine is because two through nine is because one was not mapped to any digits right one was not mapped to any digits right so we don't need to consider the one so we don't need to consider the one two was mapped to abc three was mapped two was mapped to abc three was mapped to d to d e f basically each number or each digit e f basically each number or each digit four five six each one was mapped to four five six each one was mapped to three characters some were mapped to three characters some were mapped to four characters seven is mapped to four four characters seven is mapped to four nine is mapped to four different nine is mapped to four different characters so then if you're given characters so then if you're given a string of digits let's say two 3 in a string of digits let's say two 3 in this this case right 2 3 is our string well how case right 2 3 is our string well how many different many different output strings could we have here you output strings could we have here you can see we have a can see we have a bunch right we have 9 different strings bunch right we have 9 different strings why do we have 9 different strings why do we have 9 different strings because this two could be three because this two could be three different characters it could be different characters it could be a b or c this a b or c this three could also be three different three could also be three different characters d characters d e f so three times e f so three times three is nine so basically we can have three is nine so basically we can have we can have nine different combinations we can have nine different combinations of these characters right of these characters right we could have a d we could have a we could have a d we could have a e we could have a f right and so on and e we could have a f right and so on and so on right so so on right so we could have b e b b f we could have b e b b f and then do the same thing for c right and then do the same thing for c right so then you would have nine different so then you would have nine different strings strings and so basically you can tell that this and so basically you can tell that this problem right like writing out the problem right like writing out the solution like this it's not that solution like this it's not that difficult because we're gonna basically difficult because we're gonna basically be forced to brute force this problem be forced to brute force this problem and it's a backtracking problem because and it's a backtracking problem because we have to brute force it right we have we have to brute force it right we have to basically find every single to basically find every single combination combination that we could get using the given digits that we could get using the given digits and and you might have noticed i've been doing a you might have noticed i've been doing a lot of backtracking problems recently lot of backtracking problems recently and that just goes to show you that and that just goes to show you that backtracking is a very important backtracking is a very important algorithm algorithm so let me just show you kind of the so let me just show you kind of the drawing of the backtracking solution so drawing of the backtracking solution so luckily for us in this case we're only luckily for us in this case we're only given two given two three right and so we only need to find three right and so we only need to find okay two maps to these three characters okay two maps to these three characters three maps to these three characters but three maps to these three characters but we know in total we know in total we it's possible we could have a four we we it's possible we could have a four we could have a five if we had a four could have a five if we had a four we know four maps to the next three we know four maps to the next three characters after this characters after this so g h i i think unless i'm forgetting so g h i i think unless i'm forgetting something something and basically we could have any and basically we could have any character right from character right from two through nine so we're going to need two through nine so we're going to need to create a hash map to create a hash map or some kind of way to map every or some kind of way to map every character from character from or basically every digit from two all or basically every digit from two all the way the way to five six seven all the way to nine to five six seven all the way to nine right and right and map them to the characters that they end map them to the characters that they end up being right we know nine is up being right we know nine is i think gonna be xyz we're basically i think gonna be xyz we're basically gonna have to hard gonna have to hard code this map of characters there's not code this map of characters there's not like a clean way to do it mainly because like a clean way to do it mainly because some of the characters some of the characters i think seven has four characters right i think seven has four characters right seven is mapped to four different seven is mapped to four different characters and characters and so whatever but this is a pretty small so whatever but this is a pretty small hash map right so it's not a big deal if hash map right so it's not a big deal if we have to hard code it we have to hard code it but now let's just look at this problem but now let's just look at this problem itself how are we going to solve it well itself how are we going to solve it well so the first character is 2 so the first character is 2 right so 2 could map to three right so 2 could map to three different characters so two being the different characters so two being the first digit it can map to a first digit it can map to a b or c right and the next character we b or c right and the next character we know or the next digit is know or the next digit is three so from a we could have three three so from a we could have three different different characters that follow after it we could characters that follow after it we could have a d have a d we could have an e or we could have an f we could have an e or we could have an f and that's going to be true for and that's going to be true for every single one of these right we could every single one of these right we could basically put a d basically put a d e f after each of them and this e f after each of them and this is the entire backtracking tree so based is the entire backtracking tree so based on this on this what's our solution because remember we what's our solution because remember we want to know the strings want to know the strings that this could map to well this is one that this could map to well this is one string string this is one string this is another this is one string this is another string so basically for string so basically for each of the leaf nodes in this tree each of the leaf nodes in this tree we're going to we're going to follow the entire like list of follow the entire like list of characters that came before that's going characters that came before that's going to be the output strings right a to be the output strings right a a d a e a f a d a e a f and so on right b d b e and so on right b d b e b f and the exact same thing for c b f and the exact same thing for c so when you visualize it like this this so when you visualize it like this this is actually a pretty simple problem is actually a pretty simple problem so now you just need to know how to so now you just need to know how to write this backtracking algorithm and write this backtracking algorithm and i'm going to show you how to do this i'm going to show you how to do this recursively but before i do that the recursively but before i do that the time complexity for this time complexity for this is basically the number of combinations is basically the number of combinations that we're going to have that we're going to have so the question is how many different so the question is how many different output output could we have for a string let's say the could we have for a string let's say the input string is length input string is length n how many different outputs could we n how many different outputs could we have well since we know that there are have well since we know that there are some characters like i think some characters like i think nine maps to four different characters i nine maps to four different characters i think w think w x y z actually so the brute force is x y z actually so the brute force is gonna be gonna be four to the power of n that's how many four to the power of n that's how many outputs we could actually have right outputs we could actually have right because maybe we'd get because maybe we'd get a string s equal 9999 right so a string s equal 9999 right so basically we'd have four choices for basically we'd have four choices for each of those characters so 4 times 4 each of those characters so 4 times 4 basically 4 to the power of n which is basically 4 to the power of n which is the the length of the input string right so length of the input string right so that's the number that's the number of output strings that we're going to of output strings that we're going to have and the length of each have and the length of each output string is going to be the same as output string is going to be the same as the length of the the length of the input string right so really the time input string right so really the time complexity is going to be complexity is going to be big o of n times big o of n times 4 to the n and basically this is the 4 to the n and basically this is the worst case time complexity worst case time complexity okay so now let's get into the code okay so now let's get into the code which is going to be which is going to be fairly short so the first thing we want fairly short so the first thing we want to do is have a result to do is have a result this result is going to contain the this result is going to contain the combination strings that we're trying to combination strings that we're trying to build build and the next thing we want to do is and the next thing we want to do is create a map of digits right we want to create a map of digits right we want to take take every single input digit that could be every single input digit that could be possible like two and map it to the possible like two and map it to the characters characters that are possible so abc right for two that are possible so abc right for two and and unless you wanna see me type this out i unless you wanna see me type this out i think i'm just gonna copy and paste it think i'm just gonna copy and paste it so so this is what our digit map is going to this is what our digit map is going to be like and you can verify this if you be like and you can verify this if you have an old phone laying around that have an old phone laying around that this this is the correct mapping from digits to is the correct mapping from digits to the following the following uh string characters so now let's write uh string characters so now let's write that backtracking function that backtracking function it's going to be a recursive function it's going to be a recursive function and i'm going to and i'm going to declare this function inside of this declare this function inside of this function so that we don't need to pass function so that we don't need to pass in these parameters every time we call in these parameters every time we call this backtracking function this backtracking function and we also don't need to pass the and we also don't need to pass the digits that we're on i'm only going to digits that we're on i'm only going to pass in one variable i which is going to pass in one variable i which is going to tell us what index we're at in tell us what index we're at in the digit string that we're given as the the digit string that we're given as the input to our input to our function and i'm actually going to pass function and i'm actually going to pass in one more variable in one more variable so the current string meaning basically so the current string meaning basically the current string that we're building the current string that we're building so let's say our input was so let's say our input was uh one two three and the current string uh one two three and the current string would contain something like would contain something like a right so if we've we've only visited a right so if we've we've only visited one so far we'd have a one so far we'd have a and then we'd want the next two and then we'd want the next two characters from two and three characters from two and three so we know the base case is if i so we know the base case is if i is greater than or equal to the is greater than or equal to the length of digits or actually an even length of digits or actually an even better base case would be better base case would be our current string let's say the length our current string let's say the length of the current string of the current string is exactly equal to the length of digits is exactly equal to the length of digits that means that we've that means that we've basically been able to take every single basically been able to take every single digit and then map it to a character digit and then map it to a character because current string is going to because current string is going to contain those characters contain those characters and if that is the case then we are and if that is the case then we are allowed to take our result and add to it allowed to take our result and add to it the current string that we just the current string that we just built and then since this is the base built and then since this is the base case after that we can just return case after that we can just return if this is not true though that means we if this is not true though that means we haven't haven't finished building the current string finished building the current string that means we need to continue that means we need to continue going through the digit that we're at going through the digit that we're at right at index i right at index i so let's create a loop to do that so let's create a loop to do that so basically i'm going to take digits of so basically i'm going to take digits of i that's going to tell us the current i that's going to tell us the current digit that we're at right and i want to digit that we're at right and i want to take this digit that we're at and i want take this digit that we're at and i want to map it to the list to map it to the list of characters that it maps to right so of characters that it maps to right so if we had nine we know nine maps to if we had nine we know nine maps to w x y z so how can i do that well that's w x y z so how can i do that well that's why we created this why we created this digit to character map we can take a digit to character map we can take a digit digit and then map it to a character so digit and then map it to a character so digit to to character i'm going to take this digit character i'm going to take this digit and now basically this is going to be and now basically this is going to be the the that string that it maps to and i want that string that it maps to and i want to just go to just go through every character in this string through every character in this string so for every c every single character in so for every c every single character in this string this string i want to brute force this right so for i want to brute force this right so for every single character i'm just going to every single character i'm just going to call backtrack call backtrack i'm going to make that recursive call i'm going to make that recursive call right so right so for i we're going to increment i by 1 for i we're going to increment i by 1 because we're moving to the next digit because we're moving to the next digit and for the current string we're going and for the current string we're going to just take the current string that we to just take the current string that we were given were given and add one more character to it the and add one more character to it the character that we're currently visiting character that we're currently visiting c and that's actually all that we have c and that's actually all that we have to do to do we have our single base case and we have we have our single base case and we have our recursive case you can see that the our recursive case you can see that the only thing only thing that might be different for you is that that might be different for you is that our recursive call is inside of a loop our recursive call is inside of a loop so with this backtracking function so with this backtracking function complete complete now let's actually call this now let's actually call this backtracking function so backtracking function so we the parameters to give it are going we the parameters to give it are going to be 0 for the to be 0 for the index and the current string is index and the current string is initially just going to be empty right initially just going to be empty right but i'm actually going to need to make but i'm actually going to need to make one last modification so we're only one last modification so we're only going to need to call backtracking if going to need to call backtracking if the digit string that we're given the digit string that we're given is non-empty and the reason is because is non-empty and the reason is because if digits was if digits was empty then our recursive call would be empty then our recursive call would be called and then we'd execute the base called and then we'd execute the base case case once so then we'd end up returning this once so then we'd end up returning this as our result we'd add the empty string as our result we'd add the empty string to result to result but in the way this problem is defined but in the way this problem is defined if if digits if digits was empty like this if digits if digits was empty like this if digits was just an empty string the digits was just an empty string the output that they actually want is just output that they actually want is just an an empty array like this so that's why we empty array like this so that's why we have to have to put this inside of a condition but other put this inside of a condition but other than that all we have to do is now than that all we have to do is now return return our result and the function is complete our result and the function is complete so you can see that it's pretty so you can see that it's pretty efficient about as efficient as you can efficient about as efficient as you can make a problem like this even though make a problem like this even though it's a rel it's what's it called it's an it's a rel it's what's it called it's an exponential function right exponential function right but i hope that this was helpful if it but i hope that this was helpful if it was was please like and subscribe it supports please like and subscribe it supports the channel a lot and i'll hopefully the channel a lot and i'll hopefully see you pretty soon see you pretty soon you
2024-03-19 15:54:08
17
https://i.ytimg.com/vi/0…axresdefault.jpg
Letter Combinations of a Phone Number - Backtracking - Leetcode 17
CqvXdlUHAcg
uh so this question is find customers with positive Revenue this year so yeah with positive Revenue this year so yeah right right solution to report a right right solution to report a customer with positive Revenue in year 2021 um yeah this should be straight forward so we look for the year which is equal to 2021 and the revenue is greater than zero so um yeah select the what the custom ID right so a customer ID should be what should be distin already if not then I will just add distin later anyway I'm going to just start writing customer where the year equal to 2021 sorry and the what revenue is greater than zero so work yeah true so if you want to add a work yeah true so if you want to add a this thing just make sure you have the this thing just make sure you have the you know accurate number then you can you know accurate number then you can add it but I don't mind so this will add it but I don't mind so this will this will be a solution so if you have this will be a solution so if you have question a comment see you next time bye
2024-03-22 17:33:09
1,821
https://i.ytimg.com/vi/C…axresdefault.jpg
LeetCode 1821 | Find Customers With Positive Revenue this Year | SQL
XmYYl53nxuo
hi guys in this video i'm going to walk through this elite call number 2.95 find through this elite call number 2.95 find medium from data stream medium from data stream uh so this question was asked by uh uh so this question was asked by uh amazon amazon microsoft facebook apple big dance and microsoft facebook apple big dance and not other big names not other big names and obviously amazon loves this question and obviously amazon loves this question so this is a object origin design so this is a object origin design question question let's dive into the example in here let's dive into the example in here so uh we initiate the object by uh so uh we initiate the object by uh executing this comment uh mu finder so executing this comment uh mu finder so we call it this object we call it this object uh median finder uh median finder so it's a new object so we push in one so it's a new object so we push in one number pushing the second number so number pushing the second number so right now when we right now when we uh uh request request uh the median so there will be um the uh the median so there will be um the middle of this two number which is a one middle of this two number which is a one plus two which is two uh divided by two plus two which is two uh divided by two which is 1.5 which is 1.5 and then after that we push in another and then after that we push in another number now the medium will be the the number now the medium will be the the middle number which is two in this case middle number which is two in this case um so um so the concept is pretty straightforward the concept is pretty straightforward but uh the problem is how to do it fast but uh the problem is how to do it fast um um i will um also there is a follow-up i will um also there is a follow-up question that you can think about and i question that you can think about and i will will talk about talk about my solution this follow-up question at my solution this follow-up question at the end of the video so uh the question the end of the video so uh the question was was if all the integer number uh in a range if all the integer number uh in a range of from 0 and 100 inclusive how can we of from 0 and 100 inclusive how can we optimize the solution and the second optimize the solution and the second follow-up question was if 99 into the follow-up question was if 99 into the number number from the stream are in a range of from the stream are in a range of 0 and a hundred 0 and a hundred that means uh most of the numbers are that means uh most of the numbers are smaller smaller but there is some number that is outside but there is some number that is outside this range this range could be sorry it could be uh the the less the another one percent could be smaller than zero or larger than 100 so this is not necessarily a smaller side so it could be somewhere here or somewhere there so how can we optimize the solution so um so these are 34 follow-ups and we'll discuss later on so immediately one simple approach will be used in naive or is more like a brute force approach where we can have a list that comes with the object so and then when we add the number we just append the number to the list and then um whenever we need to find the medium we sort it and when we say the length is an even is an even number uh we just uh take the average between the the center true numbers okay that's in this case when we have two numbers in here we just take the average of two number yeah so because in this case the length yeah so because in this case the length is the even is the even length length and in the case where if the and in the case where if the length is odd length is odd and it's simple just pick the and it's simple just pick the middle number middle number so this approach is a brief force way to so this approach is a brief force way to do it and uh as obviously whenever we do it and uh as obviously whenever we execute this execute this function it's going to be taking we have function it's going to be taking we have to do sorting so it's going to be taking to do sorting so it's going to be taking a big o a big o we go for n we go for n as you can see it's not very efficient as you can see it's not very efficient because whenever we call it 5 million we because whenever we call it 5 million we have to we have to we sort it and sort it and sort it again so sort it and sort it and sort it again so all the prior information is not used all the prior information is not used so that's why i mean all the pipe so that's why i mean all the pipe information is not saved information is not saved so that's why it's not very efficient so that's why it's not very efficient a more efficient way to do it is i use a more efficient way to do it is i use two heaps two heaps and one is the max heap another one is a and one is the max heap another one is a mean heap mean heap so in python the implementation is so in python the implementation is always a mean hip that's why we have to always a mean hip that's why we have to be a little bit clever be a little bit clever uh to use a mean heap to implement a uh to use a mean heap to implement a maxip so let me show you how can i do maxip so let me show you how can i do that that so first we have the so first we have the uh two heaps in here so it looks like a uh two heaps in here so it looks like a list list in python in python so one is called smalls and then no so one is called smalls and then no one's equal large one's equal large so all the number so all the number in the lodge in the lodge must be greater than must be greater than or equal to can be equal to as well or equal to can be equal to as well smalls smalls and the rule is the smallest so how to and the rule is the smallest so how to reinforce that is that we have to make reinforce that is that we have to make sure sure the smallest number in largest the smallest number in largest must be greater than the biggest number must be greater than the biggest number in smalls so in smalls so so now the problem comes from how can we so now the problem comes from how can we efficiently find the smallest amount in efficiently find the smallest amount in large and also how can we find a small large and also how can we find a small uh uh the largest number in smalls the largest number in smalls right if this condition satisfied right if this condition satisfied this is automatically satisfied okay this is automatically satisfied okay and uh most efficient way to do it will and uh most efficient way to do it will be using heaps be using heaps so so uh to find a smaller summer in uh to find a smaller summer in an array or in a list an array or in a list so we can use a mean heap so we can use a mean heap so we can use so so we can use so large we can implement it with mean heap large we can implement it with mean heap and how can we efficiently find the and how can we efficiently find the largest number in largest number in any list will be any list will be use a use a max heap max heap that's why that's why uh we can implement a maxip to a small uh we can implement a maxip to a small so it's kind of not intuitive right so so it's kind of not intuitive right so we use a max heap we use a max heap to f to implement smalls and use a mean to f to implement smalls and use a mean heap to implement uh large heap to implement uh large so again the idea is we have to find the so again the idea is we have to find the largest number in smalls and also the largest number in smalls and also the smallest number in large smallest number in large and and to find the largest number is moss would to find the largest number is moss would be i use a max heaps be i use a max heaps and you have to find the minimum number and you have to find the minimum number in the large will be use the mean heap in the large will be use the mean heap also another condition we want to also another condition we want to enforce is to look at the size right enforce is to look at the size right because we look we are basically because we look we are basically breaking up all the numbers in two breaking up all the numbers in two sections one is the number on in the on sections one is the number on in the on the smaller side will be small and the the smaller side will be small and the larger size will be large larger size will be large and so we and we want these two pieces and so we and we want these two pieces to be uh more to be uh more um uniformly distributed the sizes um uniformly distributed the sizes cannot be different from each level so cannot be different from each level so largely largely um um because for example if we have five because for example if we have five numbers numbers one side must have two numbers another one side must have two numbers another side will be three numbers which is okay side will be three numbers which is okay this is only this is only the the the the size is only deferred by one size is only deferred by one but if we have four numbers uh we have but if we have four numbers uh we have must have like a two numbers on each must have like a two numbers on each side so that's the idea side so that's the idea um um so so as you can see the size can only be as you can see the size can only be different by plus or minus one different by plus or minus one so yeah this is the initial so yeah this is the initial implementation in the init function implementation in the init function so in the add number so in the add number section section uh how can we do is um uh how can we do is um so first we push so first we push uh use a heap uh use a heap and push it to uh self.smalls and then and push it to uh self.smalls and then we can but we can put push it to the we can but we can put push it to the self the largest as well but it's gonna self the largest as well but it's gonna be the same after you understand the be the same after you understand the rest um rest um so because the we again we implemented a a max heap a max ship to um too small that's why because in python it's always a mean if um by default so in order to use a massive you you have to cleverly uh take the negative the negative sign of the number to push it in because uh the smallest net the smallest negative number will be the largest number okay so that's the idea and here is the checking checking this condition right so if there's something if this smalls is not empty and large is not empty and we are grabbing the largest number in small and smallest number in large so and also this is a lot of a big time saver because when we look up uh the the largest number and also look up the smallest number it's only look that lock up is only take up a bit of one for heaps and this is the condition where we have to make some adjustments so if the minimum the smaller somewhere in the large and also but that's less than the maximum the hot the largest number the maximum number in the smalls and this is where we have to make some adjustments this this is violating this condition and we pop it off from the smalls because now uh the max number is too large now and uh because we the implement is a negative number so what we have to put it back to the positive side or yeah so we have to flip the sign so and we save it in the tam and then push it to the large section and by using push so this operation takes a bit of a lock and time and also this the hip-hop takes that much time absolutely the same amount of time for the t-push uh operation and then and now we are checking the length and because we have to make sure that there are these two ejection they are relatively the same size i mean can be only different by one at most so if um the length large um even minus one that's still bigger than the smalls and then we pop off the from the large part large section and then save the tam and then push to the smalls and again when we push it to small and because this is a max heap we have to put a negative sign in front of it change the design and push it and this one is the same uh time complexity a bit of lock n same for the push key push and uh on the flip side if the size is the smallest is bigger and we do the same thing but on in opposite way the entire add number um so for time the entire add number um so for time complexity uh we have to take a bit of complexity uh we have to take a bit of log in and we have to make some log in and we have to make some adjustment adjustment and in the worst case it's gonna be and in the worst case it's gonna be taking taking a bigger login a bit of login again pick a bigger login a bit of login again pick up login again and again and then again up login again and again and then again so five times right so um so five times right so um and the constants dropped so you see and the constants dropped so you see that the that the number is uh big of log n number is uh big of log n uh so this is add number and the five uh so this is add number and the five medium is gonna be a bigger one and this medium is gonna be a bigger one and this is a huge time saver is a huge time saver so we first we compare the length right so we first we compare the length right so so um in the first case where um in the first case where if the smalls has a bigger length if the smalls has a bigger length that means the that means the the medium will be in the small section the medium will be in the small section let's say let's say uh if we have we have total five numbers uh if we have we have total five numbers and the smallest we have the three and the smallest we have the three numbers numbers and and large is only two numbers and and large is only two numbers and and the medium is going to be in the in here so let's say uh if this section is the smallest and this section is large so the medium is going to be the uh the largest number in the smalls okay and this is exactly how we can we and on the flip side if the large is a and on the flip side if the large is a small number small number and that is going to be in the smallest and that is going to be in the smallest number in the large number in the large and also in the case waved at the same and also in the case waved at the same length just take the average between the length just take the average between the two two so let's submit that and it works and now we can talk about some uh a little bit about the follow up so if all integer numbers from the stream are between are strictly between 0 and 100 so how can we optimize it and actually uh there's a clever way to do it so we can have an integer array of 100 so basically it's storing the count of each number uh with a total count so basically we the we have a list looks like this so we have a hundred spot so the first the first part is counting uh counting uh what is what's the frequency for the number zero the second spot is currently counting um the frequency of number one right so go all the way to 100 or 99 and then after we have the count or we have the distribution of all the frequency and we can uh this is a direct lock up to the to the medium so the time and space complexity is the bigger one and um so phi medium is big 01 as i mentioned so also the ad num it's going to be bigger one as well because we know exactly what index we we want to add to the frequency distribution so um so so this is how we optimize it and the second follow-up question was if 99 of all integer number from the stream are between 0 and 1 how can we optimize it and uh when uh 99 percent between 0 to 100 we we know for sure that the medium is going to uh in this 99 percent right because the medium is basically a fifty percent uh fiftieth percentile so we can keep a counter for less than a and yeah so we only need to know how and yeah so we only need to know how many numbers greater than 100 and then many numbers greater than 100 and then we um yeah so let's say if there is 10 number it's just greater than 10 greater than 100 a thousand number will be less than 100 a thousand number will be less than 100 because that because that that uh that uh ten number accounts for one percent ten number accounts for one percent and then often we know that a thousand and then often we know that a thousand number is less than less than 100 and number is less than less than 100 and then we can just find the medium that then we can just find the medium that way way and we can basically follow this up of and we can basically follow this up of approach again approach again we need to have a uh in a list or an we need to have a uh in a list or an array so keep track of the frequency of array so keep track of the frequency of the numbers this is below the numbers this is below below 100. below 100. so this is how we can optimize it if we so this is how we can optimize it if we are given these two pieces of are given these two pieces of information information um yeah so this is my solution this this um yeah so this is my solution this this problem problem i hope this is helpful if he does i hope this is helpful if he does please like and subscribe that would be please like and subscribe that would be a huge support a huge support thank you so much thank you so much thank you so much for watching i will thank you so much for watching i will see you in the next video
2024-03-22 14:30:25
295
https://i.ytimg.com/vi/X…axresdefault.jpg
Leetcode 295. Find Median from Data Stream
yLenwOcoTR0
hello everyone so how are you all so I am Aditya and I'm again with a new am Aditya and I'm again with a new question on lead code question on lead code today we will be solving the search in today we will be solving the search in rotated sorted array rotated sorted array so now let's read out the problem first so and we are given there is an integer and we are given there is an integer array nums okay we have been given an array nums okay we have been given an integer array integer array okay its name is nums okay its name is nums okay sorted in non-decreasing order okay sorted in non-decreasing order means increasing order okay this array has been suited in an increasing order 2 5 6 and Etc okay 2 5 6 and Etc okay so these are all in the increasing order so these are all in the increasing order now before being passed to your function now before being passed to your function nouns is rotated at an unknown pivot nouns is rotated at an unknown pivot Points k Points k welcome suppose let's Imagine This welcome suppose let's Imagine This this area has been pivoted to some point this area has been pivoted to some point k k and the value of K would be zero and the value of K would be zero okay okay so for example see it here in this so for example see it here in this example we have been given an array example we have been given an array let me clear this okay let me clear this okay so 2 5 6 2 5 6 double zero double zero one two okay one two okay so here so here we can consider the Pivot Point here or we can consider the Pivot Point here or we can consider the Pivot Point here we can consider the Pivot Point here earlier there was a similar question earlier there was a similar question search in rotated sorted array but in search in rotated sorted array but in that case there is only one Pivot Point that case there is only one Pivot Point means means we can have only one Pivot Point we can have only one Pivot Point but here we can see that there is but here we can see that there is repeated by what point means the Pivot repeated by what point means the Pivot Point can be repeated Point can be repeated and it can be more than one and it can be more than one okay so this is a problem okay so this is a problem now now what's the question says after that now resulting array is nums K nums K plus 1 will understand this later now we see that for example zero one two triple four five double six seven might be rotated at pivoted Point index 5. we have been given taking this array we have been given taking this array okay the element 2 4 6 8 10 okay the element 2 4 6 8 10 okay three four five six seven eight and ten three four five six seven eight and ten we have taken zero one two equal four we have taken zero one two equal four five double six and seven so this is the five double six and seven so this is the first area that we are given first area that we are given and it says that it might be rotated at and it says that it might be rotated at pi over 0.5 pi over 0.5 so what is the PowerPoint five zero one so what is the PowerPoint five zero one two three four and five so this is the two three four and five so this is the private point we have got private point we have got so it becomes this so it becomes this okay if I make it a pivot point so what okay if I make it a pivot point so what does it become does it become let us see that only so it becomes 4 5 6 7. 0 1 2 4 and 4 means we have to start from here we are starting from here because this is a pivot point we have been given so we have to start from here and thereafter these all elements will be written in the form okay so you must get a clear cut idea that how to solve this problem now let's move on to the next thing this is our question and come up on the example first this is the example in the array has been given nums and Target zero we have to find out whether 0 is present or not yes it is present so this is there is basically a two method two methods from which you can apply and binary searching look I am giving you a binary searching look I am giving you a hint then whenever you see these hint then whenever you see these constants like okay constants like okay whenever you see the constants are given whenever you see the constants are given you can imagine that to solve the you can imagine that to solve the quotient with the help of binary quotient with the help of binary searching okay when it has been given in searching okay when it has been given in the 10 to the power the 10 to the power in binary searching the time complexity in binary searching the time complexity will be will be we go of log n we go of log n in most of the cases it's we go of login in most of the cases it's we go of login and the other thing is that linear you can apply linear searching the linear searching the time complexity would be because when you can solve this question with the help of these two methods but binary searching is the most preferred and in the binary searching you must be knowing that concept what was the concept in the binary searching we have an array we are finding its mid position okay if mid position is greater than the first position okay if mid is greater than the previous position so what we do we just suppose this is the right thing we move this right to Mid minus 1. understood as what we do is here is the left we will increment left so this is the basic concept let's code right now let us move on the code section okay so here we are required to solve this question we have been given these things already we have seen it look there is a catch what's the catch there is a similar problem to Source rotated sorted array but nums may contain duplicates would this affect the runtime complexity how and why this is the catch then um how we are solving it from and how it is different from the previous question so first let us code thereafter we will so let's code one by one so the first so let's code one by one so the first thing I will explain from The Starting thing I will explain from The Starting Line only this is the class solution Line only this is the class solution means we are defining a class for the solution okay and this is the access modifier water access modifier suppose if you water access modifier suppose if you want to declare something according to want to declare something according to you for example if you don't want to you for example if you don't want to show the users what constants you have show the users what constants you have declared about variables you have declared about variables you have declared so you can make it private or declared so you can make it private or protected okay but you want you want to protected okay but you want you want to make it visible to the users so you can make it visible to the users so you can make it public so the third thing is make it public so the third thing is that I am taking a that I am taking a I am taking a variable a function I am taking a variable a function function variable of type Boolean okay function variable of type Boolean okay and for what we have an array nums and and for what we have an array nums and we are passing its address not I'm not we are passing its address not I'm not directly writing the nums I am passing directly writing the nums I am passing its address for the dynamic allocation its address for the dynamic allocation in the Heap in the Heap this is the basic concept that you have this is the basic concept that you have to get to get okay why you have to use the reference okay why you have to use the reference because I have to take the array because I have to take the array dynamically in the field and the second dynamically in the field and the second thing is that we have been given an thing is that we have been given an integer Target integer Target now the next line will be okay let me remove this what I am doing here I'm using the what I am doing here I'm using the concept of linear searching then you're searching with time we go off and we go off and okay so here let's see I have declared a okay so here let's see I have declared a variable I okay I have declared a variable I okay I have declared a variable I and variable I and thereafter I have run and loop for I is thereafter I have run and loop for I is equal to 0 I less than nums dot size I equal to 0 I less than nums dot size I plus plus plus plus and I have run a loop and I have run a loop from 0 to nums.sidance array size okay from 0 to nums.sidance array size okay thereafter I am checking the condition thereafter I am checking the condition if nums of I is equal to equal to Target if nums of I is equal to equal to Target what does it mean what does it mean if if for example I am running a loop from for example I am running a loop from here okay and I'm running from element here okay and I'm running from element to element and if I suppose if I get the to element and if I suppose if I get the target element suppose I am finding 0 target element suppose I am finding 0 and ones are iterating and ones are iterating these array elements I got zero I got 0 these array elements I got zero I got 0 I will return true I will return true else what I will do I will return first else what I will do I will return first that I have got no value equal to Target that I have got no value equal to Target suppose I am finding 3 here in this suppose I am finding 3 here in this array so once on iterating each and array so once on iterating each and every element I did not get three so I every element I did not get three so I will just return first will just return first okay so this is the linear searching okay so this is the linear searching method which is very simple but the main method which is very simple but the main catch is that I don't want this time catch is that I don't want this time complexity complexity I don't I don't want want I want to better optimize code so let's I want to better optimize code so let's run this first okay so accepted also so no problem is let us submit after this uh okay submitted also so now I am going to write a binary search code so the first thing that so the first thing that I will declare a variable I I will declare a variable I not I let us left left is equal to 0 not I let us left left is equal to 0 I will declare another I will declare another write is equal to write is equal to none start size minus 1 none start size minus 1 understood understood now what I will do now what I will do I will check while I will check while left is less than equal to right what I left is less than equal to right what I will do will do I will just I will just find the mid mid would be left Plus right minus left upon 2. and now I will check if I will check if nums of mid is equal to is equal to the Target then what I will do oh oh okay if I got nums of mid is equal to okay if I got nums of mid is equal to Target I will return true yes I founded Target I will return true yes I founded it it okay okay let's take elsef okay let's take elsef as if as if I got nums of left nums of made nums of made and and nums of right nums of right is equal to is equal to numbers of mid is equal to is equal to numbers of mid this is the important catch here please this is the important catch here please check it out I am telling this I am check it out I am telling this I am checking this condition y because I may checking this condition y because I may have a repeated character have a repeated character as we have seen that there is a pivot as we have seen that there is a pivot point and there could be a repeated point and there could be a repeated character here okay there may be a character here okay there may be a repeated repeated character in triple repeated repeated character in triple four so it might be a case that in the four so it might be a case that in the left digit is equal to the mid digit and left digit is equal to the mid digit and the right digit also the right digit also okay okay so we have checked this condition so we have checked this condition let us remove else part here it was a let us remove else part here it was a mistake mistake and in this part why what will I do just remove it I will decrement the r firstly I will increment the left left plus plus and right minus minus okay now what will I do else if nums of with nums of I with nums of I not I itself not I itself it's left okay it's left okay is less than equal to is less than equal to nums of mid nums of mid in this condition in this condition I will check one another thing what's I will check one another thing what's another thing that if Norms of left is less than equal to Target and The Arrogant is less than what okay okay so in this case so in this case what would be returning okay in this case uh don't return anything you just make the right is equal to in the else part what I will do left is in the else part what I will do left is equal to Mid plus one equal to Mid plus one understood this concept I have already understood this concept I have already discussed it okay thereafter else in the else case if checking the another condition is less than is less than Target and end Target and end Target is Target is less than equal to less than equal to nums of right nums of right I will visualize everything don't worry I will visualize everything don't worry in this condition in this condition just make left is equal to left is equal to met plus one met plus one and the else case right is equal to and the else case right is equal to minus 1 minus 1 okay and here just return okay and here just return false false in the else case let's run this in the else case let's run this we will definitely get error I know we will definitely get error I know so made okay I haven't so made okay I haven't declared it the data type declared it the data type now run it okay very nice we have our question has wrong answer okay so test case not fast wrong answer okay so test case not fast what is the what is the let me see the question once again the let me see the question once again the code once again next one once again next one once again it's kind of mistake okay now again we have to find the article the variable return the size right right what have I done declared Madness equal to Target return to if now I'm suffering equal to remote left S Plus right minus minus okay at last year we have three open curly braces let's remember that one here okay it has been closed there after this has been closed the code is why it avoids okay so I think uh we have to remove okay so I think uh we have to remove this this move this thing move this thing and just write elsewhere okay so our question has been accepted done so this is the binary searching we have founded the mid check if mid is equal to is equal to Target element we have returned true else if what I am checking if num if nums of left is equal to Mid and lumps of right is equal to mince means all the values in the left in the right and in the middle is same so what will I do I will just increment the left and decrement the right by one okay else if if mid is greater than left number if mid is greater than left number and Target is greater than left and Target is less than mid okay so Target element may be in the middle of the left and the middle so what I am doing I am just decrementing right to the mid minus one else and incrementing left to Mid plus one and just opposite thing I am doing in this slope as I have returned first at the last stage so this was the question please leave any comment if you
2024-03-20 12:18:15
81
https://i.ytimg.com/vi/y…axresdefault.jpg
81. Search in Rotated Sorted Array II | Leetcode | #array | CODEPECT
5rcqRnYOwTM
problem 962 the columns to make sorted3 okay so let's go through the problem okay so let's go through the problem description first we are given an array description first we are given an array a of n lowercase letter strings all of a of n lowercase letter strings all of the same length now we may choose any the same length now we may choose any set of deletion indices and for each set of deletion indices and for each string we delete all the characters in string we delete all the characters in those indices so for example if we have those indices so for example if we have an array a which is made up of these two an array a which is made up of these two strings and the deletion indices are 0 1 strings and the deletion indices are 0 1 & 4 then we basically delete the & 4 then we basically delete the characters at these 3 indices in every characters at these 3 indices in every single string in the array okay and the single string in the array okay and the final array has every element in that final array has every element in that graphic order graphic order so basically problem says that we want so basically problem says that we want to delete characters so I if we to delete characters so I if we visualize this array as a matrix so like visualize this array as a matrix so like there each string each individual string there each string each individual string is a row of the matrix then we can is a row of the matrix then we can actually visualize columns which can be actually visualize columns which can be deleted from this matrix so what the deleted from this matrix so what the problem says is that you can actually problem says is that you can actually select column indices that you are going select column indices that you are going to delete such that every row is gonna to delete such that every row is gonna be sorted in the end after you're done be sorted in the end after you're done deleting these indices so yeah so that's deleting these indices so yeah so that's what the problem says so they also have what the problem says so they also have so okay for clarity is you know isn't so okay for clarity is you know isn't that so graphic order if this okay yeah that so graphic order if this okay yeah so like the equals are also graphically so like the equals are also graphically it's possible so like you can have a it's possible so like you can have a string like a BB and this would be string like a BB and this would be considered lexicographically sorted and considered lexicographically sorted and if you returned minimum value of TR if you returned minimum value of TR length or we have to return the minimum length or we have to return the minimum number of deletions for which this is number of deletions for which this is possible okay so I think the problem possible okay so I think the problem statement is clear the problem statement is clear the problem immediately it's not very clear how to immediately it's not very clear how to approach this but I insist on actually approach this but I insist on actually breaking the problem down so the best breaking the problem down so the best way of breaking this problem down is to way of breaking this problem down is to think in terms of one string so like think in terms of one string so like forget about this other one let's say forget about this other one let's say that butan they had this one string so that butan they had this one string so if we add if we add sponsoring and we will allow to delete sponsoring and we will allow to delete some characters and we had to make the some characters and we had to make the strings such that the remaining strings such that the remaining characters are in that so graphic order characters are in that so graphic order how would you go out in that how would you go out in that so like one approach that comes to my so like one approach that comes to my mind is that so you run a loop on this mind is that so you run a loop on this ring you go through every character so ring you go through every character so let's say that you approach this see in let's say that you approach this see in your loop your loop I would then check all the characters I would then check all the characters before see considering each one to be before see considering each one to be the last character before see so for the last character before see so for example let's say that I read at a so example let's say that I read at a so like I'm considered in my outer loop I'm like I'm considered in my outer loop I'm considering see I go back I am now at a considering see I go back I am now at a I would assume that all the characters I would assume that all the characters between a and C have been do so you can between a and C have been do so you can easily come to indices of CNA you can easily come to indices of CNA you can easily compute the number of characters easily compute the number of characters that have been deleted and then all you that have been deleted and then all you have to do is actually make this string have to do is actually make this string sorted so like this immediately like sorted so like this immediately like rings dynamic programming in my mind so rings dynamic programming in my mind so so like even like okay so that's let's so like even like okay so that's let's go to enemy programming once we have go to enemy programming once we have settled on our recursive solution so for settled on our recursive solution so for every character all you have to do is go every character all you have to do is go back each character that comes before it back each character that comes before it and consider it as the last character and consider it as the last character before it so like deleting all the before it so like deleting all the essentially deleting all the characters essentially deleting all the characters between the character under between the character under consideration and the character that we consideration and the character that we got from going back so I think that got from going back so I think that should be easy enough to do but then now should be easy enough to do but then now we have to scale the solution to we have to scale the solution to multiple rows but that isn't a problem multiple rows but that isn't a problem right because I think the constraint so right because I think the constraint so you're looking you can look at the you're looking you can look at the constraints they're not very strong so constraints they're not very strong so what we can do is that we can actually what we can do is that we can actually select this problem has two sort of select this problem has two sort of logics right so when you go back and logics right so when you go back and let's say that for this see if you or let's say that for this see if you or rather let's say for this a when you go rather let's say for this a when you go back and find this B there is no back and find this B there is no possible scenario in which this would possible scenario in which this would give a lexicographically sorted string give a lexicographically sorted string right so the answer will be minus one right so the answer will be minus one now this check or rather like this check now this check or rather like this check whether or not this configuration is whether or not this configuration is possible right now we could just do it possible right now we could just do it in one line because it was one string in one line because it was one string but now let's say we have n strings so but now let's say we have n strings so we can write a separate check function we can write a separate check function which or what it will do is it will go which or what it will do is it will go row by row and it will compare the row by row and it will compare the columns that you give it and it's going columns that you give it and it's going to make sure that you are actually able to make sure that you are actually able to use this configuration or every let's to use this configuration or every let's say like if I call the character at say like if I call the character at index A to B I and the character at index A to B I and the character at index then index before it to be J and index then index before it to be J and basically it will go through every row basically it will go through every row and check that the character IJ is less and check that the character IJ is less than character at I or or equal because than character at I or or equal because if it's greater then it's not possible if it's greater then it's not possible so they give in any one of the strings so they give in any one of the strings it's greater we actually can't use this it's greater we actually can't use this configuration so this won't be a part of configuration so this won't be a part of subproblems that actually make up the subproblems that actually make up the solution for for that particular I so I solution for for that particular I so I hope that makes the problem clear enough hope that makes the problem clear enough gain more clarity once I start coding so gain more clarity once I start coding so let's get to coding let's get to coding you first things first if a relent is zero we return zero fig is nothing to delete then we declare our DPA and after realizing that we'll need the length of the strings repeatedly we assign that to a variable n the length of the DP array and then just beyond under the loops you want to iterate over our elements left to right starting at index one in the RFP the interview goes from I minus 1 to 0 we also want to initialize the DPL do at index I with I because in the worst case we may end up deleting all the nicest before I so the DB value can be more now we check if it's possible to make a now we check if it's possible to make a solution which chairs the preceding solution which chairs the preceding column 2 I we update our DB values if I column 2 I we update our DB values if I minus J plus 1 plus T PJ is actually minus J plus 1 plus T PJ is actually lower than the current value here I lower than the current value here I minus J plus 1 are the number of minus J plus 1 are the number of deletions between I and J while TP j is deletions between I and J while TP j is the minimum cost to make the string the minimum cost to make the string sorted from 0 to J now we can compute sorted from 0 to J now we can compute the answer by simply iterating over our the answer by simply iterating over our DP array and considering I as our last DP array and considering I as our last element the total cost is then the DP element the total cost is then the DP value at I plus the length of the rest value at I plus the length of the rest of the string which we would have to of the string which we would have to delete to make I the last column finally delete to make I the last column finally check function all we need to do is to check function all we need to do is to go through every string and compare the go through every string and compare the characters at I and J we return false if characters at I and J we return false if the character at J is greater than the the character at J is greater than the character at i for any of the strings character at i for any of the strings you can return true otherwise and there you have it folks 96% optimality that's it for this one please trouble like if you like this dislike if you disliked this and as always subscribe for more thank you bye bye
2024-03-25 12:20:48
960
https://i.ytimg.com/vi/5…axresdefault.jpg
Leetcode 960. Delete Columns to make sorted III
5J7YDbUqXoc
well I leave code every day never take no I leave code every day never take no Hiatus this is number of sets of K Hiatus this is number of sets of K non-overlapping line segments non-overlapping line segments okay let's go ahead and get right into okay let's go ahead and get right into this problem this problem so so given endpoints given endpoints on a 1D plane on a 1D plane where the ith point where the ith point from 0 to n minus 1 from 0 to n minus 1 is at k x equals I find the number of is at k x equals I find the number of ways we can draw exactly K ways we can draw exactly K non-overlapping line segments such that non-overlapping line segments such that each segment covers two or more points each segment covers two or more points the endpoints of each segment must have the endpoints of each segment must have integral coordinates okay so you have to integral coordinates okay so you have to place place lines at lines at integer points right you can't place a integer points right you can't place a line at 2.5 and 3.5 right it has to be line at 2.5 and 3.5 right it has to be on two or three right it has to be the on two or three right it has to be the ends of the line have to be placed on ends of the line have to be placed on integer points integer points the K line segments do not have to cover the K line segments do not have to cover all endpoints okay so there can be gaps all endpoints okay so there can be gaps in the space that you fill in the space that you fill and they are allowed to share endpoints and they are allowed to share endpoints right so if you had one line that went right so if you had one line that went from two to three you could have another from two to three you could have another line that went from three to four so line that went from three to four so they can share endpoints but they can't they can share endpoints but they can't overlap right you can't have a line from overlap right you can't have a line from two to four and three to five right two to four and three to five right because there would be overlap there but because there would be overlap there but you could have two to three and three to you could have two to three and three to four if they share an endpoint that four if they share an endpoint that doesn't mean they overlap doesn't mean they overlap yeah return the number of ways we can yeah return the number of ways we can draw K non-overlapping line segments and draw K non-overlapping line segments and since this number can be huge since this number can be huge we're going to return it modulo 10 to we're going to return it modulo 10 to the 9 plus 7. the 9 plus 7. okay so a little confusing okay so a little confusing if we looked at this example here and if we looked at this example here and then then so we have four so we have four points I guess you could call it four points I guess you could call it four points in the system uh what just points in the system uh what just happened happened okay we have four points in our system okay we have four points in our system so I'm going to draw that system like so I'm going to draw that system like this this so you could draw a line so you could draw a line to to three three and four so this is our one dimensional and four so this is our one dimensional plane where we can put plane where we can put our strings or we call them strings here our strings or we call them strings here segments all right I might use the term segments all right I might use the term strings interchangeably right but you strings interchangeably right but you have these line segments well have these line segments well if the dimension is four well I could if the dimension is four well I could put a line here put a line here that's one way I could do it I have to put k equals two lines right I have to put k equals two lines right because we have k equals two so I could because we have k equals two so I could put a line here and a line here put a line here and a line here that's one way I could do it that's one way I could do it I could put a line of this link here I could put a line of this link here and then another line of this of length and then another line of this of length one here one here I could do the opposite I could do the opposite right I could put a line oh no I couldn't do that what else could I do there's five ways of doing this okay I could put and finally I could put a line here and finally I could put a line here and here and here right so these are all five numerable right so these are all five numerable ways right so this is two lines right so ways right so this is two lines right so there's a line here segment and another there's a line here segment and another line segment here two line segments on line segment here two line segments on their own note that you know there can their own note that you know there can be a gap we don't have to cover the be a gap we don't have to cover the whole Space just for this size four whole Space just for this size four space these are all you know this space these are all you know this enumerates all possible enumerates all possible possible placements okay so how do you approach this problem I guess what led me to the solution I guess what led me to the solution first was thinking about first was thinking about in this line segment system right in this line segment system right I can place if I have two lines I need to place right I can place the first line like this and then for the remainder of the system I have to put one line here I could place the line like this and then for the remainder of the system or I could place the line like this or I could place the line like this and then for the remainder of the system and then for the remainder of the system I'd have one line here I'd have one line here so what I'm basically saying is like so what I'm basically saying is like for any system right if this thing is for any system right if this thing is length n so let's draw it out so we have this space right just in a general case what I'm which is length n and I have to place K lines so I have to place K lines in this n space well what are my options well I could put a line of length one here which means that I'm going to have to place K minus one lines here in this Dimension here there's something wrong with my iPad charge unfortunately right and I guess even more generally I have to do K minus one one lines here using what using n minus one space why well because I create a line that's length one here so then I I have K minus one lines remaining and I have to use n minus one space to do it put a line of length two put a line of length two but that means now that I need to put K but that means now that I need to put K minus one lines using minus one lines using n minus 2 space n minus 2 space or I could do something of length three but that would mean that I'd have to place K minus one lines using n minus three space and I can keep going down until I get to the very end using all end space and not have to place K minus one lines using n minus n space so I can for any point I can draw a line like for any close four here and I could draw a line that covers almost all the space you know I can draw a line that covers all the space I can call a draw line that covers this much and this much so and then I would just have to fulfill the remainder of the solutions for what's left over okay which makes sense right because I can place a line and then since I placed that line I now have K minus one lines I still have to consider and then for those K minus one lines I have n minus the size of the line that I've decided to use left to fill that space um now there's one more thing I can do um now there's one more thing I can do right I don't actually have to fill up right I don't actually have to fill up all the space so what I can also do is all the space so what I can also do is not fill up the space at all not fill up the space at all and fill up K lines and fill up K lines using using n minus one space n minus one space right so either I use a line so I have K right so either I use a line so I have K minus 1 lines left and since this line minus 1 lines left and since this line has length one I have n minus one space has length one I have n minus one space left to fill it up I could use a line left to fill it up I could use a line that's length two so I have K minus one that's length two so I have K minus one lines left that I have to place using n lines left that I have to place using n minus two space n minus three minus four minus two space n minus three minus four all the way up to n all the way up to n or I can decide that I don't want to put or I can decide that I don't want to put a line here and I can just use K lines a line here and I can just use K lines to fill up n minus one space and that to fill up n minus one space and that will you know create the will you know create the the space you see in this example right the space you see in this example right like in the beginning I can do a line of like in the beginning I can do a line of length one length one and then these are the ways that I can and then these are the ways that I can do a lot do a lot where I use one line here in this system or I can decide to skip this space and not use it at all and distribute my K minus my K lines with n my in N minus one space right because here n equals four so I'm Distributing all my two lines in n equals four but I can decide I won't use this space so how many ways can I distribute a line in and minus one space how many ways can I distribute two lines k equals two lines and N minus one space hopefully that makes sense so that's the idea here so how do we generalize this idea well let's just say that I have this dynamic programming array n right and I say how many ways can I using K lines let's actually make this a different color make it red can I distribute those lines into n can I distribute those lines into n space space well I can well I can I can distribute the line of length one I can distribute the line of length one right so I can use this line here right so I can use this line here right I can distribute this line here right I can distribute this line here which basically means well I'm going to which basically means well I'm going to create a line of length one which will create a line of length one which will remove one spot one space from the total remove one spot one space from the total space right because when I use this one space right because when I use this one space I've allocated it so I have n space I've allocated it so I have n minus one space available left and since minus one space available left and since I've used the line well I can use D of K I've used the line well I can use D of K minus one because I've used a line minus one because I've used a line and that line uses space and that line uses space one so I have n minus 1 space left one so I have n minus 1 space left plus well I could use a line of length plus well I could use a line of length two and I get n minus 2 space left plus d of K minus three so I can use a line of no matter what I'm using only one line no matter what I'm using only one line and that I could use a line that has and that I could use a line that has length two length two I'm using one line I'm using one line and that line has length three all the way up to what well I can't use a line that exceeds the space that I have so the maximum line I could use in this example would be DK minus one n minus n right so these are the links of all the lines I can use so I'm basically saying if I have K lines well I could distribute one line and I can make that line length one I can distribute one line make that line link two I distribute a line make that line link three all the way up to n right because the line can't exceed the size of the space that I'm using and that will give me the total number of ways that I can distribute this system right because what's basically happening is is I distribute a line of length one and then my question just becomes well if I distribute a line of length one how many ways can I distribute a line of a lines how many ways can that should be K minus one lines with n min n minus one space so that's basically the idea here so if I distribute a line of link two well I can do that and then I would just have to figure out how many ways can I distribute K minus one lines using n minus two space since I've just used two space here right now we just saw that recurrence relationship for this problem as well um this is more stated in our tabular recurrence relationship you could use mobilization for this as well right which might be a little bit simpler but as we go through this problem further we'll figure out that there's a optimization to make this even more efficient okay so that's all the ways that I could distribute a line right these are all the ways that I could distribute one line and these are all the links that I could use okay now the final way I can do it that's not articulated here is I can also decide that I don't want to use so this is kind of like the outlier so this is kind of like the outlier right this is basically saying right this is basically saying okay I'll just distribute okay I'll just distribute okay I'll use K lines and N minus one okay I'll use K lines and N minus one space I won't use the space for anything space I won't use the space for anything I'll leave this space empty so the I'll leave this space empty so the number of ways that I can distribute K number of ways that I can distribute K lines covering n space lines covering n space is the same as the number of ways that I is the same as the number of ways that I can distribute K minus one lines to M can distribute K minus one lines to M minus one space if I decide to use a minus one space if I decide to use a line of length one I can use the link line of length one I can use the link line of link two link three all the way line of link two link three all the way up to n or I can decide to not use this up to n or I can decide to not use this space so I can also add in the number of space so I can also add in the number of ways that I can distribute K lines to n ways that I can distribute K lines to n minus one space minus one space okay now if you want to use a little bit okay now if you want to use a little bit of a mathematical notation to kind of of a mathematical notation to kind of simplify the way that this works a simplify the way that this works a little bit we can call this the sum from I equals 1 to n of d k minus one n minus I right so that addresses this sum here because the sum has a very natural progression Plus so this is one term on its own of n minus 1. so this basically saying of n minus 1. so this basically saying is all the ways that I can distribute is all the ways that I can distribute one line and its length plus not one line and its length plus not Distributing a line at all Distributing a line at all and just not using this space so where do we go from here well so where do we go from here well we can just do we can just do a a for Loop right a nested for Loop if for Loop right a nested for Loop if we've gone from for I in range for J for J in range in range Okay so Okay so we could populate this system I we could populate this system I or I guess j i or I guess j i equals the sum of equals the sum of I prime equals one I guess we could call I prime equals one I guess we could call I prime that's fine I prime that's fine I prime equals one up to I up to I d k minus DJ minus one d k minus DJ minus one d i minus I prime plus d j D of I minus 1. so we could run this whole thing right this this this formula here sorry if the notation is incorrect or sloppy the but the general idea is right we're gonna have to look at o of N Things here o of K thinks here and then here we have to do o of K well it's actually up to I so o of n operations right so for each o of n so for each n we have to do K things and for each K things we have to do n things so that means we have to do Big O of n times K times n or Big O of N squared k now this might be good enough but n is less than or equal to a thousand so a thousand is 10 cubed so that'd be 10 cubed times 10 cubed times 10 cubed 10 to the nine so that's going to give us a time limit exceeded um issue so this is still to um this is still too slow right barely but it is still the case that this is too slow of a process for our purposes so I guess the one thing we can do to fix this problem to make it just a little bit more efficient so that we don't need to do o of n times K times n operations right is work with the math directly and think work with the math directly and think about how we can make uh this just a about how we can make uh this just a little bit more efficient little bit more efficient okay well okay well foreign right meaning you know when we calculate this this is constant time right but this this right now is taking o of n time to operate so since it's taking all of that time it's causing that additional n factor in making our solution 10 to the 9th if we made this constant then it would be o of one so if we just kept track of this sum somehow kept track of this sum somehow um um recompute this over and over again what recompute this over and over again what if we had like a prefix some idea what if we had like a prefix some idea what if we had this information catched or if we had this information catched or saved somehow that way when we calculate saved somehow that way when we calculate this this information is constant well this this information is constant well let's just call let's call D of of k n 1 to n d of K n minus I n minus I so that would mean if we substituted so that would mean if we substituted that in here that in here D of k n D of k n so I'm just trying to do some direct so I'm just trying to do some direct substitution here substitution here would be D of K minus one would be D of K minus one all the way up to n Plus Plus D of K D of K n minus 1. n minus 1. so then you might be just saying right so then you might be just saying right now okay well that's just a foolish now okay well that's just a foolish substitution who cares right substitution who cares right um um I guess the idea here is then I guess the idea here is then we could update we could update this system this system we could update d k of n we could update d k of n by saying DK of n D of K minus one because what is DK of n because what is DK of n in terms of DK of n minus one all the way up to n so if it's all the way up to n then the recurrence relationship here would be sorry this is a very confusing problem and I'm not articulating what's going on okay because I guess the idea is here because what is DK of n minus one well d k of n minus what's this here just to prove it to you why I wrote right it equals that right it equals that let's make it blue let's make it blue and we're adding in and we're adding in DK well it's DK n minus I d k of N and since it's n minus one this so then we're just adding in this final so then we're just adding in this final term right this is just this is just the last term of this sum this equals I equals 1 to n d k of n or because this will be the final term of the sum if you just went one past what it was before very mathematically intensive problem very mathematically intensive problem here here so with all that said in order to solve so with all that said in order to solve this problem this problem if we just keep track of this sum using if we just keep track of this sum using this system then we only actually need this system then we only actually need to solve to solve these two problems these two problems and this can be solved in constant time and this can be solved in constant time and this can be solved in constant time and this can be solved in constant time and at the end you just return uh and at the end you just return uh the final value of this system the final value of this system hopefully that makes a little bit of hopefully that makes a little bit of sense I sense I this is my own unique solution and I this is my own unique solution and I didn't see anyone else do this so it's a didn't see anyone else do this so it's a little weird little weird but that would basically make but that would basically make you know now solving for any of these is you know now solving for any of these is constant right this is constant this is constant right this is constant this is a constant thing we catch is the a constant thing we catch is the constant thing we catch constant thing constant thing we catch constant thing we catch constantly we catch constantly we catch constantly we catch constantly cash so for k n values so in Big O of NK cash so for k n values so in Big O of NK time we do constant things so it's MK time we do constant things so it's MK time um in any space right d of in any space right d of I guess D of 0 because for any K value if you have how because for any K value if you have how many ways can you distribute nothing to many ways can you distribute nothing to any space one one way doing nothing any space one one way doing nothing right so that's basically what this is right so that's basically what this is saying here for any n value is one okay so let's go ahead and just walk through this recurrence relationship and see if okay so we have Big D and we have Little okay so we have Big D and we have Little D so we'll do one Plus zero times zero times n n for for blank in range blank in range okay okay and then now let's just run through this recurrence relationship so we'll go through n through k we don't need to look at n equals zero we don't need to look at n equals zero for k k and range we'll just update using this recurrence we'll just update using this recurrence relationship and not think about it too relationship and not think about it too much so D of k n much so D of k n equals DK minus one n plus d k n minus equals DK minus one n plus d k n minus one one okay so little d k n okay so little d k n equals equals D of K minus 1 D of K minus 1 and and plus d of K let's um okay so this is DKK and the KK and then E K K and N and then Big D of KK and it updated is just taking the previous operations value adding in current one and then at the end you just return D of negative one because this will give you right negative one negative one would be dkn which would give you the number of ways that you can sum up man that'll be K because it's K plus one all right this is link K plus one let's see if this broke my recurrence relationship had a KK minus 1 and n you know and that's the wrong it's minus okay so this is mod 10. okay so this is mod 10. you know this game you know this game the game we always fail notice the max that this system can go notice the max that this system can go to is n minus one right it goes from n to is n minus one right it goes from n minus n you can't make a string that's n minus n you can't make a string that's n minus n here here because there would be no space for the because there would be no space for the remaining string remaining string so the highest they could this can go is so the highest they could this can go is n minus n minus one n minus n minus one so this would be then n minus 1 here so this would be n minus 1 here and I'll get you the solution all right guys this may this may be my very worst video nobody watches this like most of my videos that's fine but it's good for me for practice this is uh it's difficult okay what's the runtime what's the space okay so for space and run it's the same now we have to look at N Things K things so for all NK things we do constant operation it's NK NK time we have to also populate NK things here and populate NK things here so it's NK space as well so NK time and K space
2024-03-15 18:45:07
1,621
https://i.ytimg.com/vi/5…axresdefault.jpg
Leetcode 1621. Number of Sets of K Non-Overlapping Line Segments
TTFrsi6iDog
There are hello guys also in this video they go into se 10 problem numbers and wonderful into se 10 problem numbers and wonderful subjects so what is a wonderful subjects so what is a wonderful subscribe interesting where at most one subscribe interesting where at most one later affairs and number of times she can later affairs and number of times she can see the example portion this scene which is six see the example portion this scene which is six example water crisis in the number example water crisis in the number example water crisis in the number Times Series Repeated History Advantages Defeated Is Two Shoulder Should Be The Most Helped Emphasis Of Days 100 Most One Letter Application And Number-10 President SPS And Number Address To Love The Ne Pac And Number Times S You Can See The Example E 20 Directly Executives and Senior Students will Sleep MP Isko Times and Acid Test More Than New Episode Number 500 Backem Chief Bustling with the Number of and 1200 A Specific Years subscribe to the Page if you liked The this all this all this all your also what we have to bank savings so let's get up and intuition you from here this problem and will directly 100 glue subscribe to angry birds for going to be something Lakshmi explain you this act and operator and cancer se by product sweater se 0.2 subscribe to your after eggs with subscribe this piece 10101 subscribe this piece 10101 A little boy's bodh and once in this way A little boy's bodh and once in this way you will again be too difficult for lips this thank you you will again be too difficult for lips this thank you have to keep in the Distic Distic have to keep in the Distic Distic and one more thing exclusive lu dis page let's see subscribe like you can do something like this a in this and disposed and it's ok to give it a go back to this actually zero zero exams page so what's this after what you want to subscribe and decided to The That The That The That And Spiritual Mask 120 Sports C And Spiritual Mask 120 Sports C What This Will Result In This Will Result What This Will Result In This Will Result In April 2012 161 Straight B C And E Will In April 2012 161 Straight B C And E Will Be Deleted And Will Be Like This Be Deleted And Will Be Like This Subscribe Tab Off All The States With Water All Subscribe Button Letter With With U That Suvatiya is going to perceive what we will give That Suvatiya is going to perceive what we will give you now Maruti 800 1320 you now Maruti 800 1320 Bhavya Bhavan to the Video then subscribe to Bhavya Bhavan to the Video then subscribe to the Page if the hour ago to represent district the one and 10 minutes after representatives of this letter and 10 minutes after representatives of this letter will be will be will be converter05.htm that word MP's mass as zero examples notification is such only source of will suffice for a 0001 for 20 2010 ch-51 09 speed meat and exhausted Be Difficult To 10 Of 10 Things You Must See This Value Is Well In Waqt Camp What Is The Value Of 200 Maa Skirt With 20018 A Similar D Is Drafting Pocketmar Chalega Teen Do Ek Baar Off Birth Mass Mass Karne Quote Exams Page Issi Against AIDS Will be removed and will take place Will be removed and will take place Will be removed and will take place to the Tags Arvind Chief Disawar You Must to the Tags Arvind Chief Disawar You Must Agri Milk 0 Sila Duma Stands For Agri Milk 0 Sila Duma Stands For Storage Vacancy Shodh Elizabeth 110 Will Again Storage Vacancy Shodh Elizabeth 110 Will Again Witnesses And After The Printed 1200 More Importance Okay This Video Exothermic C Value 800 To this is such a To this is such a To this is such a 342 experts have the holy cave of window to Sadar Asraf so Anand Sheela me civil again this mask to 21814 operation operation this mask to 21814 operation operation operation of elements of this operation of elements of this Bluetooth once operation Shabdish are in Bluetooth once operation Shabdish are in Features What Is Means 2012 1,000 Aur Sabse Features What Is Means 2012 1,000 Aur Sabse Zor Peerche Aksar Seervi Seervi Collectively Zor Peerche Aksar Seervi Seervi Collectively 1025 E O N 0 The Video then subscribe to the Video then subscribe to The Amazing Number of the Day A S T Spoon Ali reached the fighter end gate -Between point -Between point -Between point vacancy se zinc burst MP4 se zinc from a vacancy se zinc burst MP4 se zinc from a point start cesc pair bp.ed ya na point start cesc pair bp.ed ya na dhoop wa subscribe between two points on this thing dhoop wa subscribe between two points on this thing is the meaning of the number 999 is the meaning of the number 999 apni badi easy players will always be in apni badi easy players will always be in will not understand the giver will not understand the giver will not understand the giver Everything From This Point 0.5 Special Guest Sage In 1803 E Mein Aa Adityanath Seervi Akunth Specific Market Value Is 409 Plus Understand How Will Get The Number Of And Value Member This See Its Fans Free Mode On And Drags Pair Co * Supports Then Eye Can They Pair Co * Supports Then Eye Can They Pair Co * Supports Then Eye Can They Reduce Orange Letter Of Big Reduce Orange Letter Of Big Roll Number Of Times Plain Letter Confirmation In Roll Number Of Times Plain Letter Confirmation In Which Which CBSE Is This Is Not Carefully Sweat Through CBSE Is This Is Not Carefully Sweat Through This Hair Care Numbers Page Number 2 Ask This Hair Care Numbers Page Number 2 Ask Exam Form This This Page Directly Middle Exam Form This This Page Directly Middle School With Water All The Chief Sea Fennel 2 School With Water All The Chief Sea Fennel 2 Exorbise Sapoch Example.com Sep 2012 Exorbise Sapoch Example.com Sep 2012 I One 0821 Services 12101 33500 Term End I One 0821 Services 12101 33500 Term End 109 Busy Schedule Graeme Smith And 109 Busy Schedule Graeme Smith And Sapoch 300 B C D 120 Dip So Many 0 End Sapoch 300 B C D 120 Dip So Many 0 End Values ​​End WhatsApp To See The Values ​​Off I am your show interview has welcome zero to I am your show interview has welcome zero to 1000 wide variety debate stage so 1000 wide variety debate stage so set time particular point now screams set time particular point now screams rent act will be be r ashwin dance simple rent act will be be r ashwin dance simple a letter with and recitation a letter with and recitation only be but give me example player only be but give me example player leuvin undercurrent suicide 10th over leuvin undercurrent suicide 10th over smart smart smart rear it is active on Thursday subscribe surya market value got but market value easy 2015 on amazon to z sirsa construction and worries of this character recipe subscribe button video 000 subscribe already being that This particular This particular This particular point to the end were amazed with point to the end were amazed with subscribe will be repeated subscribe to subscribe will be repeated subscribe to the Page if you liked The Video then bbc ne 181 number agree with is vansh everything is related to And subscribe And subscribe And subscribe yes bhaiya sab singh aadat hai notification for this yes bhaiya sab singh aadat hai notification for this is the concept or any user name is the different are subscribe to subscribe to the Video then subscribe to subscribe ki naav par neech character in the world everything is going to see what ki naav par neech character in the world everything is going to see what is that is that characters of characters of characters of subscribe and subscribe the Channel and subscribe and subscribe the Channel and subscribe this for the number one and number two subscribe this for the number one and number two A View of Movie Pt. Total Because Vivek A View of Movie Pt. Total Because Vivek Poochhega Qualities of Yours Veer Verification of Yourself Thank Poochhega Qualities of Yours Veer Verification of Yourself Thank You Are Masking Disha You Are Masking Disha And head and subscribe the world at that this vitamin C important direct commission committee seriously so let's committee will see this rumor giving them without any fear in 2030 password has arrived like this thank
2024-03-25 13:04:29
1,915
https://i.ytimg.com/vi/T…og/sddefault.jpg
Leetcode-Number of Wonderful substring
gmu0RA5_zxs
hey what's up guys think white here I do token counting stuff on twitch in token counting stuff on twitch in YouTube I do the Premium Lee codes on YouTube I do the Premium Lee codes on patreon everything's in the description patreon everything's in the description and you should join my discord thank you and you should join my discord thank you this problem is called rotate array a this problem is called rotate array a lot of likes some dislikes I saw people lot of likes some dislikes I saw people complaining it was too hard given an complaining it was too hard given an array rotate the array I'm sure you guys array rotate the array I'm sure you guys have heard of this rotating an array have heard of this rotating an array given an array rotate the array to the given an array rotate the array to the right by K steps where K is non-negative right by K steps where K is non-negative okay so we're given an array like this 1 okay so we're given an array like this 1 2 3 4 5 6 7 and we rotate it to the 2 3 4 5 6 7 and we rotate it to the right three times so the 7 goes to the right three times so the 7 goes to the front the 6 goes to the front and the 5 front the 6 goes to the front and the 5 goes to the front and then it's 5 6 7 1 goes to the front and then it's 5 6 7 1 2 3 4 2 3 4 so rotate a rotation is just popping so rotate a rotation is just popping something off one rotation is popping something off one rotation is popping one number off the end of the array one number off the end of the array putting it to the front and pushing putting it to the front and pushing everything else to the right so I mean everything else to the right so I mean yeah ok k equals 2 so you rotate the 99 yeah ok k equals 2 so you rotate the 99 to the front and then the 3 to the front to the front and then the 3 to the front I mean it's pretty straightforward I mean it's pretty straightforward people complain people complain this is people complain people complain this is too hard this should be medium this too hard this should be medium this should be a hard problem is so hard should be a hard problem is so hard guess what it's not hard dude guess what it's not hard dude let me tell you why you guys think that let me tell you why you guys think that when you this is what I have a problem when you this is what I have a problem with this people think especially people with this people think especially people that try to understand algorithms and that try to understand algorithms and they give up they sit and they I they'll they give up they sit and they I they'll sit and look at this problem and be like sit and look at this problem and be like they'll have a double for loop solution they'll have a double for loop solution and be like how do I do this I don't and be like how do I do this I don't know how to do this I can only get N know how to do this I can only get N squared solution I don't know how to do squared solution I don't know how to do this guess what look at the solution this guess what look at the solution just look at the solution sometimes and just look at the solution sometimes and in this case there is a trick that you in this case there is a trick that you can either sit here and spend all day can either sit here and spend all day trying to figure out and eventually trying to figure out and eventually figure it out or you can just look and figure it out or you can just look and think oh this is how it is you do these think oh this is how it is you do these steps and this is how you do it in a steps and this is how you do it in a linear run time you know it's just the linear run time you know it's just the way that it is you don't have to you way that it is you don't have to you know there's no crazy explanation for it know there's no crazy explanation for it it's just the way it is sometimes and it's just the way it is sometimes and I'll explain you know I'll show you it I'll explain you know I'll show you it the trick here is you know the array you the trick here is you know the array you know you have this array so like 1 2 3 5 know you have this array so like 1 2 3 5 6:7 if you want to rotate it three times 6:7 if you want to rotate it three times the trick is you reverse all the numbers the trick is you reverse all the numbers so you reverse one two three four five so you reverse one two three four five six seven so it becomes seven six five six seven so it becomes seven six five four three two one four three two one then you reverse the first K numbers then you reverse the first K numbers five six oh seven six five the first five six oh seven six five the first three numbers becomes five six seven three numbers becomes five six seven then you reverse the last numbers after then you reverse the last numbers after K four three two one becomes one two K four three two one becomes one two three four and look if we were to have three four and look if we were to have pulled this seven six and five off the pulled this seven six and five off the front you put five six seven one two front you put five six seven one two three four it's exactly what it is so three four it's exactly what it is so you reverse the whole list you reverse you reverse the whole list you reverse the first K numbers then you reverse the the first K numbers then you reverse the leftover numbers that's it it's just how leftover numbers that's it it's just how it is you don't have to you know it's it is you don't have to you know it's not like the person who thought of this not like the person who thought of this probably had to sit there and think for probably had to sit there and think for a while we don't have to because he did a while we don't have to because he did we just learned things it's like just we just learned things it's like just learning a thing in math class you learning a thing in math class you learned what it is you remember this learned what it is you remember this next time and that's just how it is you next time and that's just how it is you don't have to sit here like if you don't have to sit here like if you didn't know how to do it in an interview didn't know how to do it in an interview like yeah you'd have to sit there and like yeah you'd have to sit there and look at it but you that's why you study look at it but you that's why you study for the interviews you study so you see for the interviews you study so you see stuff like this you do these easy stuff like this you do these easy problems and then you know how to do problems and then you know how to do them so you know that's my rant so first them so you know that's my rant so first thing we're gonna do is we're gonna take thing we're gonna do is we're gonna take K and we're gonna do K mod nums dot K and we're gonna do K mod nums dot length just because apparently the length just because apparently the problem let's there be none nums array problem let's there be none nums array where the length of the array is less where the length of the array is less than K or equal to K and in that case than K or equal to K and in that case you know it's gonna be we have to do you know it's gonna be we have to do this to be able to know how many numbers this to be able to know how many numbers to reverse and then like we're gonna do to reverse and then like we're gonna do the steps right so we reverse nums from the steps right so we reverse nums from zero to nums dot length so we reverse zero to nums dot length so we reverse the whole array minus one we reverse and the whole array minus one we reverse and once we reverse the whole erase we once we reverse the whole erase we reverse the whole rec it looks like this reverse the whole rec it looks like this then we reverse the first K letters so then we reverse the first K letters so we pass in nums we're gonna do from zero we pass in nums we're gonna do from zero to K minus one these are indices that's to K minus one these are indices that's what were you adding the minus ones here what were you adding the minus ones here and then we're gonna reverse the and then we're gonna reverse the leftover numbers that's it guys don't leftover numbers that's it guys don't think on it too hard if you don't have think on it too hard if you don't have to think about it so much then don't you to think about it so much then don't you know so many people get stressed out and know so many people get stressed out and it's like you don't need to be so it's like you don't need to be so stressed out and then you make your stressed out and then you make your reverse method that's a it's real that's reverse method that's a it's real that's why it's easy because why it's easy because it's easy you know just look learn it it's easy you know just look learn it and then you don't forget it you know and then you don't forget it you know just remember some of them you do have just remember some of them you do have to figure out solutions to but you you to figure out solutions to but you you have to learn your tools before you have to learn your tools before you actually you know this is a tool actually you know this is a tool learning one so and then you use this to learning one so and then you use this to figure out harder versions of this figure out harder versions of this problem but this is something you just problem but this is something you just got to know got to know so whilst art is less than and we're so whilst art is less than and we're gonna do you get your tenth will set it gonna do you get your tenth will set it to numbs of start we're basically just to numbs of start we're basically just doing swaps so you do a number doing swaps so you do a number that's equal the number and this is just that's equal the number and this is just our basic reversal so you just go our basic reversal so you just go through the array and you swap the it's through the array and you swap the it's like two pointers almost one at the like two pointers almost one at the beginning one at the end and you're just beginning one at the end and you're just swapping them as you go through that's swapping them as you go through that's just a basic reversal and then nums and just a basic reversal and then nums and then you always have to make a temp then you always have to make a temp because you lose the reference to start because you lose the reference to start right here we're resetting it so we want right here we're resetting it so we want to set numbs abend equal temp and then to set numbs abend equal temp and then you just decrement start so you do plus you just decrement start so you do plus plus and minus minus and yeah that's it plus and minus minus and yeah that's it it's the whole problem that's why it's it's the whole problem that's why it's easy you know it's easy there you go let easy you know it's easy there you go let me know what you guys think let me know me know what you guys think let me know if I'm wrong here but I'm I mean I see a if I'm wrong here but I'm I mean I see a lot of people that like complain about lot of people that like complain about you know this should be under medium you know this should be under medium category it's like I don't know it's I category it's like I don't know it's I think it's just people overthinking think it's just people overthinking things and it's like sometimes you know things and it's like sometimes you know I don't here's a one more thing before I I don't here's a one more thing before I get off I know this isn't like a advice get off I know this isn't like a advice video but if you're struggling with a video but if you're struggling with a problem for more than twenty or thirty problem for more than twenty or thirty minutes minutes you're wasting time dude look at the you're wasting time dude look at the solutions learn from them there's solutions learn from them there's thousands of these problems you can thousands of these problems you can learn the basics just look at the learn the basics just look at the solutions and learn from them and then solutions and learn from them and then when you're ready you can start using when you're ready you can start using your knowledge to actually knock out your knowledge to actually knock out problems on your own you know that's problems on your own you know that's what I that's my strategy let me know what I that's my strategy let me know what you guys think in the comments but what you guys think in the comments but appreciate you guys for watching sorry appreciate you guys for watching sorry for being a little bit negative I just for being a little bit negative I just want you know you guys not to waste your want you know you guys not to waste your time don't waste hours on these and then time don't waste hours on these and then stress yourself out and give up just fit stress yourself out and give up just fit learn from learn from things this like I learn from learn from things this like I got it down in my mind now I don't know got it down in my mind now I don't know I don't have to look I don't have to I don't have to look I don't have to look you're look you're the whole list you reversed the first K the whole list you reversed the first K you reversed the rest of them that's it you reversed the rest of them that's it thank you guys for watching and I'll see thank you guys for watching and I'll see you guys in the next one
2024-03-20 10:49:53
61
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode Rotate Array Solution Explained - Java
qZ6wFKhaCeQ
hi everyone welcome back in this video I'll be solving another SQL problem I'll be solving another SQL problem problem number 1193 monthly transactions problem number 1193 monthly transactions let's take a look at the problem let's take a look at the problem statement we are given a table called statement we are given a table called transactions this table has five columns transactions this table has five columns ID country State amount and Trans State ID country State amount and Trans State ID is the primary key of this table the ID is the primary key of this table the table has information about incoming table has information about incoming transactions the state column is an enum transactions the state column is an enum of type approved and declined so our of type approved and declined so our task is to find for each month and task is to find for each month and Country all right the number of Country all right the number of transactions and their total amount the transactions and their total amount the number of approved transactions and number of approved transactions and their total their total amount we can return the result table in amount we can return the result table in any order so let's take a look at the any order so let's take a look at the example so this is the transactions example so this is the transactions table for ID number 121 122 123 and table for ID number 121 122 123 and 124 country 124 country State the amount Trend State the amount Trend State and the in the output as you can State and the in the output as you can see we get the month from Trans State see we get the month from Trans State the month column include the year and the month column include the year and month of the trans date so we have to month of the trans date so we have to extract the year and month from trans extract the year and month from trans date column to make a month column here date column to make a month column here and Country all right and trans and Country all right and trans count trans count should be the number count trans count should be the number of transactions so it's going to be the of transactions so it's going to be the count of um the amount so that's going count of um the amount so that's going to be the trans count what else we need to be the trans count what else we need approved count so it's going to be approved count so it's going to be um the count or the sum of um the count or the sum of uh let's do the sum because we are going uh let's do the sum because we are going to use uh the IF function or case when to use uh the IF function or case when so it's going to be the sum of uh so it's going to be the sum of uh approved so where if it's approved we're approved so where if it's approved we're going to give a value one so it's going going to give a value one so it's going to be approved sum to be approved sum approved right so this is going to be an approved right so this is going to be an approved count what else do we need uh TRS total amount so this is going to be right the number of approved and the right the number of approved and the total amount okay so sum total amount okay so sum amount so this is going to be the trains amount so this is going to be the trains total amount and what's next okay the number of a through transaction and the total amount oh so it's going to be the sum of the um amount as well so if it's approved we are going to get the amount value so this is going to be the approved total amount our total amount all right so this is pretty much what we need um to create the rest of the column besides month country uh columns all right so let's solve this problem okay so let's take a look at um how we are going to get the year and month of the uh date time uh format so the function to get the um date of the year and month is going to be date format don't know the that function you can just type in like how to get year month from date in um let's take a look at this one we can get the month only year only but all right so this is the function we need so we use the function date format and we put the date the the train date that we need to extract the date from and we put the format that we need Okay so let's do that so in order to get the format we use trans format we use trans date and the format we want is year and month all right so we call call this column month even though it have it has years in it uh right so and then we also need country and now we are going to calculate these uh the number of transactions the total amount the number of approved transactions and total uh amount the order is a little bit different than is listed here but that's okay we are going to create create trans count excuse me count count excuse me count amount this is going to be a trans count next we have uh we need to get the approved count all right so approv count as I said um earlier we are going to use either case when or if condition if you watch my uh other videos you will see that I use this if function a lot to um bring in the condition so it's going to be sum of so if um approved then we're going to give it a approved then we're going to give it a value one if not it's zero all right value one if not it's zero all right this column is going to be called uh this column is going to be called uh approv account approv count all right next come what do we need trans total amount so the amount of the uh transaction that has to state um oh wait so this is the trans total amount oh so this is the amount the total amount from this uh transaction account so it's going to be so just call so just call this trend total this trend total amount all right what is amount all right what is next approved total amount so it's going next approved total amount so it's going to be the amount where the state of of to be the amount where the state of of the transaction is approved so we're the transaction is approved so we're going to do going to do sum again we're going to use if uh sum again we're going to use if uh condition condition State equal to approve D then we'll take the sum of amount so here we're going to put amount if not zero so this is called approved total amount all right is approve total amount I think we have all columns one two 3 4 5 six 1 2 3 4 5 6 okay we select like all table okay and we're going to group Country Country current okay so let's run this all right uh case one accepted all right so that's that's good but let's make sure that we pass all the test cases nice so I passed all the test cases nice so I passed all the test cases uh run time 1178 milliseconds B cases uh run time 1178 milliseconds B 25.2% of users with my SQL okay nice uh 25.2% of users with my SQL okay nice uh that is for today thank you for watching that is for today thank you for watching I'll see you in another video
2024-03-25 18:08:40
1,193
https://i.ytimg.com/vi/q…axresdefault.jpg
Leetcode SQL 50 | 1193. Monthly Transactions I Solution
0BgaoIN1VUQ
hi everyone this is Emma let's look at some little problems today we are going some little problems today we are going to look at 365 water and Jack problem so to look at 365 water and Jack problem so first let's read the problem you are first let's read the problem you are given two Jacks with capacity The Jug 1 given two Jacks with capacity The Jug 1 capacity and the drag 2 capacity leaders capacity and the drag 2 capacity leaders and there is infinite amount of the and there is infinite amount of the water supply available you need to water supply available you need to determine if it is possible to measure determine if it is possible to measure exactly the target capacity leader using exactly the target capacity leader using these two jacks these two jacks so finally the target capacity leader of so finally the target capacity leader of the water need to be contained within the water need to be contained within one or both buckets one or both buckets here are the options you are allowed to here are the options you are allowed to do you can fill any of the tracks with do you can fill any of the tracks with water so initially that's empty you can water so initially that's empty you can feel it okay fill with water or you can feel it okay fill with water or you can empty any of the Jets so it has some empty any of the Jets so it has some water inside you can empty that or you water inside you can empty that or you can pour water from one Jack to another can pour water from one Jack to another one so you have the smaller one it has one so you have the smaller one it has the the one liter of the water and you the the one liter of the water and you decide to pour water from the smaller to decide to pour water from the smaller to bigger one so finally smaller one is bigger one so finally smaller one is just empty their liter inside and the just empty their liter inside and the larger one has a one liter of the water larger one has a one liter of the water and here's one example we have the and here's one example we have the Jaguar capacity three and the Jack 2 is Jaguar capacity three and the Jack 2 is a larger it is a larger capacity is five a larger it is a larger capacity is five and our Target is full the output is and our Target is full the output is true so let's see how to solve this true so let's see how to solve this problem problem so we have two Jack so we have two Jack one is smaller it has capacity and the one is smaller it has capacity and the other is bigger is five we have our other is bigger is five we have our Target capacity Target capacity that is four that is four so what we can do right now since these so what we can do right now since these two Jacks are empty right now we can two Jacks are empty right now we can choose either fill the smaller or the choose either fill the smaller or the bigger jug with water so let's try to bigger jug with water so let's try to fill the bigger one with water while you fill the bigger one with water while you can also choose a smaller one but here I can also choose a smaller one but here I just use a bigger one as a demonstration we fill the drug with water larger one with water so right now it has five inside it's still empty and we decide to um pour the water from the larger one to smaller one right we can get a smaller one it has a on the water from the larger one so finally it has a three right three over here and the larger one only and next what we can do we can empty and next what we can do we can empty This Modern one This Modern one right and we can transfer we can pull right and we can transfer we can pull the water the water so finally what we can get so finally what we can get we can get so initially that will empty we can get so initially that will empty the smaller jog is zero and we'll get the smaller jog is zero and we'll get two two water from the larger one water from the larger one and the larger one would be just empty and the larger one would be just empty next we can add water to the larger on next we can add water to the larger on junk junk and we can transfer the water to a and we can transfer the water to a smaller one so if I know what we can get smaller one so if I know what we can get so for the smaller one so for the smaller one it will be full it will be full with three and the larger one initially with three and the larger one initially that is five that is five it says one liter of the water get to a it says one liter of the water get to a smaller one so finally you know when it smaller one so finally you know when it has four left okay has four left okay and this one the smaller one is three and this one the smaller one is three and finally we just need to remove the and finally we just need to remove the water from the smaller jug and finally water from the smaller jug and finally we can get we can get smaller one is empty and a larger one it smaller one is empty and a larger one it has a four liter inside and this is our has a four liter inside and this is our Target Target if we look at the entire process we if we look at the entire process we track the total amount of the water of track the total amount of the water of both jugs okay you will notice initially both jugs okay you will notice initially this is zero right and we this is zero right and we add five add five here is transfer body will not affect here is transfer body will not affect the total amount the total amount and then we will remove from the smaller and then we will remove from the smaller jug is minus three jug is minus three and here is we add another five and here is we add another five we'll remove another three we'll remove another three so that's a zero plus five minus three so that's a zero plus five minus three plus five minus three finally we'll get plus five minus three finally we'll get a four here as we can see for each step a four here as we can see for each step we have four options we have four options you can plus five or minus five or plus you can plus five or minus five or plus three or minus three three or minus three so finally we will get our Target floor so finally we will get our Target floor or not or not let's recall how we solve the problem so let's recall how we solve the problem so let's track the total order of Two Jacks so initially two of the two of the drugs they're empty so the total should be zero and we have four options we can do plus five minus five minus three plus three and we can calculate total so the total and we can calculate total so the total here is five negative five negative here is five negative five negative three and three three and three so for the first one the five is okay so for the first one the five is okay well it's negative five it's not well it's negative five it's not possible the total of the two jar should possible the total of the two jar should be at least zero that means at this be at least zero that means at this moment they are empty if the total is moment they are empty if the total is smaller zero and also if the total is smaller zero and also if the total is um larger than eight the eight is the um larger than eight the eight is the largest possible amount of the water largest possible amount of the water when Two Jacks fill with water when Two Jacks fill with water we need to return we need to return we couldn't find a solution from these we couldn't find a solution from these steps here we can just return false get steps here we can just return false get a false a false this way as possible this way as possible and we can keep searching so for this one so for this one is larger than the upper boundary we can is larger than the upper boundary we can just return force and this one just return force and this one zero we've already seen zero before so zero we've already seen zero before so we don't want to repeat over here we we don't want to repeat over here we need to need to um um create a set create a set we call that scene to track the total of we call that scene to track the total of Two Jacks we've seen before so we Two Jacks we've seen before so we already seen zero over here and a five already seen zero over here and a five right we add a five and we also add right we add a five and we also add three inside or or it is out of the boundary it is out of the boundary we all need to return false so we can continue this is false because we've already seen that zero before and this is two we didn't see that so it is okay and eight is also okay okay so let's just add the two in it to the sink over here and we can continue from here we have four potential options five minus five minus three and three so we can do a calculation of the total here should be seven negative three negative one and also five so we can check the seven we didn't see that before so we can add a 7 to the same and negative three since that is smaller than zero we just need to return false and also here's negative value return force and the five we've already seen five in the same set so we just written fours plus five minus five minus three plus five minus five minus three plus three we can do a calculation of plus three we can do a calculation of the total it should be the total it should be 12 2 4 10. 12 2 4 10. so for the 12th it's out of boundary so for the 12th it's out of boundary larger than 8 return Force the two we've larger than 8 return Force the two we've already seen two before return force and already seen two before return force and here the 4 equals to our Target total equals to the Target okay just return true so we can find the final Target is four we can just return true so it's from zero five minus three then plus five final again get our Target so we will look at our criteria over here if we didn't see that before and that increasing the boundary and it's not the target so for the total we have four options we can plus 5 minus five or minus three or plus three if any of them return true we can just return true else we return false so right now let's consider about the time and space complexity so for the space as we can see we only have this thing set and for the things that we have potential value from 0 to the sum of two capacity the capacity one plus a capacity to a space complexity it should be o the capacity of one plus capacity two while for the time we have jaguan and jag2 so for the Jaguar just zero liter of the water to the capacitive one well for the juncture it has zero to capacity two so how many combinations over here you should be capacity one plus one then times capacity 2 times 1. so finally for the time complexity it should be o capacity 1 times capacity 2. here we will introduce both DFS and BFS to implement idea we share before let's so first we need to create a set we'll so first we need to create a set we'll keep the totals we see before and then we will create a function for then we will have the total as our input then we will have the total as our input so if the total so if the total that equals to the Target that equals to the Target we can just return true we've seen the total before we've seen the total before or the total is out of boundary or the total is out of boundary larger than the sum of jug 1 and jugular larger than the sum of jug 1 and jugular capacity capacity so we just return both so we just return both if the total is not equal to Target we if the total is not equal to Target we didn't see that before it's also within didn't see that before it's also within the boundary the boundary then we can add the total to C for Next Movement we can either add or minus junk capacity over M minus junk to capacity so you can do that quickly so for for different for potential if any of them if any of them return true we will return true right return true we will return true right all of the Rhythm force it will return all of the Rhythm force it will return Force Force so we can just return it so we can just return it and now we need to call this DFS and now we need to call this DFS function initially the total should be function initially the total should be zero so both of them are empty you can zero so both of them are empty you can just return this value and we can try to run so finally we can pass on the test and so finally we can pass on the test and now we can try the second solution now we can try the second solution be at best be at best and we are going to use Q to implement and we are going to use Q to implement this idea so we will create a queue this idea so we will create a queue and we have the first value the total is and we have the first value the total is zero inside zero inside and we will create a set and we will create a set keep tracking keep tracking the thing total the thing total and we have four different potential and we have four different potential options options so we can plus or minus the Jack so we can plus or minus the Jack capacitor one or plus minus drug capacitor one or plus minus drug capacity two while we have something in capacity two while we have something in the queue the queue and we will pop the first one and we will pop the first one this is the top left this is the top left and we will iterate all the potential and we will iterate all the potential operations operations will calculate the total the total will be current plus that and if the total equals to our Target we will just return true if the total we and the total is releasing the limit and the total is releasing the limit that means that means nicer than zero and also smaller than nicer than zero and also smaller than the sum of two capacity the total the total you see you see we will append this tunnel to the we will append this tunnel to the current queue current queue if there is no solution return true your if there is no solution return true your return false and we can try to run it and it works
2024-03-24 11:27:43
365
https://i.ytimg.com/vi/0…axresdefault.jpg
Leetcode 365. Water and Jug Problem [Python] DFS, BFS
QnTCtWTmVgU
hello everyone let's look at jump game the problem statement is we are giving the problem statement is we are giving an array an array of positive integers we are initially of positive integers we are initially positioned at the first index of the ray positioned at the first index of the ray each element in array represents the each element in array represents the maximum jump we can take maximum jump we can take at that position we need to determine if at that position we need to determine if we are able to reach we are able to reach the last index let's look at the example the last index let's look at the example this is input 23114 initially we are this is input 23114 initially we are here here at two and then we can jump either one at two and then we can jump either one step or two steps step or two steps so if we jump one step we reach three so if we jump one step we reach three and three we can jump three steps and three we can jump three steps to four or we can jump one or two to four or we can jump one or two so if we jump three steps to four then so if we jump three steps to four then we reach the end we reach the end that's the explanation jump one start that's the explanation jump one start from index zero to one and then three from index zero to one and then three steps steps to the last index i guess a to the last index i guess a really straightforward solution is to really straightforward solution is to try every single jump pattern try every single jump pattern starting from the zero index and then starting from the zero index and then we only need to check if any path will we only need to check if any path will lead us to the last index lead us to the last index this is like travels a tree and we need this is like travels a tree and we need to use recursive back tracing to use recursive back tracing but if we think about recursion it might but if we think about recursion it might not be the optimal solution not be the optimal solution this is like if we want to solve a this is like if we want to solve a fibonacci sequence fibonacci sequence we rather use a recursion rather than we rather use a recursion rather than using a single loop using a single loop however for this question i will still however for this question i will still explain the recursive solution explain the recursive solution but in general it should be categorized but in general it should be categorized into dynamic programming into dynamic programming it's a top-down dynamic programming it's a top-down dynamic programming solution solution let's use an example here think about our input arrays 3 so initially we're at position zero so initially we're at position zero that's three that's three that means we can jump one step two that means we can jump one step two steps three steps steps three steps if we jump one step it's one if we jump one step it's one the value is one we can only jump once the value is one we can only jump once then we jump to zero zero we won't go then we jump to zero zero we won't go anywhere anywhere so this path three one zero doesn't work so this path three one zero doesn't work let's back to three if we jump twice let's back to three if we jump twice then we jump to zero we jump to here and then we jump to zero we jump to here and then we still don't go anywhere then we still don't go anywhere so three zero this path doesn't work so three zero this path doesn't work if we jump three steps then we jump to two and two the value two we can jump either once or twice and then reach four that's the last and then reach four that's the last index index so we have this one path 3 so we have this one path 3 2 4 reach the last index 4. 2 4 reach the last index 4. as a result we can return true so as a result we can return true so we can easily build this tree structure we can easily build this tree structure and then and then determine if we can reach the last index determine if we can reach the last index let's look at this tree again well let's look at this tree again well please think of this as a tree please think of this as a tree when we jump we can mark a certain index when we jump we can mark a certain index as good or bad for example this one as good or bad for example this one index is two is certainly a bad index index is two is certainly a bad index because the value is zero it won't lead because the value is zero it won't lead us to anywhere us to anywhere we end up stuck stacking here also we end up stuck stacking here also for index one the value is 0 for index one the value is 0 sorry the value is 1 and the next one is sorry the value is 1 and the next one is also 0 also 0 so this index is also bad so this index is also bad to sum up we want to mark every index to sum up we want to mark every index either good or bad either good or bad from top to down from top to down let's go through an example so initially the values are unknown this is unknown unknown unknown unknown okay from top to bottom for unknown okay from top to bottom for three three we don't know for one we don't know for we don't know for one we don't know for zero zero index is 2 this one becomes bad index is 2 this one becomes bad because index 2 is bad index 1 is also because index 2 is bad index 1 is also bad bad so this becomes from unknown to bad so this becomes from unknown to bad and then 2 and then 2 two we don't know but next one that's two we don't know but next one that's four four four is good so that's two four is good so that's two is also good and three is also good is also good and three is also good because they're on the same path because they're on the same path and all these good and back can be saved and all these good and back can be saved into a memorization array into a memorization array let's call it memo so initial value will let's call it memo so initial value will be all unknown be all unknown and then from top to bottom we update and then from top to bottom we update the value the value in the end as long as the first element in the end as long as the first element for this array is good then we know for this array is good then we know we can jump until the end based on the we can jump until the end based on the rule we just described here rule we just described here i know you are thinking about why now we i know you are thinking about why now we check the index in a reverse order check the index in a reverse order first from 4 then to 2 then to 0. first from 4 then to 2 then to 0. i'm telling you this is a really good i'm telling you this is a really good thought thought this will be the second solution we call this will be the second solution we call it a bottom-up it a bottom-up dynamic programming let's first look at dynamic programming let's first look at the implementation for the recursive the implementation for the recursive top-down approach so first we get the length of the input array and then we initiate our memorization array the initial value are all unknown and we want to update that last element the last element should be good and then this is our recursive method and then this is our recursive method we pass index in as a parameter we pass index in as a parameter and then we only need to return and then we only need to return jump 0 let's look at the implementation jump 0 let's look at the implementation for this recursive method if the car inducts the value is good will return true and then we have this number's i this is and then we have this number's i this is a value a value is how many steps we can jump for the is how many steps we can jump for the loop loop we need to have a boundary check we need to have the mean value for the lens minus 1 and the steps we can jump this is because we need to have this boundary check and what should be the start index for this what should be the start index for this i i i think it should be index plus one if we think the starting index is index if we think the starting index is index plus 1 plus 1 then this max jump here we should also then this max jump here we should also have idx have idx plus nums i and then plus nums i and then let's do the jump again let's do the jump again we pass it in we check the jump result if it's true then we can update the index for this memo and also return true otherwise after the for loop if we don't it should be marked as bad and this is the recursive method and this is the recursive method and uh and here it should be idx not i and uh and here it should be idx not i so this is the how many steps we can so this is the how many steps we can jump and we add this um jump and we add this um index that's why we have i equals index index that's why we have i equals index plus one plus one let's sum it in past let's sum it in past but it's um yeah takes really long time but it's um yeah takes really long time let's first look at the capacity here for space is all n [Music] this is the size of our mammal table it's open square because we have this it's open square because we have this recursive method obviously we all know recursive method obviously we all know this is definitely not the optimal this is definitely not the optimal solution solution let's look at the bottom-up solution let's look at the bottom-up solution for the bottom-up approach let's see for the bottom-up approach let's see this example again so this is our mammal the initial value will be bad bad bad bad bad initial value is all bad except the last digit the last one is good and then we from back to front if 4 is good and the next one second last two is too good i think it is good because it can jump either one step or two steps so we update this too good and then we keep moving back zero is this good or bad no it's bad we keep it like this and then one is one good or bad i guess it's bad and then three is three good or bad it's good by doing this we get this final mammal array and then we return the first element for this memo sorry not return the first element but to check if the first element first we can completely get rid of this first we can completely get rid of this recursive method recursive method in the end what we need to return we only need to return this as long as the first element for the memorization array is good then we should return true let's look at inside we do the loop from back to front so the start index is the second last and then we keep minus one inside the loop we also have this and then inside this we have another for so for the j as long as the j so for the j as long as the j is at the good position so if j is good then we can say i is we can break this inner loop and then we go to the outer loop we have this this is typo we have this max jump and then we do the inner loop again after the for loop ends we return this if the first element for the memo array is good let's submit it passed and this time the performance is much better than the first approach let's look at this time space is of n that's the size this time space is of n that's the size of our memorization array of our memorization array for time it's all n squared because we for time it's all n squared because we have this outer loop and inner loop have this outer loop and inner loop i do understand for both top down and i do understand for both top down and bottom up dynamic programming solutions bottom up dynamic programming solutions are not optimal and even confusing if i are not optimal and even confusing if i have confused you have confused you feel free to move back and look at the feel free to move back and look at the video one more time video one more time finally let's look at grady which is finally let's look at grady which is supposed to be the best solution supposed to be the best solution for this question to illustrate my idea for this question to illustrate my idea let's look at this example again let's look at this example again let me clean up this a bit so initially we have a value called maxjump and the initial value is 4 4 comes from length -1 then we can loop through the array from back to front we can skip the last index and then let's look at the second last index index is 3 value is 2 and we need to compare the sum value 3 plus 2 if it's greater or equal than max jump if it's greater then we mark this index as good the reason is because at this index we can jump two steps that's greater than four so we mark this as good and then we update our max jump into three that's the index for this good index and then we keep loop we move to index two and index two the value is zero so we add them together we get 2 2 is less than max jump so we mark this as a bad index and we don't update our max jump max jump is still 3 and then we move to index 1. value is also one we have one plus one that's two that's less than max jump still we mark this index as a bad index and we don't update our max jump and then we move to index zero adding them together zero plus three is three so we mark this as a good index and then we update our max jump to be zero after the loop if the maximum value is zero then we can return true if i have confused you let's look at the implementation i can confirm it will be clear when we look at the this is our max jump initial value and this is our max jump initial value and then let's do the for loop [Applause] [Music] last if the sum value is greater or equal than max jump after the for loop will we return if max after the for loop will we return if max jump equals zero let's submit it looks good first base is constant the time is o of n we have this loop here i'm sorry this video is a bit long i hope you find this explanation useful when you look at this question thank you for watching if you have any question please leave a
2024-03-20 10:29:32
55
https://i.ytimg.com/vi/Q…axresdefault.jpg
LeetCode 55 Jump Game in javascript
gj1Y-enAlXM
now let's take a look at a legal problem called longest called longest substring with at most two distinct substring with at most two distinct characters characters so given a string s find the length of so given a string s find the length of the longest substring t that contains at the longest substring t that contains at most two distinct characters most two distinct characters so at most to the same character so at most to the same character basically means that um not no more than two distinct characters so if we have only one distinct character in the string that still count as a uh that we can still calculate the longest substrate right only if it's like more than three uh distinct characters in the substring then we cannot be able to uh count that as a as a longest substring uh so in this case here you can see we have an example of e c e b a and the longest substrate in this case is gonna be three because we have ece which has a length of uh three right so in this case it has two distinct characters in the substring and uh we only we have a size of three right so is is the max so and then here you can see we have another example of c c a a b b b and in this case t is a a b b b which is has length is five right so we have a a b b b which has a length five and uh it has two distinct characters in the substring now we could choose ccaa but in this case we have a line of four so it's not the it's not the largest so to solve this problem uh we're going to use sliding window technique uh basically we're just going to expand our window uh if it can satisfy our condition and we're going to contract our window when we don't satisfy our condition right when we when we start to uh don't satisfy our condition we want to make sure we can track our window and um and then from that we're going to continue to expand our window after we're done contracting right after we're contracting we want to make sure our windows satisfy the concurrent condition that we can be able to expand so let me show you a demonstration of that so let's say we have an example of e c e b a okay so so far we have one element in the table in this case we have e and the max length that we have seen so far is one because we can have uh one character in this case our current window satisfy the condition because we have no more than two distinct characters in our window so now we expand our window now we have c so c has up here once okay so we're going to have max length that we have seen so far is two because we have two elements in our window so now we have e so now we're going to add e by one right so in this case we're going to out in this case our window has two e's and our wind our maximum length that we have seen so far is three so now we're going to expand our so now we're going to um so now we're going to um check to see if if we satisfy the check to see if if we satisfy the condition but in this in this case we condition but in this in this case we don't because we have at least three and don't because we have at least three and now we have three distinct characters so now we have three distinct characters so we're gonna we're gonna uh contract our window so now we're uh contract our window so now we're going to going to shrink our window now we have only one e shrink our window now we have only one e and now we're going to still doesn't and now we're going to still doesn't satisfy the condition then we're going satisfy the condition then we're going to shrink our window again to shrink our window again now we have e and b now we have e and b so now we're gonna update our maximum so now we're gonna update our maximum length in this case but the thing is length in this case but the thing is that that our maximum length is three three is our maximum length is three three is bigger than two so we don't we won't bigger than two so we don't we won't update the update the the the current uh the current maximum the the current uh the current maximum life so then we're gonna life so then we're gonna start to expand our window again because start to expand our window again because in this case we have in this case we have satisfied the condition so now we have a satisfied the condition so now we have a we add a onto our window we add a onto our window and then we're going to have three and then we're going to have three elements but in this case we have elements but in this case we have the same characters of three so we have the same characters of three so we have to start contracting because to start contracting because in this case we don't satisfy our in this case we don't satisfy our condition so now we're going to remove e condition so now we're going to remove e out of our table out of our table and now we start to met the requirement and now we start to met the requirement metacondition metacondition and then we have to update our max and then we have to update our max length in this case the size length in this case the size is two but the max length right in this is two but the max length right in this case the max length case the max length is three so three is bigger than two is three so three is bigger than two right so there are only two element right so there are only two element two elements in the window so in this two elements in the window so in this case we're not going to update that case we're not going to update that so now let's take a look at how we can so now let's take a look at how we can do this in code so do this in code so first we know we basically know that the first we know we basically know that the constraints constraints it doesn't really have any constraints it doesn't really have any constraints so what we can say is this we can first so what we can say is this we can first define our base case define our base case so if the string is empty or string has so if the string is empty or string has only one element only one element uh then we can just return the size of uh then we can just return the size of string right because there's only string right because there's only uh one element where there's no there's uh one element where there's no there's no elements at all so we're going to no elements at all so we're going to return the size of the string return the size of the string size of string if if the size of the size of string if if the size of the in this case if the size of the string in this case if the size of the string is less than three actually because if is less than three actually because if there's only two there's only two then we know that that's going to be uh then we know that that's going to be uh that's going to be a valid answer right that's going to be a valid answer right then once we define our base case we're then once we define our base case we're going to define our pointers right so going to define our pointers right so define our pointers define our pointers and we want to make sure we define the and we want to make sure we define the table table right and we want to define right and we want to define a max length so once we define those a max length so once we define those variables we're going variables we're going to basically trying to to basically trying to find the max length find the max length right so max length substring right so max length substring to the same characters okay to the same characters okay so let's define those sections so first so let's define those sections so first we're going to have we're going to have n which is equal to s dot n which is equal to s dot uh as the length or what we can do is we can convert this into a character array which is equal to s.2 character array and then we're just going to say okay so once we've done that we're going okay so once we've done that we're going to say if n is less than three we can to say if n is less than three we can just return just return it right if there's only one element in it right if there's only one element in the array the array in the in yeah in the array then we can in the in yeah in the array then we can just return the size of the array if just return the size of the array if there's two elements then we can just there's two elements then we can just return two return two right and then we're gonna define our right and then we're gonna define our pointers so our pointer is gonna be pointers so our pointer is gonna be in this case we have our left which is in this case we have our left which is equal to zero so the right equal to zero so the right also starts at zero once we define our also starts at zero once we define our pointers we're going to define our table pointers we're going to define our table so we have a map sorry it should be character should be the key right and the integer is going to be the value so we have hashmap is equal to hashmap okay so once we define our table we're going to define our max length so now we are going to have integer max length which starts at zero okay initially we have we haven't had any elements yet okay so we're going to say this we're going to say while the right point is less than n right we're going to start to expand our window because in this case we we uh we satisfied our condition right so what we're going to do is we're going to first add the current character onto our hash map so we're going to say hashmap.put okay we're going to say array at right okay it's going to be hashmap.get or default because we don't know if we create that position we haven't created that element yet so in this case we're going to say array at r by default is zero we're going to plus so once we update our hash map we're so once we update our hash map we're also going to also going to basically check to see if we satisfy our basically check to see if we satisfy our condition right so in this case what condition right so in this case what we're going to do we're going to do is we say while right so while is we say while right so while um the the size of the hash map so the um the the size of the hash map so the size size in this case is if it's bigger than two in this case is if it's bigger than two then we know that we don't satisfy then we know that we don't satisfy so we shrink so we contract so we shrink so we contract our window if we don't our window if we don't met the condition right if we don't need met the condition right if we don't need the condition the condition so in this case we're going to start to so in this case we're going to start to shrink our window right shrink our window right so what we're going to do is we're going so what we're going to do is we're going to to remove the element that the left pointer remove the element that the left pointer is pointing to is pointing to so we're going to say hashmap.put so we're going to say hashmap.put array at left we're going to decrement array at left we're going to decrement that element by one so hashmap.get that element by one so hashmap.get uh array uh array left decrement by one and if you realize left decrement by one and if you realize that hash map dot get that hash map dot get right hash my bucket array left right hash my bucket array left is equal to zero then we know that we is equal to zero then we know that we can just delete that element right so can just delete that element right so remove remove array left and just delete the l delete array left and just delete the l delete that element and otherwise if we that element and otherwise if we uh if we don't we don't have to delete uh if we don't we don't have to delete an element right so in this case what an element right so in this case what we're going to do then is we're going to we're going to do then is we're going to move move the left pointer one to the right the left pointer one to the right because now we delete the element off because now we delete the element off our table our table and we can be able to shrink our window and we can be able to shrink our window now so now so then at the end what we're going to do then at the end what we're going to do is we're going to continue to get to a is we're going to continue to get to a state where we state where we continue to shrink our window until we continue to shrink our window until we met the condition until we met the met the condition until we met the condition which is condition which is basically uh can track our window until basically uh can track our window until we have at least uh uh you know we have at least uh uh you know less than or equal to two elements in less than or equal to two elements in the in the table right the in the table right so then what we're gonna do then is so then what we're gonna do then is we're gonna um we're gonna um update our max length right so in this update our max length right so in this case our max length case our max length is now equals to the maximum value is now equals to the maximum value between either max between either max length or the size of table or sorry the length or the size of table or sorry the size of the window size of the window in this case to calculate the size in this case to calculate the size window is going to be the right point or window is going to be the right point or minus the left pointer minus the left pointer plus one to give to which give us how plus one to give to which give us how many elements do we have in our window many elements do we have in our window so once we update our max length we're so once we update our max length we're gonna gonna we're going to move our right pointer we're going to move our right pointer one to the right one to the right so now we because now we know we met so now we because now we know we met because after we've been through all because after we've been through all this this while loop thing we know that we met the while loop thing we know that we met the condition that we can start to expand condition that we can start to expand our window again our window again so we're going to continue to do that so we're going to continue to do that until we get to a point where we until we get to a point where we um iterate or basically traverse all the um iterate or basically traverse all the elements in the array then we can just elements in the array then we can just return return the max length okay so the max length okay so now let's try to uh run our code okay let's try to run a code okay let's try to run a code okay so let's try with this example okay so let's try with this example right here right here and let's try to submit so here you can and let's try to submit so here you can see this is how we solve see this is how we solve this uh liko long longest substring with this uh liko long longest substring with at most two distinct characters
2024-03-21 13:38:56
159
https://i.ytimg.com/vi/g…axresdefault.jpg
[Java] Leetcode 159. Longest Substring with At Most Two Distinct Characters [Sliding Windows #2]
KBQXKkAPLlU
hello everyone today we are gonna solve find common characters problem so in this problem we have an array of strings and we have to find the common characters which are present in all string including the duplicate so in this example you can see that e double l is present in all of these three string so in this case we will written e l and double l and this can be in any order so how do we do that so our first intuition will be what we can do one thing we can use um map we can use the map where we will store how many times a character is present let's say this is present b is present one time is present he is here present one time l is present two times and e is present one time and here also we can map how many characters are present here so we can say that l is present here two times and a is present here one times b is present here one times and is present here one time and if i map this also so this will be r is present one time o is present one times l is present two times and this is present one times and this r is present um definitely it's present two times so i will remove this so now now what i have to do i have to find b is present here b is present here so what i can say that here my b is present yes it is one here i can say that b is present zero times yes so what i have to do i have to choose the minimum one from this so my b is present zero time so if b is zero then i will not include into my answer not included my answer now see now let's see e is one time one time and here he is also one time so minimum will be one time so i can write e one time here now let's see here is is to um this is l this is l so l is two times here at l is two times and here also l is two times so what i will do i will make l two times in my answer now this a is here one time also one time here is no is i can say that a is zero times so minimum will be zero so i have done this so what uh how can i do this so this is my intuition how can i do this for this case how many number of alphabets we have in english so we have 26 alphabets so what we can use we can use a simple array having size 26 and we will initialize with zero in the slide with zero why because initially we have no character in a string then we will iterate from i trade this first string and store all the character in this all the character in this string or this array and now we will add this into our new vector and check compare which one is which one is minimum and the minimum one will be stored in this vector and this let's say i will name it as a common vector so i will do that after all after that i will add all these characters of the string into my vector and i will do it for all the strings all the remaining string and once i will find the common i will find the common and this common will be minimum minimum of all this all character minimum so at if there are is to here is two time present here is two time present but here is one time present then i will add only e one time if this is two everywhere or minimum two then i have to add two here so now let's see how we can solve this uh using the so here what we are doing is first of so here what we are doing is first of all we are using this vector which is all we are using this vector which is our common vector and which will store our common vector and which will store our result and we are initializing with our result and we are initializing with into max because we have to store here into max because we have to store here the minimum occurrence and this is our the minimum occurrence and this is our result which will store a string okay so result which will store a string okay so basically they are correct and not basically they are correct and not string but we are using it as a single string but we are using it as a single character string so how we are doing is character string so how we are doing is first of all uh in our arrays this first of all uh in our arrays this arrays arrays what we are doing is we find this string what we are doing is we find this string first string and what we are doing is we first string and what we are doing is we initialize it with zero so i have this initialize it with zero so i have this vector and i am initializing it all with vector and i am initializing it all with zero now after that what i will do i zero now after that what i will do i will count how many number of characters will count how many number of characters i have in this string and i have in this string and their occurrence so if i have a one time their occurrence so if i have a one time so i will mapping like this so i will mapping like this so once i done this then what i will so once i done this then what i will check i will check check i will check this is my common vector this is my this is my common vector this is my common vector so i will check which is common vector so i will check which is minimum which is minimum and i will minimum which is minimum and i will update my minimum to this common vector update my minimum to this common vector now after doing this what i have to do now after doing this what i have to do all known zero all non zero element from all known zero all non zero element from this common i will store it into my this common i will store it into my result and how do i store this is like a result and how do i store this is like a string i will convert here i am storing string i will convert here i am storing numbers here i am storing numbers and numbers here i am storing numbers and here i will again create make them here i will again create make them string and storing it to my result so string and storing it to my result so now let's understand the time and space now let's understand the time and space complexity part so what will the time complexity part so what will the time complexity so if you see here so the complexity so if you see here so the time complexity of our solution will be time complexity of our solution will be often often because what we are doing is what we are doing here is uh we are running a loop for this and this will be run for we can say of l time l is the length l is the maximum length and here this will be of 26 which i can say of one and it is also i can say this is also awesome this is also awesome so now what i can say here is that my overall time complexity will be of n into l and what will be my uh this space complexity i can say my space complexity of 1 because i use here i use one vector which have the fixed size which is have the fixed size 26 so i can say it is my constant space so i hope you understand the time complexity and the intuition and source code if it helps you do not forget to hit the like and subscribe button thanks [Music]
2024-03-25 13:02:49
1,002
https://i.ytimg.com/vi_w…U/sddefault.webp
1002. Find Common Characters | Using HashMap | Vishal Rajput
6TOcbET2bzI
category is Easy. In this problem, you have to category is Easy. In this problem, you have to design a parking system in which design a parking system in which you have to draw only two umpires, one is Ad you have to draw only two umpires, one is Ad and the other is Ad. These are the only two umpires which are there in and the other is Ad. These are the only two umpires which are there in your parking system. your parking system. your parking system. of parking in it: Big, Medium, Small. What will be given to you in the constructor tomorrow is that Big, Medium and Small. How many stalls do you have for this type of parking? Basically, how many vehicles of this type can you have in your parking system? Yes, then it will be added to you tomorrow in which we will give you what type of tax has come to us, it has come medium, what do you have to tell whether you can make it talk to your parking system or not, basically Is the stall available for tax or not? Is the stall available for tax or not? Is the stall available for tax or not? If it is available then you have to make If it is available then you have to make your stall one mine and your stall one mine and if not available then what type of tax is there. Here we have big type tax here, medium type here and And here again And here again And here again due to big type, in this starting hole, due to big type, in this starting hole, what we will do is we will initialize all these stalls what we will do is we will initialize all these stalls in our variables so that in our variables so that we can do them later and then they came to us, we had we can do them later and then they came to us, we had this stall available to us, so this stall available to us, so we have made provision that we have made provision that we have made provision that and we made this stall made it zero, now we did not have a lot, made it zero, now we did not have a lot, then there then there was no slot, now we saw how many stalls we made by doing it to you, then This system has to be designed This system has to be designed This system has to be designed simply, which we have just discussed, these three will be big, medium and small. We have to store them. To store them, if we want, we can take three variables. We have taken a vector here and Medium and these three Medium and these three Medium and these three stalls have been stored, now we will add it stalls have been stored, now we will add it whenever this AP comes and we will be given the car type. whenever this AP comes and we will be given the car type. What will we have to check by What will we have to check by typing it, whether we have the stall or not, typing it, whether we have the stall or not, if so then note it. if so then note it. if so then note it. i.e. do one mine and return true. Can you advise me to attend the holes whether we have stall of this type i.e. if it is more than zero then do one stall on it If it is 4 If it is 4 If it is 4 seater then what will be our time for it? We are seater then what will be our time for it? We are doing three variables here doing three variables here and check a condition here too, here too if and check a condition here too, here too if off one will come then a will go. We are taking vector but how many types of loan do What will be the size of the vector? If it is 3, then What will be the size of the vector? If it is 3, then What will be the size of the vector? If it is 3, then what will be the
2024-03-19 15:28:41
1,603
https://i.ytimg.com/vi/6…axresdefault.jpg
Design Parking System | Leetcode 1603 | Daily Challenge
ZZ5bOSRxAqM
hi guys good morning welcome back to a new video again a bit Rand in the new video again a bit Rand in the beginning I see a lot of people just in beginning I see a lot of people just in sake of telling the most optimal sake of telling the most optimal solution they forget to tell that it is solution they forget to tell that it is not applicable to anything so in this not applicable to anything so in this we'll see very deep again we'll see two we'll see very deep again we'll see two questions first is sabaris some less questions first is sabaris some less than equal to G has been asked by than equal to G has been asked by Facebook yendex Amazon okay Facebook 73 Facebook yendex Amazon okay Facebook 73 times is last in the last last 6 months times is last in the last last 6 months Google Apple Bloomberg like any company Google Apple Bloomberg like any company you can think of Goldman any company you can think of Goldman any company like it has been asked and you can see like it has been asked and you can see it's a lot and then that comes the it's a lot and then that comes the question of today which is which has question of today which is which has been okay sorry which has been asked by been okay sorry which has been asked by a few companies but still it's exactly a few companies but still it's exactly same or if not I'll tell you what's the same or if not I'll tell you what's the difference but it's more or less same difference but it's more or less same than that of this question which is 560 than that of this question which is 560 okay you can do it by yourself Al exact okay you can do it by yourself Al exact same code you can copy paste I did the same code you can copy paste I did the exact same thing cool so the problem exact same thing cool so the problem simply says again we are doing right now simply says again we are doing right now 9:30 binary subar with some and we also 9:30 binary subar with some and we also do par 560 which isaris some equal to K do par 560 which isaris some equal to K so both simply says one thing that you so both simply says one thing that you are given again the only only difference are given again the only only difference is that in the left side you are given a is that in the left side you are given a binary array in the right side you are binary array in the right side you are given any array okay now let's see the given any array okay now let's see the PO statement you are given binary AR PO statement you are given binary AR nums and an integer called as goal we nums and an integer called as goal we have to return the number of nonempty have to return the number of nonempty sub arrays with a sum goal usually it's sub arrays with a sum goal usually it's always non empty if we are asked for always non empty if we are asked for empty then okay it's just one add a one empty then okay it's just one add a one for empty also but the rest all will be for empty also but the rest all will be nonempty now um and the exact same stuff nonempty now um and the exact same stuff is also told in the right side the only is also told in the right side the only difference I told told you that in the difference I told told you that in the left side which is the problem which is left side which is the problem which is of today it is saying that nums of I is of today it is saying that nums of I is either a zero or a one which means a either a zero or a one which means a binary array on the right side nums of I binary array on the right side nums of I can be positive zero or negative again can be positive zero or negative again that's a plus Factor number can be zero that's a plus Factor number can be zero number can be negative also if it would number can be negative also if it would have been only positive I would have have been only positive I would have said it's exactly same as having a 01 said it's exactly same as having a 01 but it's having a zero also okay AR but it's having a zero also okay AR what's the difference no worries no what's the difference no worries no worri at all there's no difference at worri at all there's no difference at all let's see how we'll solve it again all let's see how we'll solve it again we'll come back to a very basic thing it we'll come back to a very basic thing it just simply ask to return me total just simply ask to return me total number of sub arrays who sum so I'll do number of sub arrays who sum so I'll do exact same stuff I have an array I will exact same stuff I have an array I will find total number of subarrays my total find total number of subarrays my total number of subarrays are n square and number of subarrays are n square and then I will find the sum of those then I will find the sum of those subarrays which is again o of n time so subarrays which is again o of n time so it will become o of n Cub the one basic it will become o of n Cub the one basic for I can tell my interviewer method one for I can tell my interviewer method one is okay approach one is simple Brute is okay approach one is simple Brute Force now a bit optimized Brute Force we Force now a bit optimized Brute Force we have usually seen that if we have a have usually seen that if we have a subar again we used to split okay subar again we used to split okay firstly find the subar and then find the firstly find the subar and then find the sum of that subar but I can just Club sum of that subar but I can just Club them up which means while finding my sub them up which means while finding my sub arrays which are of n Square I can arrays which are of n Square I can parall compute the sum also of that parall compute the sum also of that subar how you can do it for example subar how you can do it for example while you are moving your point moving while you are moving your point moving your pointers in pointers you make sure your pointers in pointers you make sure okay I pointer J pointer I pointer J okay I pointer J pointer I pointer J pointer I pointer J pointer so I'm pointer I pointer J pointer so I'm saying as you have your in okay right saying as you have your in okay right now your sum will be one okay add a one now your sum will be one okay add a one by default your sum is zero add a one as by default your sum is zero add a one as soon as you are at J As you move on your soon as you are at J As you move on your J again for this specific subar the sum J again for this specific subar the sum is one also and that's true as you move is one also and that's true as you move on your J earlier because of the basic on your J earlier because of the basic root Force approach you had to go on to root Force approach you had to go on to the entire subar but now I'm saying just the entire subar but now I'm saying just simply add the component of J which simply add the component of J which means I'll only add my sum of two so now means I'll only add my sum of two so now in the existing sum which was one I in the existing sum which was one I added a two it became sum of three so added a two it became sum of three so with this easily you can get a sub arism with this easily you can get a sub arism i2j again as you move on your J only add i2j again as you move on your J only add the G component so you will get the sub the G component so you will get the sub arism from i2j and that's how you can arism from i2j and that's how you can optimize it and get for all these sub optimize it and get for all these sub arrays the sub aray some parall in N arrays the sub aray some parall in N Square time also okay but still by the Square time also okay but still by the constraints still it will not work like constraints still it will not work like neither for this nor for other problem neither for this nor for other problem again on the right side I have 560 on again on the right side I have 560 on the left side I have what what 9:30 now the left side I have what what 9:30 now coming on back that how to actually coming on back that how to actually improvise it no worries all always read improvise it no worries all always read the problem statement problem statement the problem statement problem statement simply say one thing bro return me the simply say one thing bro return me the total number of sub arrays whose sum so total number of sub arrays whose sum so ultimately I am saying I have to find ultimately I am saying I have to find the subar sum which means I have to find the subar sum which means I have to find again subar is a portion of an array so again subar is a portion of an array so I have to find the range which means in I have to find the range which means in a specific range I have to find the sum a specific range I have to find the sum oh so ultimately my problem boils down oh so ultimately my problem boils down to finding the range sum now we have a to finding the range sum now we have a few algorithms okay we have Spar tables few algorithms okay we have Spar tables we have Fen Tre segment Tre but the we have Fen Tre segment Tre but the basic most basic basic most basic rain sum algorithm is prefix sum for us rain sum algorithm is prefix sum for us now if you know if you don't know what's now if you know if you don't know what's the prefix no worries I'll give you a the prefix no worries I'll give you a quick glance but you should be knowing quick glance but you should be knowing what the prefix Su is because it's very what the prefix Su is because it's very important so prefix sum simply says okay important so prefix sum simply says okay keep the track keep the track again AR keep the track keep the track again AR how how would I know that I have to use how how would I know that I have to use a prefix sum or for for sure you have a prefix sum or for for sure you have not even studied and there's a high not even studied and there's a high chance that you will not even study if chance that you will not even study if you're considering only only uh DSA if you're considering only only uh DSA if you want CP I highly recommend it's a you want CP I highly recommend it's a very short crisp sweet algorithm um very short crisp sweet algorithm um now coming on back how would I know okay now coming on back how would I know okay if you don't have any updates and it's if you don't have any updates and it's very simple you just have to compute do very simple you just have to compute do a pre competition and then find the a pre competition and then find the prefix sum or find the range sum then prefix sum or find the range sum then for sure prefix sum is the best approach for sure prefix sum is the best approach to find the range sum if you don't have to find the range sum if you don't have any updates at all now the prefix some any updates at all now the prefix some simply says one thing keep track and say simply says one thing keep track and say okay my so far again prefix as in the okay my so far again prefix as in the starting part sum starting part sum is starting part sum starting part sum is the perfect sum which means one 1 two the perfect sum which means one 1 two which is the sum is three okay 1 2 three which is the sum is three okay 1 2 three the sum is six six so it is how I'm the sum is six six so it is how I'm keeping track so by default initially keeping track so by default initially the sum is nothing zero then I added a the sum is nothing zero then I added a one which means my sum became a one then one which means my sum became a one then I added one two then it became a three I added one two then it became a three and then I added 1 two three it became a and then I added 1 two three it became a six and R so to compute this I have to six and R so to compute this I have to get the entire row no row simply add get the entire row no row simply add this to get a this simply add this to this to get a this simply add this to get a this that's how you can simply get a this that's how you can simply compute your prefix sum which means compute your prefix sum which means prefix sum of I let's say I am at I it prefix sum of I let's say I am at I it will be nothing but prefix sum of I will be nothing but prefix sum of I minus one which is this Value Plus your minus one which is this Value Plus your nums of I which is this value nums of I nums of I which is this value nums of I that's how you can simply comp a prefix that's how you can simply comp a prefix in O of end time okay when it is done in O of end time okay when it is done how are you saying that it can give me how are you saying that it can give me the range sum bro if I ask you that you the range sum bro if I ask you that you want to find the range sum from here to want to find the range sum from here to here then you can simply say Okay prefix here then you can simply say Okay prefix sum of six minus prefix sum of 1 R in I sum of six minus prefix sum of 1 R in I is here J is here so you are saying that is here J is here so you are saying that prefix sum of J minus prefix sum of IUS prefix sum of J minus prefix sum of IUS one is the answer yes bro that's how you one is the answer yes bro that's how you come the perfect sum you can see 6 - 1 come the perfect sum you can see 6 - 1 is 5 and you can see the range sum is is 5 and you can see the range sum is five if I ask you any any any other five if I ask you any any any other range any other range let's say if I ask range any other range let's say if I ask you the sum of this range J is here I is you the sum of this range J is here I is here so my answer will be J minus IUS here so my answer will be J minus IUS one prefix sum of J prefix sum of J one prefix sum of J prefix sum of J minus prefix sum of IUS one that's my minus prefix sum of IUS one that's my range sum okay 3 minus 0 that's the r range sum okay 3 minus 0 that's the r which is three okay so so far you have which is three okay so so far you have got that okay you can easily figure out got that okay you can easily figure out range sum which is the subar sum in O of range sum which is the subar sum in O of One Time by doing a pre-computation by One Time by doing a pre-computation by using a prefix so now you have got to using a prefix so now you have got to know that okay your know that okay your ultimate your ultimate said this that ultimate your ultimate said this that you have to find goal or are not I know you have to find goal or are not I know goal oh yeah bro you know goal and also goal oh yeah bro you know goal and also you are at again if you're moving in you you are at again if you're moving in you can move in any indexes okay as is as if can move in any indexes okay as is as if I moving in I will be having my J okay I moving in I will be having my J okay imagine okay usually you move by I but imagine okay usually you move by I but as you saw my I is before J so something as you saw my I is before J so something after should be moving right so let's after should be moving right so let's say my J is moving okay which means if say my J is moving okay which means if my J is moving I am at my J pointer so I my J is moving I am at my J pointer so I know what is nums of J and I also know know what is nums of J and I also know what is prefix of J which because I have what is prefix of J which because I have precomputed this so I know my goal which precomputed this so I know my goal which is given in the question I am moving on is given in the question I am moving on my J so I know the prefix of j h I know my J so I know the prefix of j h I know this because I'm at this right now this this because I'm at this right now this is given to me I have to just simply is given to me I have to just simply figure out what is my prefix of IUS one figure out what is my prefix of IUS one no Aran you don't have to figure out no Aran you don't have to figure out what is prefix of IUS one because you what is prefix of IUS one because you already know because see prefix of IUS already know because see prefix of IUS one will simply be prefix of J minus one will simply be prefix of J minus goal this is what you know your ultimate goal this is what you know your ultimate Mak your Mak was that you have to find Mak your Mak was that you have to find out number of again remember your Tim out number of again remember your Tim name was number of sub arrays who some name was number of sub arrays who some so I don't have to find like I can find so I don't have to find like I can find okay this is the this is the prefix sum okay this is the this is the prefix sum of I which I require but I have wanted of I which I require but I have wanted number of those number of those so I'm number of those number of those so I'm just saying I wanted how many of those just saying I wanted how many of those prefix sums are actually available how prefix sums are actually available how many as frequency okay I need the many as frequency okay I need the frequency to be there so what I'll do I frequency to be there so what I'll do I will maintain the frequency frequency of will maintain the frequency frequency of what prefix sums so I will have to what prefix sums so I will have to maintain the frequency of perix sums so maintain the frequency of perix sums so okay if let's say I know this is a perix okay if let's say I know this is a perix sum of I one value which I need to sum of I one value which I need to figure out how many such per Su of IUS figure out how many such per Su of IUS one are there these many number of sub one are there these many number of sub arrays will be there for example for arrays will be there for example for example let's say this was our nums I example let's say this was our nums I simply computed my prefix sum quickly simply computed my prefix sum quickly you can simply see quickly again these you can simply see quickly again these are examples are built by me just are examples are built by me just because in the future I will tell you because in the future I will tell you something great and that's the reason I something great and that's the reason I had to build a bit examples from my end had to build a bit examples from my end now goal is to okay great simply you now goal is to okay great simply you will say bro if Aran I am at this will say bro if Aran I am at this specific index J I Need to Know Okay J specific index J I Need to Know Okay J is this so I know the prefix sum of J is is this so I know the prefix sum of J is this so what what will be the prefix sum this so what what will be the prefix sum of IUS one value which I need to find of IUS one value which I need to find this value what what what will be this this value what what what will be this value this value I know again it is a Al value this value I know again it is a Al to this value I know it is two gold to this value I know it is two gold value was two so ultimately I'm trying value was two so ultimately I'm trying to find prefix sum of IUS one as a zero to find prefix sum of IUS one as a zero so I'm saying okay if I am at this so I'm saying okay if I am at this specific J I want to find zero but specific J I want to find zero but remember frequency of zero so how many remember frequency of zero so how many zeros have occurred previously two two zeros have occurred previously two two zeros have occurred previously which zeros have occurred previously which ultimately indicates us that okay I will ultimately indicates us that okay I will have two subarrays I will have these two have two subarrays I will have these two subarrays and that's how you can simply subarrays and that's how you can simply keep on keep on accumulating your prefix keep on keep on accumulating your prefix sum frequency okay firstly you will sum frequency okay firstly you will compute the some then or you can do compute the some then or you can do everything parall also compute perect everything parall also compute perect some parall compute the frequency of some parall compute the frequency of them also parall I'll show you guys that them also parall I'll show you guys that but yeah if a basic approach you want to but yeah if a basic approach you want to take simply compute the perfect sum then take simply compute the perfect sum then it on the array again and then as you it on the array again and then as you keep on moving keep on keeping track of keep on moving keep on keeping track of the prefix some frequency and then the prefix some frequency and then update your actually okay at this update your actually okay at this specific J what is the frequency of specific J what is the frequency of prefix sum of I minus one which I prefix sum of I minus one which I require and that main number of sub require and that main number of sub arrays we actually be ending at J index arrays we actually be ending at J index cool the code again it's pretty simple cool the code again it's pretty simple again if you want to do a bit more dry again if you want to do a bit more dry run you can do it but I don't think so run you can do it but I don't think so because it's a simple concept of perix because it's a simple concept of perix sum which I explained above and then sum which I explained above and then accumulating that with the concept of accumulating that with the concept of frequency that's a that's the major two frequency that's a that's the major two concept which we will actually club with concept which we will actually club with each other so again I will do it each other so again I will do it everything together which means I everything together which means I compute the prefix sum also parall and compute the prefix sum also parall and also I will be Computing my frequency also I will be Computing my frequency also parall so I had my prefix Samar also parall so I had my prefix Samar okay great I don't know there's one okay great I don't know there's one thing I saw today in lead code that some thing I saw today in lead code that some variables colors was being changed I variables colors was being changed I don't know what's a bug but uh yeah don't know what's a bug but uh yeah that's a bug comment down below what you that's a bug comment down below what you think could have been the bug in this think could have been the bug in this case now um here I keep track of the case now um here I keep track of the frequency that frequency will be of frequency that frequency will be of perect sums now uh you will see that in perect sums now uh you will see that in the very beginning you always have a the very beginning you always have a zero so so zero so so frequency again frequency of zero will frequency again frequency of zero will be one because zero is always there now be one because zero is always there now I keep on going on to all the elements I keep on going on to all the elements of my num as I land on to any element of my num as I land on to any element again increase the perfix sum value as again increase the perfix sum value as you increase the perix Su value okay you increase the perix Su value okay that's done that's great but as soon as that's done that's great but as soon as you are at any specific prefix some you are at any specific prefix some value you have to go and find your value you have to go and find your prefix Su of I minus one so I'll go and prefix Su of I minus one so I'll go and just check okay bro prefix sum of IUS just check okay bro prefix sum of IUS one that is nothing but that again that one that is nothing but that again that is nothing but current prefix sum minus is nothing but current prefix sum minus gold current prefix sum minus go is the gold current prefix sum minus go is the value which I'm looking for and that value which I'm looking for and that from that I have the frequency so I'll from that I have the frequency so I'll search in my frequency not map that search in my frequency not map that prefix sum of prefix sum minus again prefix sum of prefix sum minus again this prefix sum is prefix sum of J which this prefix sum is prefix sum of J which which I was referring because I'm moving which I was referring because I'm moving on to my J this is for J again I don't on to my J this is for J again I don't have to make a new are that's the reason have to make a new are that's the reason I took as a variable right okay to I took as a variable right okay to reduce a bit space space will not reduce reduce a bit space space will not reduce like space complexity will still be open like space complexity will still be open but a bit space will be reduced by this but a bit space will be reduced by this now uh I will simply go and find it if now uh I will simply go and find it if it is there great bro great if it's it is there great bro great if it's there then your frequency of how many there then your frequency of how many times this value was there I will add times this value was there I will add that my number of times in my answer that my number of times in my answer because that many number of sub arrays because that many number of sub arrays will be there okay then ultimately when will be there okay then ultimately when this portion is which means the this portion is which means the contribution contribution of these zeros contribution contribution of these zeros are added then okay bro for the future are added then okay bro for the future purposes this frequency needs to be purposes this frequency needs to be increased for this specific two so I increased for this specific two so I just said frequency of this prefix sum just said frequency of this prefix sum of J increase it by one because okay I of J increase it by one because okay I have encountered two which is a prefix have encountered two which is a prefix Su value so exact same stuff prefix sum Su value so exact same stuff prefix sum of sorry frequency of prefix sum of sorry frequency of prefix sum increase that by one and that's going increase that by one and that's going simply trate and return return back your simply trate and return return back your answer in simply o of n time because answer in simply o of n time because you'll see it's a simple o of n you'll see it's a simple o of n operation everything is a o of n operation everything is a o of n operation which is happening this Loop operation which is happening this Loop I'm saying now again this find is oone I'm saying now again this find is oone operation in an unordered map because we operation in an unordered map because we have used an unordered map which is a have used an unordered map which is a simple hash map so you saw the time we simple hash map so you saw the time we are using is orn but the space we are are using is orn but the space we are actually using is because of frequency actually using is because of frequency we are using a space also of O ofn we are using a space also of O ofn although we reduce the space by not although we reduce the space by not making a prefix Samar but still unly we making a prefix Samar but still unly we are making or using a space of offn now are making or using a space of offn now you might say AR this is the best case you might say AR this is the best case for sure again the exact same code exact for sure again the exact same code exact same code exact same code will work for same code exact same code will work for are this 560 which has been so many are this 560 which has been so many companies it it will exactly work and companies it it will exactly work and and you will be shocked to hear this is and you will be shocked to hear this is a best possible solution for your 560 a best possible solution for your 560 problem best possible solution now problem best possible solution now coming on back um why you specifically coming on back um why you specifically said the best POS for 5 is this not the said the best POS for 5 is this not the best for the this problem this problem best for the this problem this problem is it not the is it not the best um like did you think like did you best um like did you think like did you ever think of one thing I never ever think of one thing I never considered what could have been the considered what could have been the value between these I never considered value between these I never considered in this like in any point of time I I I in this like in any point of time I I I ever asked you what could have been the ever asked you what could have been the value is it matter like will it matter value is it matter like will it matter or not I never I never asked you so now or not I never I never asked you so now to think of that again the interview to think of that again the interview will say can you please improvise it now will say can you please improvise it now you are just shocked how you will you are just shocked how you will improvise it no worries go back to the improvise it no worries go back to the example so again that metaphor is danger example so again that metaphor is danger for the folks again people on the for the folks again people on the YouTube and other stuff they will just YouTube and other stuff they will just teach you they will just teach you but teach you they will just teach you but it's a danger if you don't understand it's a danger if you don't understand this how things work how two pointers this how things work how two pointers how other again I not tell okay I have how other again I not tell okay I have already spoiled but yeah if if you don't already spoiled but yeah if if you don't know how to poin side all that stuff know how to poin side all that stuff works you will end up wasting your time works you will end up wasting your time both in contest and also in an interview both in contest and also in an interview so your Basics should be clear that okay so your Basics should be clear that okay when what to apply that's what we're when what to apply that's what we're going to see now so again that's a going to see now so again that's a danger for those who don't know and they danger for those who don't know and they end up applying anything so what end up applying anything so what happened in this case we saw that we happened in this case we saw that we simply had to find the goal of two so we simply had to find the goal of two so we saw that if we have an simple array then saw that if we have an simple array then I can simply expand this oh expand this I can simply expand this oh expand this can you just remember something expand can you just remember something expand then shrink and then you'll see okay I then shrink and then you'll see okay I just simply shifted this then I shrinked just simply shifted this then I shrinked this did you like can you just recall of this did you like can you just recall of something okay you have a window in something okay you have a window in which you expand the window you shift which you expand the window you shift the window you shrink the window oh that the window you shrink the window oh that seems like a two-pointer and sliding seems like a two-pointer and sliding window again uh both can be used window again uh both can be used interchangeably because it's a window interchangeably because it's a window and the window actually works on and the window actually works on pointers so both can actually be used pointers so both can actually be used but I will say let's say 2.0 sliding but I will say let's say 2.0 sliding window I can use both of them both of window I can use both of them both of them mean same so okay that's a window them mean same so okay that's a window sliding Windows more of the window sliding Windows more of the window remain same but two pointer say windows remain same but two pointer say windows can be sh or increased so now we can EAS can be sh or increased so now we can EAS see okay I can see something I can use see okay I can see something I can use two pointers and I can say okay this is two pointers and I can say okay this is the window for me this is the beginning the window for me this is the beginning window for me again let's erase it this window for me again let's erase it this is the beginning window for me I is here is the beginning window for me I is here J is here I know I know I know that in J is here I know I know I know that in in my two pointers or in the sliding in my two pointers or in the sliding window I keep on increasing my J again window I keep on increasing my J again that's a standard concept that if you that's a standard concept that if you had to use a sliding window or two had to use a sliding window or two pointer so either uh you increase your J pointer so either uh you increase your J at every step and then you can keep on at every step and then you can keep on shrinking your eye so that you can shrinking your eye so that you can actually see how many number of such actually see how many number of such subarray are there so maybe I can just I subarray are there so maybe I can just I know that okay I still have the know that okay I still have the capability to increase my J so I'll have capability to increase my J so I'll have my I here and J here okay then I try to my I here and J here okay then I try to increase my J again but then my sum increase my J again but then my sum became a three Ah that's a pain for me became a three Ah that's a pain for me it should not so I'll just try to shrink it should not so I'll just try to shrink okay if I try to shrink then my array okay if I try to shrink then my array will be become in like this again J is will be become in like this again J is ended so for sure you will try to again ended so for sure you will try to again maybe shrink okay again maybe shrink maybe shrink okay again maybe shrink then IJ became like this now so far then IJ became like this now so far people are thinking okay I got it it's a people are thinking okay I got it it's a sing window I simply apply it bro you sing window I simply apply it bro you missed a lot of things there are many missed a lot of things there are many many many stuff happening here and you many many stuff happening here and you should be knowing when and what to apply should be knowing when and what to apply although I have told a numerous times on although I have told a numerous times on the videos that when to use two pointers the videos that when to use two pointers or maybe like I can again I'm actually or maybe like I can again I'm actually using sliding window here but again using sliding window here but again remember sliding window is is is saying remember sliding window is is is saying the concept that the window remains same the concept that the window remains same you just keep on moving two pointer say you just keep on moving two pointer say Okay window can shrink expand shrink Okay window can shrink expand shrink expand all that stuff usually SL window expand all that stuff usually SL window concept is more used in let's say rabing concept is more used in let's say rabing C building hash and stuff sliding window C building hash and stuff sliding window is more of window remains same but two is more of window remains same but two pointers window can shrink expand shrink pointers window can shrink expand shrink expand but both of them cannot happens expand but both of them cannot happens has hly it means shrinking then has hly it means shrinking then shrinking expanding expanding that's not shrinking expanding expanding that's not s that then it's a simple two pointer s that then it's a simple two pointer sorry then it's a simple Loop for you sorry then it's a simple Loop for you happening now coming on back that I have happening now coming on back that I have already told that in a two pointers how already told that in a two pointers how we usually think of is okay if things we usually think of is okay if things are increasing again when I say things I are increasing again when I say things I mean it can be either array it can be mean it can be either array it can be either sum it is what you want to find either sum it is what you want to find the answer for or maybe it's a hop in the answer for or maybe it's a hop in between for example I'm just thinking of between for example I'm just thinking of a number I just want to apply two a number I just want to apply two pointers on a number maybe the numbers pointers on a number maybe the numbers are increasing maybe I want to find the are increasing maybe I want to find the sum of them for example in this case sum of them for example in this case maybe the sum is increasing Maybe the maybe the sum is increasing Maybe the sum decreases and then decreas from the sum decreases and then decreas from the end so maybe it is decreasing and then end so maybe it is decreasing and then increasing so in the cases when you increasing so in the cases when you think it increases or decreases or think it increases or decreases or increases decreases in that cases it's increases decreases in that cases it's highly likely that you will apply two highly likely that you will apply two pointers now what you we what you mean pointers now what you we what you mean by thing in this case I so you can by thing in this case I so you can simply see the thing what I meant is was simply see the thing what I meant is was your sum for you your ultimate M was to your sum for you your ultimate M was to find the sum so for sum you'll see the find the sum so for sum you'll see the prefix sum as you saw also just to say prefix sum as you saw also just to say the prefix was 1 3 and six so it is the prefix was 1 3 and six so it is increasing har in but elements can be increasing har in but elements can be zero also here okay bro that's true it zero also here okay bro that's true it can be then it can be then same also can be then it can be then same also like okay it can be 1 1 3 and six so like okay it can be 1 1 3 and six so okay when I say increasing I mean non okay when I say increasing I mean non decreasing always okay right okay make decreasing always okay right okay make sure now and how to use two pointers in sure now and how to use two pointers in these cases simple we know that we have these cases simple we know that we have a window remember this fact we have a a window remember this fact we have a window I and j i and J J is always later window I and j i and J J is always later on like that's how I usually do it you on like that's how I usually do it you can also keep I later on now G moves G can also keep I later on now G moves G moves G moves V to simplify stuff moves G moves V to simplify stuff usually have a template of two pointers usually have a template of two pointers that again that's a two pointers in that again that's a two pointers in which we are actually compressing and which we are actually compressing and expanding so while J is less than n n is expanding so while J is less than n n is the size of the window then at every the size of the window then at every step no matter what you will increase step no matter what you will increase your J that's a simple template and and your J that's a simple template and and and but okay which means we at every and but okay which means we at every step I'm increasing my J but I'm saying step I'm increasing my J but I'm saying that if what whatever condition that if what whatever condition satisfies for us that's good I will keep satisfies for us that's good I will keep on moving as it but if some condition is on moving as it but if some condition is not satisfying which means in this case not satisfying which means in this case this condition is some so if I'll keep this condition is some so if I'll keep on moving on j j j some keep on on moving on j j j some keep on expanding that's true it will it will expanding that's true it will it will but as soon as it becomes more I have to but as soon as it becomes more I have to start shrinking stuff so it is a simple start shrinking stuff so it is a simple case that while your any condition any case that while your any condition any condition here in this case it was a sum condition here in this case it was a sum if the sum becomes more than the goal if the sum becomes more than the goal then bro please keep on shrinking which then bro please keep on shrinking which means you will just keep on bringing means you will just keep on bringing your eye this is a basic template which your eye this is a basic template which we use for expanding and shrinking this we use for expanding and shrinking this is usually two pointers which we use now is usually two pointers which we use now in this case you can simply see that in this case you can simply see that your G always increases and then your I your G always increases and then your I moves when you're when you actually have moves when you're when you actually have to improve like decrease or increase to improve like decrease or increase your thing again I'm using a thing word your thing again I'm using a thing word not the actual thing because it is not the actual thing because it is generic so I'm just saying expand I and generic so I'm just saying expand I and compress sorry expand J and compress I compress sorry expand J and compress I expand J compress I I is is compressing expand J compress I I is is compressing my window J is expanding my window and my window J is expanding my window and this to be simplified again you can this to be simplified again you can actually implement it in many other ways actually implement it in many other ways but just to be on the safe side and just but just to be on the safe side and just to build a template out that we don't to build a template out that we don't have to apply our minds much we just have to apply our minds much we just usually have template okay at every step usually have template okay at every step my J will increase and basis of the my J will increase and basis of the condition on the basis of the condition condition on the basis of the condition that okay if my condition has that okay if my condition has violated which which was the sum for us violated which which was the sum for us if it has violated then okay please if it has violated then okay please increase or basically please compress increase or basically please compress your eye now for for for sure for sure your eye now for for for sure for sure for sure we will again that's most for sure we will again that's most important problem is for us is 560 which important problem is for us is 560 which was having which was having that the was having which was having that the elements sorry the elements can be elements sorry the elements can be negative also because it has so many negative also because it has so many companies so that's so it's a prior companies so that's so it's a prior prior problem for us like priority so prior problem for us like priority so what I will do is I will just try to what I will do is I will just try to think okay bro let's try this sliding think okay bro let's try this sliding window because okay it's a sliding window because okay it's a sliding window which means okay it's just using window which means okay it's just using two pointers so for sure I can optimize two pointers so for sure I can optimize my space I remember my space was being my space I remember my space was being used as o of n time will for prob be it used as o of n time will for prob be it can never be reduced but still maybe can never be reduced but still maybe space can be reduced so I might end up space can be reduced so I might end up thinking I will apply two pointers here thinking I will apply two pointers here that's great Aran but you know the hint that's great Aran but you know the hint I told you it's it's not not be applied I told you it's it's not not be applied let's see why I'm why I was seeing it let's see why I'm why I was seeing it again that's for when I had negative again that's for when I had negative elements also so what what will happen elements also so what what will happen in this is that you have your I you have in this is that you have your I you have your again I took any middle middle okay your again I took any middle middle okay currently your state is in now your currently your state is in now your current sum is one you can see - 1+ 1+ current sum is one you can see - 1+ 1+ one it's one now if I ask you bro you one it's one now if I ask you bro you are saying okay if I go by your template are saying okay if I go by your template Aran if I go by your template you will Aran if I go by your template you will say it every step J will say it every step J will increase okay and then and then if your increase okay and then and then if your sum becomes more then your like you will sum becomes more then your like you will say okay your IE will actually increase say okay your IE will actually increase which means you will which means you will compress okay but in that case it was compress okay but in that case it was fixed that my J will increase okay then fixed that my J will increase okay then my thumb becomes more then I will my thumb becomes more then I will compress my eye okay here you will compress my eye okay here you will see my if even if even if currently my see my if even if even if currently my sum is one for sure which is lesser than sum is one for sure which is lesser than my gold so you might end up thinking my gold so you might end up thinking iren for sure for sure which is it is iren for sure for sure which is it is less so it is obvious that I will less so it is obvious that I will increase my J so what you might end up increase my J so what you might end up happening is that okay your I is still happening is that okay your I is still here you will increase your J you can here you will increase your J you can see my sum increased now my sum in see my sum increased now my sum in nothing but three some increase with j nothing but three some increase with j and that's what was happening also okay and that's what was happening also okay bro great then you might end up saying bro great then you might end up saying okay my goal was to so I just end up okay my goal was to so I just end up decreasing my eye I might end up decreasing my eye I might end up decreasing my eye which meanor decreasing my eye which meanor increasing my eye which means increasing my eye which means compressing my eye so if you compress compressing my eye so if you compress your eye okay compressing your eye you your eye okay compressing your eye you see what happened your sum earlier was a see what happened your sum earlier was a three now your sum became a four three now your sum became a four compressing your ey increased your sum compressing your ey increased your sum oh Arin which means which means Arin oh Arin which means which means Arin maybe it is a case because um I was maybe it is a case because um I was having I was I I was compressing wrongly having I was I I was compressing wrongly so what I will do is I will compress so what I will do is I will compress first earlier you were saying okay first earlier you were saying okay expand always always put the J that was expand always always put the J that was what you were doing so maybe I will just what you were doing so maybe I will just go reverse what I will do is I know this go reverse what I will do is I know this is a window so I want to I just want one is a window so I want to I just want one thing okay I know one thing that maybe thing okay I know one thing that maybe maybe after compressing my window like maybe after compressing my window like my sum will increase so I just compress my sum will increase so I just compress okay now my ey is here and now as you okay now my ey is here and now as you can see my Su also increased it has can see my Su also increased it has become a become a two you will end up increasing your eye two you will end up increasing your eye just in the case you thinking maybe your just in the case you thinking maybe your sum will increase now but what if it is sum will increase now but what if it is minus one you increase your eye your sum minus one you increase your eye your sum will again decrease so now it is super will again decrease so now it is super super like confusing that okay you super like confusing that okay you should shrink or you should expand should shrink or you should expand because in expanding also you can because in expanding also you can increase your sum or decrease your sum increase your sum or decrease your sum in shrinking also you can increase sum in shrinking also you can increase sum or degrees of sum so it's a bit both are or degrees of sum so it's a bit both are confusing that is it good to expand or confusing that is it good to expand or it is bad to expand or shring anyways it is bad to expand or shring anyways both will cause confusion so no way I both will cause confusion so no way I will end up in a confusion okay I should will end up in a confusion okay I should expand shring expand shring expanding expand shring expand shring expanding expanding expanding both on inj anything expanding expanding both on inj anything can happen on both sides so it's of no can happen on both sides so it's of no point I will end up having of n Square point I will end up having of n Square algorithm if I use sliding window in algorithm if I use sliding window in this so you saw that I cannot use again this so you saw that I cannot use again just to just to be just to give you a summary because of be just to give you a summary because of negative numbers because of negative negative numbers because of negative numbers I got to know that my sum will numbers I got to know that my sum will actually end up decreasing or increasing actually end up decreasing or increasing decreasing or increasing it can do it decreasing or increasing it can do it can go anyways as long as I move my eye can go anyways as long as I move my eye or anyways the sum can either increase or anyways the sum can either increase or decrease that's the reason I cannot or decrease that's the reason I cannot apply my two pointers because I know my apply my two pointers because I know my graph it can go it it cannot it cannot graph it can go it it cannot it cannot go like this this this it should be go like this this this it should be consistent it should be consistent so if consistent it should be consistent so if my sum will decrease increase decrease my sum will decrease increase decrease increase then for sure I can never apply increase then for sure I can never apply my two pointers so I got to know that my two pointers so I got to know that because of the negative number only I because of the negative number only I cannot apply my two pointers here okay cannot apply my two pointers here okay no worries bro let's come on to the no worries bro let's come on to the existing problem because in the existing existing problem because in the existing problem which was binary samaris we know problem which was binary samaris we know the numbers are binary so numbers are the numbers are binary so numbers are not negative maybe we can apply RN R not negative maybe we can apply RN R maybe we can apply two pointers here maybe we can apply two pointers here let's see again I'll take a very normal let's see again I'll take a very normal again you will see in every problem I again you will see in every problem I always land on to a mid example mid always land on to a mid example mid example because I don't go from very example because I don't go from very scratch because there's no time to go in scratch because there's no time to go in from very scratch and then take a mid from very scratch and then take a mid example always think of a mid example I example always think of a mid example I took a mid example I again this is took a mid example I again this is example which I made now uh my goal is example which I made now uh my goal is to okay so now you will see um let's to okay so now you will see um let's usually you say that okay always expand usually you say that okay always expand oh bro the goal is two your Su right now oh bro the goal is two your Su right now is also two so it's good right it's good is also two so it's good right it's good it's good it's good so you should not it's good it's good so you should not increase rather you should ex like increase rather you should ex like string compress the window so that this string compress the window so that this will be the new window size and this new will be the new window size and this new window again please make sure to listen window again please make sure to listen very carefully because it can be a bit very carefully because it can be a bit confusing so right now your window is confusing so right now your window is this now I'm saying considering this now I'm saying considering considering I go by your fact which considering I go by your fact which means your inance Iran if I go by aran's means your inance Iran if I go by aran's fact Aran always increases his J okay fact Aran always increases his J okay always increases J so now the window always increases J so now the window size becomes this still my sum is two oh size becomes this still my sum is two oh my sum is two now I have the ability I my sum is two now I have the ability I have the ability to compress it so I have the ability to compress it so I will do okay now my sum is two which is will do okay now my sum is two which is the good sum for me so maybe I can try the good sum for me so maybe I can try compressing it okay compress it okay now compressing it okay compress it okay now still my sum is two I'll again try to still my sum is two I'll again try to compress it but I cannot compress it so compress it but I cannot compress it so maybe by so far I saw okay if I increase maybe by so far I saw okay if I increase my J first then I have a chance to my J first then I have a chance to compress it then if I increase my J compress it then if I increase my J first so my possible windows or possible first so my possible windows or possible subar which I will give you as an answer subar which I will give you as an answer will be this one and this one remember will be this one and this one remember this fact so I will put this one and this fact so I will put this one and this one remember this fact and again no this one remember this fact and again no other subar was given by you to the other subar was given by you to the answer but but if I had choosed to answer but but if I had choosed to compress first if I choose to compress compress first if I choose to compress because still I know the sum is two my because still I know the sum is two my goal is two so maybe I can compress it goal is two so maybe I can compress it right now also right okay I'll compress right now also right okay I'll compress it first So my answer the answer which it first So my answer the answer which it gave is it it gave me this one then it gave is it it gave me this one then you might end up saying okay I now I you might end up saying okay I now I cannot compress I'll try to expand it cannot compress I'll try to expand it okay I'll expand it so this one so this okay I'll expand it so this one so this is the answer which you end up giving is the answer which you end up giving your solution even if you follow my way your solution even if you follow my way which is expanding first J or if you say which is expanding first J or if you say okay no I'll compress my I first so you okay no I'll compress my I first so you end up giving this as an answer and this end up giving this as an answer and this as an as an answer so you saw that this one the blue answer so you saw that this one the blue or like the the the the pink one which I or like the the the the pink one which I highlight okay it is covering but then highlight okay it is covering but then if you shrink first then you will get if you shrink first then you will get the top one if you expand first you you the top one if you expand first you you you you will get the bottom one and you you you will get the bottom one and you can do one like either you can do either can do one like either you can do either you can shrink first or you can do you can shrink first or you can do expand first expand first anything you do one thing you will anything you do one thing you will miss oh which means in simple two miss oh which means in simple two pointers cannot be applied here we have pointers cannot be applied here we have to use some other magic and that's the to use some other magic and that's the reason people just tell you oh it's a reason people just tell you oh it's a simple to points apply it bro it is not simple to points apply it bro it is not that simple now we have got the issue that simple now we have got the issue okay we if we start by shrinking then if okay we if we start by shrinking then if we start again let's let's come back we start again let's let's come back okay let's erase this if we start by okay let's erase this if we start by shrinking I hear J here if we start by shrinking I hear J here if we start by shrinking then either my sum will same shrinking then either my sum will same my new sum because you saw my right now my new sum because you saw my right now my sum was right now my sum was two if I my sum was right now my sum was two if I shrink it my sum Still Remains Two or if shrink it my sum Still Remains Two or if it would have been a one so if I shrink it would have been a one so if I shrink it my sum would have become a two like it my sum would have become a two like if right now the existing sum would have if right now the existing sum would have been three so the new sum would have been three so the new sum would have been become a two so I saw that with been become a two so I saw that with shrinking I either my sum will remain shrinking I either my sum will remain same or my sum will decrease my new sum same or my sum will decrease my new sum will either remain same which means will either remain same which means equal or my new sum will actually will equal or my new sum will actually will be less and also the same will go for be less and also the same will go for vice versa that if I expand either my vice versa that if I expand either my sum will increase or my sum will remain sum will increase or my sum will remain same some will remain same and that's same some will remain same and that's the fact this equal to is only possible the fact this equal to is only possible because of zero as a number if zero because of zero as a number if zero would not have been there we would not would not have been there we would not have to even think of any of these have to even think of any of these conditions you have simply applied conditions you have simply applied simple two poters simple expand simple simple two poters simple expand simple compress simple expand simple compress compress simple expand simple compress that's how you would have solved it but that's how you would have solved it but now it is equal to which is causing an now it is equal to which is causing an issue but still but issue but still but still but still it is not that confusing still but still it is not that confusing as what we had previously that because as what we had previously that because in earlier case when we had negative in earlier case when we had negative numbers also expanding or compressing numbers also expanding or compressing anything whatsoever you do you will end anything whatsoever you do you will end up having something different but here up having something different but here in this case I know bro it is either in this case I know bro it is either expanding or compressing which means expanding or compressing which means either my area is like this or either my area is like this or straightforward going up then my sum is straightforward going up then my sum is this or going down that's how things are this or going down that's how things are working okay great so now I got to know working okay great so now I got to know that we can't directly deal with equal that we can't directly deal with equal to sum because I know okay my new sum it to sum because I know okay my new sum it can be less or more so I can indirectly can be less or more so I can indirectly deal with less than equal to sum or more deal with less than equal to sum or more than equal to sum so I actually dealing than equal to sum so I actually dealing with less than equal to sum or more than with less than equal to sum or more than equal to sum and not directly with equal equal to sum and not directly with equal to sum equal to sum I could have tell if to sum equal to sum I could have tell if if I had only positive numbers so I if I had only positive numbers so I cannot do that I will actually have to cannot do that I will actually have to deal with less than equal to sum I what deal with less than equal to sum I what what what you what you what you mean by what what you what you what you mean by that is that okay so as to find the that is that okay so as to find the number of sub array with the sum equal number of sub array with the sum equal to goal you will just simply go and ask to goal you will just simply go and ask bro question bro give me the number of bro question bro give me the number of subar with the sum less than equal to subar with the sum less than equal to goal but you remember you want to find goal but you remember you want to find equal to goal so then you can simply equal to goal so then you can simply Subtract with the number of sub RSM less Subtract with the number of sub RSM less than goal Arian what do you mean by less than goal Arian what do you mean by less than goal like I only know for less than than goal like I only know for less than equal to Pro you can convert this less equal to Pro you can convert this less than goal to nothing but some less than than goal to nothing but some less than equal to goal minus one so this became equal to goal minus one so this became exactly like this it's just goal has exactly like this it's just goal has just reduced by one so I can simply make just reduced by one so I can simply make a function let's name the function at a function let's name the function at most you will see why the function name most you will see why the function name as atmost but let's say I Nam this as atmost but let's say I Nam this function I can simply call okay nums is function I can simply call okay nums is my input array and now my goal is this my input array and now my goal is this specific goal again remember this specific goal again remember this function should return number of function should return number of subarrays with some less than equal to subarrays with some less than equal to your goal then again you will find and your goal then again you will find and go same function with the nums and go same function with the nums and saying goal minus one which is nothing saying goal minus one which is nothing but less than your goal now let's see but less than your goal now let's see how this function will work for us again how this function will work for us again remember remember remember the aim of the question like remember the aim of the question like aim of the specific function number of aim of the specific function number of sub the Su less than equal to goal so sub the Su less than equal to goal so now right now when your in are very at now right now when your in are very at the beginning you know the sum right now the beginning you know the sum right now is one but answer is the number of subar is one but answer is the number of subar less than equal to your sum how many are less than equal to your sum how many are there right now one are there okay this there right now one are there okay this is the one one is the number of Saar is the one one is the number of Saar with the sum less than equal to your with the sum less than equal to your goal and I have showed on the right side goal and I have showed on the right side what that one subar is for you to know what that one subar is for you to know that okay to just help you visualize now that okay to just help you visualize now for sure my J will move again exact same for sure my J will move again exact same concept J will move j will move j will concept J will move j will move j will move I just simply compress it down now move I just simply compress it down now okay J Will moves okay J was zero so okay J Will moves okay J was zero so some will still remain same but my some will still remain same but my answer I increase by plus two plus two answer I increase by plus two plus two is two more sub is added the sum whose is two more sub is added the sum whose sum is less than equal to your goal and sum is less than equal to your goal and the two sub is at one is Zer and one is the two sub is at one is Zer and one is 01 again remember the fact one one one 01 again remember the fact one one one as the subarray was already there okay as the subarray was already there okay now your J will again move again your J now your J will again move again your J will keep on moving at every step no will keep on moving at every step no worries so your sum will increase to do worries so your sum will increase to do again your sum is less than equal to K again your sum is less than equal to K so your answer will be I'll add to plus so your answer will be I'll add to plus three plus three is saying 1 1 0 and 1 0 three plus three is saying 1 1 0 and 1 0 1 three subar is added 1 three subar is added three so again again my J will move three so again again my J will move answer will my sum will still remain answer will my sum will still remain same again I'll simply add again now as same again I'll simply add again now as I was showing you the numbers now I I was showing you the numbers now I showed you what I'm actually adding I'm showed you what I'm actually adding I'm adding J minus I + 1 that's simple okay adding J minus I + 1 that's simple okay 0 1 2 3 so I'm adding 3 - 0 + 1 so I'm 0 1 2 3 so I'm adding 3 - 0 + 1 so I'm adding four four sub which is 0 1 0 0 1 adding four four sub which is 0 1 0 0 1 0 and 1 0 0 1 0 1 0 these four I'm 0 and 1 0 0 1 0 1 0 these four I'm adding when I'm at Che so this is the adding when I'm at Che so this is the number of which I'm adding now I what if number of which I'm adding now I what if you increase your J much more okay as I you increase your J much more okay as I increase my J my sum became a three as increase my J my sum became a three as soon as you know okay if the sum became soon as you know okay if the sum became if the sum became more bro do one thing if the sum became more bro do one thing do one thing bro simply compress your ey do one thing bro simply compress your ey simply compress so so while my sum is simply compress so so while my sum is more than my goal I'll simply compress more than my goal I'll simply compress which means reduce my sum and increase which means reduce my sum and increase my I and that's how compression works my I and that's how compression works and that's how you can simply apply your and that's how you can simply apply your simple logic of two pointers here itself simple logic of two pointers here itself so what will happen in the code so what will happen in the code ultimately firstly you have your i j ultimately firstly you have your i j answer sum and your n while your J is answer sum and your n while your J is less than n again standard template of less than n again standard template of your simple two pointers while your J is your simple two pointers while your J is less than n ultimately in the end less than n ultimately in the end remember increase your J everything will remember increase your J everything will go in between as you are specifically on go in between as you are specifically on the J firstly add the contribution of J the J firstly add the contribution of J because at every step your J is moving because at every step your J is moving add the contribution of J now what if add the contribution of J now what if your sum became more then your goal bro your sum became more then your goal bro simply compress compress the array I simply compress compress the array I I'll keep on compressing the aray make I'll keep on compressing the aray make sure make sure to also put this sure make sure to also put this condition because if you end up condition because if you end up compressing a lot and you surpassed compressing a lot and you surpassed surpassed your eye then you you will end surpassed your eye then you you will end up even increasing it either put in the up even increasing it either put in the condition that I is less than n or put condition that I is less than n or put in the condition that I is less than in the condition that I is less than equal to J like put in anything so that equal to J like put in anything so that your I should stop after a point cool um your I should stop after a point cool um then I'll simply decrease my sum because then I'll simply decrease my sum because I'm increasing my I and then I'll simply I'm increasing my I and then I'll simply keep on moving compressing my eye simple keep on moving compressing my eye simple concept and then answer plus is equals concept and then answer plus is equals to j- I + 1 which is the contribution at to j- I + 1 which is the contribution at the G index number of subarrays which I the G index number of subarrays which I have added at the G index and that have added at the G index and that subarrays is all these subar is whose subarrays is all these subar is whose sum is less than equal to K because sum is less than equal to K because after this Loop any sum I get will be after this Loop any sum I get will be the sum Which is less than equal to K the sum Which is less than equal to K less than equal to my goal and simply less than equal to my goal and simply ultimately return the answer again ultimately return the answer again that's I called this function firstly that's I called this function firstly for my less than equal to goal and then for my less than equal to goal and then for my less than goal which is nothing for my less than goal which is nothing but less than equal to goal minus one so but less than equal to goal minus one so this difference will give me equal to this difference will give me equal to goal value and that's how I can simply goal value and that's how I can simply say my time because I'm using simple two say my time because I'm using simple two pointers my time Isn and space is one pointers my time Isn and space is one because I'm not using any space but because I'm not using any space but remember this is only applicable when remember this is only applicable when the numbers was positive and zero if the the numbers was positive and zero if the number would have negative it is not number would have negative it is not applicable in that because we saw we it applicable in that because we saw we it will end up giving us o of n Square will end up giving us o of n Square solution rather than o of n which will solution rather than o of n which will incre the time and that we don't want incre the time and that we don't want cool I know this video has gone bit long cool I know this video has gone bit long but I wanted to make you understand how but I wanted to make you understand how to think of so that you don't waste your to think of so that you don't waste your time on YouTube on YouTube people will time on YouTube on YouTube people will just tell you do this do this they will just tell you do this do this they will not tell you when to use the two not tell you when to use the two pointers and when not which will pointers and when not which will actually hemper and you might end up actually hemper and you might end up thinking in an interview oh Arian taught thinking in an interview oh Arian taught us the similar problem and I can again us the similar problem and I can again apply two pointers here also sorry uh apply two pointers here also sorry uh yeah s here also and 2. it will not be yeah s here also and 2. it will not be applicable you should be knowing the applicable you should be knowing the basics of when to apply what cool thank basics of when to apply what cool thank you so much goodby take care bye bye you so much goodby take care bye bye Cheers Cheers
2024-03-25 11:31:50
930
https://i.ytimg.com/vi/Z…axresdefault.jpg
930. Binary Subarrays With Sum | 560. Subarray Sum Equals K | Prefix Sums | 2 Pointer LOGIC
ECbgLWIXeMo
Loot Hello Viewers Welcome Back YouTube Channel Score Today Will Be Solving Tracking And Water Before You Start Prepare YouTube Channel Subscribe And Hit Notification Force And Latest Update In This Question In The Given Away With Certain Parts Example 06 2012 Total Arm Hole Example Subscribe Liquid water contains two three one two three idiots so 6 subscription this is this universe minimum of local maximum sleep will win this question is will be hydration from inductive one from near soaked left right left maximum maximum Android maximum and minimum of friends maximum subscribe Total Total Subscribe Button Maximum Maximum Total Total Subscribe Button Maximum Maximum Total Total Subscribe Button Maximum Maximum Subscribe Our Face One Subscribe Our Face One Chittor Se Left Maximum Mirchi Nothing But Chittor Se Left Maximum Mirchi Nothing But One Drops Right No Maximum Is Nothing But One Drops Right No Maximum Is Nothing But 333 For Will Be Taking Minimum Of This 2 333 For Will Be Taking Minimum Of This 2 And Will Be Operating To Total Its Position Where And Will Be Operating To Total Its Position Where No One Will Spread The Deficit In No One Will Spread The Deficit In Wway Top 10 Water Ko Subscribe Button Ki Tum - 52 - 03 But One Improved Total Voters Ki Tum - 52 - 03 But One Improved Total Voters And Continues It's Nothing But One Should Move And Continues It's Nothing But One Should Move Into Position Top Maximum Too Left Is Nothing But Does Into Position Top Maximum Too Left Is Nothing But Does Right Is Three Layer Will Take Right Is Three Layer Will Take Minimum Of This Is Minimum Of This Is Minimum Of This Is selecting it was not good subscribe three subscribe the subscribe the soldiers were given a factor height show will just make soldiers were given a factor height show will just make a variable end for a variable end for convenience and science main convenience and science main video singh bisht pailin for that so video singh bisht pailin for that so first will first will first will Record Of Sex A Voice Mail Control Volumes Milk And Milk All Difficulties In President And Fennel Subscribe 508 121 Is All The Best To That I Plus So Will Be Calling Left This Hello How To Fetch A Jhal Was Was Ki no will be running over lokpal starting from Ki no will be running over lokpal starting from tomorrow morning meeting amar maximum set jo tomorrow morning meeting amar maximum set jo left equal to a minimum of left arm on do jhala height offer ki neeti do english se padhare light show willow Cutting and Write as a torch light of I Tags English Meaning of Votes Rights Will Be Hydration Will Start From I Plus One That I Will Update On Right To That I Will Update On Right To Jhal Ka Jhal Ka Apart From Pradesh Apart From Pradesh I Will Be Adding To Total In Which I Will Be Adding To Total In Which I Will Be Adding To Total In Which ki sampras ko ki sampras ko minimum of minimum of me left kumar 8 - till height me left kumar 8 - till height ki and where present at right under current ki and where present at right under current situation situation ki undercurrent hydration point will be ki undercurrent hydration point will be cutting diet in veins open to 4 plus media cutting diet in veins open to 4 plus media platform tight - site is alarm set ireland uk the song of jhal hai so lb max not minimum cosmetic gender maximum ko whatsapp mein good night jhal gather problem air force with a jhal gather problem air force with a meeting minimum but acid maximum acid meeting minimum but acid maximum acid discus throw ki discus throw ki mujhe time tak hoti mujhe time tak hoti jhal Then Then Then lighter video subscribe and notification lighter video subscribe and notification belt thank you for watching
2024-03-20 09:18:29
42
https://i.ytimg.com/vi/E…axresdefault.jpg
42. Trapping Rain Water | Popular interview problem Leetcode | Competitive programming | CityCoder
WQToaP4AXoY
That welcome too much expressed in the chair and going to explain about fundamental fundamental list superman tourist places contract employee list superman tourist places contract employee in english playlist begum in english playlist begum elements humble subject vision spelling and elements humble subject vision spelling and notes the notes the fair will create unrest north to turn the M.Ed value het the fifth month man tech Unclean Work Fuel And Secondarily E The Patient Tag Archives Welcome Page Will Appear Tunnel This Site Post Templates Hair Oil Yet Another Love U That Bike Hello And Null Hindi S M And Null Hindi S M And Null Hindi S M Lose Everything Under Lokpal Bill Account Shift I Have Just Done Value Bank Statement Of Proven Strike On The That A Legal Advisor And Have Written In The That A Legal Advisor And Have Written In The Statement Proof Of Statement Proof Of A Noble Area Harassment And A This expectation is This expectation is This expectation is newly submitted yes thank newly submitted yes thank you
2024-03-22 11:23:05
234
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 234.Palindrome Linked List
N5i7ySYQcgM
hi everyone welcome back to lead coding i am your host faraz so let us continue i am your host faraz so let us continue solving some more questions on dynamic solving some more questions on dynamic programming programming so this question decode ways is a really so this question decode ways is a really famous interview question it has come so famous interview question it has come so many times in interviews and many times in interviews and this question is going to teach you this question is going to teach you something really important something really important it will teach us how to use recursion it will teach us how to use recursion and then it will teach us how to use and then it will teach us how to use memoization into recursion and then memoization into recursion and then convert it to the bottom of dynamic convert it to the bottom of dynamic programming programming so we will go step by step first of all so we will go step by step first of all let's understand what the problem let's understand what the problem statement is statement is so basically a is mapped to 1 b is so basically a is mapped to 1 b is mapped to 2 c is mapped to 3 and so on mapped to 2 c is mapped to 3 and so on till till z is mapped to 26. now we are given z is mapped to 26. now we are given some digits and we have to tell the some digits and we have to tell the reverse mapping of this we have to reverse mapping of this we have to decode that decode that so for example if we have a a j so for example if we have a a j and f a and f a a j and f the corresponding to this the a j and f the corresponding to this the digits will be digits will be 1 for a 1 for a for j is 10 and for f it 1 for a 1 for a for j is 10 and for f it is is 6. now actually we are given this part 6. now actually we are given this part we are given this part and we have to we are given this part and we have to generate generate all the possible decodes of this now one all the possible decodes of this now one way obviously is this way obviously is this we can treat them as 1 1 we can treat them as 1 1 10 and 6 and then reverse map them 10 and 6 and then reverse map them so it will be a a j and f but there's so it will be a a j and f but there's one more way one more way and that is to consider one and one and that is to consider one and one together together one and zero together and six so for one and zero together and six so for this the decoding is this the decoding is k j and f so we have to tell for a given k j and f so we have to tell for a given digits for a given sequence of digits digits for a given sequence of digits how many d codes can we have how many d codes can we have for a given set of digits how many d for a given set of digits how many d codes can we generate codes can we generate we have to tell the number okay so let we have to tell the number okay so let us see what are the possibilities are us see what are the possibilities are here with us here with us i should take the same example there is i should take the same example there is 1 1 1 0 and 6. 1 1 1 0 and 6. now for this given sequence of digits now for this given sequence of digits what i can do when i have been given what i can do when i have been given this entire sequence i am at the this entire sequence i am at the beginning beginning so there are two possibilities with me so there are two possibilities with me the first possibility is to replace this the first possibility is to replace this one one with a and then generate with a and then generate the d code for the remaining sequence so the d code for the remaining sequence so we can consider a here and 1 1 we can consider a here and 1 1 0 6 corresponding to this i will 0 6 corresponding to this i will generate all the decodes generate all the decodes of course with the help of recursion we of course with the help of recursion we don't have to do anything here we just don't have to do anything here we just have to call recursion have to call recursion on i plus 1 that is starting from this on i plus 1 that is starting from this point point clear okay clear okay so this is one of the possibility so this is one of the possibility now what is the other possibility the now what is the other possibility the other possibility is other possibility is to take these starting two ones together to take these starting two ones together that is 11 that is 11 and corresponding to 11 we will be and corresponding to 11 we will be having k having k so we have k here and we should now so we have k here and we should now call recursion on this part now for this call recursion on this part now for this part our i should become part our i should become i plus 2 okay it should point over this i plus 2 okay it should point over this place so we'll be left with 1 0 6 and we have to generate all the d codes of 1 0 6 with the help of regression of course okay so whatever decodes we have corresponding to 1 1 0 6 we are going to append that in front of a and whatever t chords we have corresponding to 1 0 6 we will append them at the back of k now if we add both these options we will get our answer so we only have to do two things the first thing is to pick up the first number okay and then call the recursion on remaining part and the second option is to pick up the starting two numbers and then call recursion on the remaining part and then add both these together so that is what we have to do now let me just show you how does this recursion work actually you won't have to do this every time because in some time you will have enough practice that you won't have to think that how is it working we'll just write these two steps and that's it but as of now as you want more clarity as as to how this recursion work i will just explain it to you so here again we can either pick the first number so i will replace it by a and then call recursion on the remaining part that is 106. okay or i can take the starting two numbers that is going to give me so if i pick up starting two numbers so if i pick up starting two numbers it's going to give me k and i'll call it's going to give me k and i'll call recursion on the remaining part now again corresponding to one zero six what i can do is i can take the starting one number so if i take starting one number i will replace it with a and then i will be left with 0 6 or i can take starting two numbers that is 1 0 10 10 could be replaced with the help of 10 could be mapped to j so j and the remaining number is 6. now if i want if i expand this one i can take the if i expand this one i can take the starting one number that is 0 starting one number that is 0 but i cannot replace 0 with any of the but i cannot replace 0 with any of the alphabet alphabet as we can see here we are starting from as we can see here we are starting from 1 and 26 there is no space for 1 and 26 there is no space for 0 so from here i will not be able to 0 so from here i will not be able to proceed proceed so in this case simply return 0 y 0 so in this case simply return 0 y 0 because there is no way to generate such because there is no way to generate such a decode a decode all right so let us look at the right all right so let us look at the right hand side in the right hand side what do hand side in the right hand side what do we have we have we have we can take the starting two we have we can take the starting two numbers that is zero six again for zero numbers that is zero six again for zero six we have no mapping so we will be six we have no mapping so we will be returning zero from this returning zero from this as well so zero from both these places as well so zero from both these places so so zero will be returned here zero plus zero will be returned here zero plus zero is zero it will be written here now zero is zero it will be written here now let's see what is the right hand side let's see what is the right hand side this one so here we have 6 and 6 could this one so here we have 6 and 6 could be replaced with f be replaced with f so we will be having f and as we are so we will be having f and as we are done decoding the entire sequence done decoding the entire sequence because now we will be left with nothing because now we will be left with nothing as we are done as we are done decoding the entire sequence we will decoding the entire sequence we will return one from here now one will be return one from here now one will be returned from here returned from here from the left hand side we got zero from from the left hand side we got zero from the right hand side we got one so zero the right hand side we got one so zero plus one plus one one one will be returned back to here one one will be returned back to here now again now again using the same procedure we cannot using the same procedure we cannot decode 0 6 as we were not able to decode decode 0 6 as we were not able to decode it here itself so we will be returning it here itself so we will be returning 0 from this place again 0 1 is 1 so 1 0 from this place again 0 1 is 1 so 1 will be returned here will be returned here okay all right let's move on to this okay all right let's move on to this part part if i want to record one zero six as i if i want to record one zero six as i saw that one zero six could be decode saw that one zero six could be decode into into one of the ways that is j one of the ways that is j and f so i can return simply one from and f so i can return simply one from here here i will not write all these steps such as i will not write all these steps such as a a then taking 0 6 and then taking j and 6 then taking 0 6 and then taking j and 6 will be left will be left so actually these steps are same as this so actually these steps are same as this i will not write the entire thing i will i will not write the entire thing i will simply return one from here so 1 plus 1 simply return one from here so 1 plus 1 is 2 so 2 is the answer for this is 2 so 2 is the answer for this i hope you understand this if you don't i hope you understand this if you don't understand this understand this just hold on a minute i will just tell just hold on a minute i will just tell you how to write the code the code is you how to write the code the code is really simple really simple so what you have to do you have to so what you have to do you have to create a function a recursive function create a function a recursive function and you have to start with i from 0 and and you have to start with i from 0 and then have a string s then have a string s passing it as a reference again you can passing it as a reference again you can see see now as i told you if i am able to now as i told you if i am able to exhaust the entire sequence if i am able exhaust the entire sequence if i am able to reach the end to reach the end so when i is actually equal to s dot so when i is actually equal to s dot size size in this case return one because i in this case return one because i decoded the entire string decoded the entire string otherwise i will create an answer and i otherwise i will create an answer and i will have two options either to pick up will have two options either to pick up the first letter the first letter so how can i do that int so how can i do that int option 1 is equal to s of i option 1 is equal to s of i minus 0 so this is actually going to minus 0 so this is actually going to give me the integer give me the integer of the first digit okay of the first digit okay all right now let us take these starting all right now let us take these starting two numbers so if for that i'll have to two numbers so if for that i'll have to check this condition check this condition if s dot size is smaller than if i is if s dot size is smaller than if i is smaller than smaller than s dot size minus one then only i will be s dot size minus one then only i will be having two numbers at least two numbers having two numbers at least two numbers left in that case left in that case option two is equal to option two is equal to option one multiplied by ten option one multiplied by ten plus s of i plus s of i plus 1 minus 0. plus 1 minus 0. so i have to convert it into integer i so i have to convert it into integer i hope this step is very clear hope this step is very clear option 1 into 10 plus option 1 into 10 plus the next number the next number okay now if option 1 okay now if option 1 is greater than 0 in that case is greater than 0 in that case answer plus equal to answer plus equal to help of i plus 1 s now checking the conditions for option 2 if option 2 is also greater than 0 and option 2 is smaller than or equal to 26 now in this case answer plus equal to help of i plus return answer now let me just call this return answer now let me just call this i hope these steps are very clear to you i hope these steps are very clear to you actually i'm just actually i'm just making these two integers option one and making these two integers option one and option two these two integers are the option two these two integers are the integer representation of these numbers integer representation of these numbers so so for this example option 1 will be 1 and for this example option 1 will be 1 and option 2 will be option 2 will be 11 okay now i will check the conditions 11 okay now i will check the conditions for both of these if for both of these if option 1 is greater than 0 then i can option 1 is greater than 0 then i can proceed i can add proceed i can add this into the answer if option 2 is also this into the answer if option 2 is also greater than 0 as well as option 2 is greater than 0 as well as option 2 is smaller than 26 smaller than 26 then i can decode it okay then i can decode it okay help of zero comma s help of zero comma s and i can simply return it from here and i can simply return it from here let us just try to run this and see if let us just try to run this and see if there are any compilation errors there are any compilation errors option 2 is equal to oops option i will option 2 is equal to oops option i will have to create have to create the option 2 option 2 is equal to option 1 into 10 plus s of i minus okay actually uh this there's a problem the problem is so the error is because of this i have to do i plus i plus 2 instead of i plus 1 i'm jumping two steps aha so here the condition is when i is equal to s dot size but in some cases i might be equal to s or size plus one so in that case this condition will not return from here and it will simply start executing these steps which is obviously wrong so for that i is greater than equal to sort size then i will be returning from here also i should initialize this option to now i am getting correct answer let me now i am getting correct answer let me just try to submit this okay so i was waiting for this error now why am i getting this error so the reason is simple uh we had 0 6 now for 0 6 obviously there is no possibility because we cannot break it down into 0 and 6 neither can we have 0 6 so both these possibilities cannot be mapped back actually there is no d code for 0 6 and there is no decode for 0 and 6 but why are we getting 1 as the answer because when we took option 1 as 0 and we calculated option 2 option 2 was actually calculated 0 multiplied by 10 plus six which is equal to six now option two became six okay in this case in this example we can see here so let me just print it we can see here so let me just print it out option out option two see it is six so that is why this see it is six so that is why this condition is being satisfied but condition is being satisfied but we should also check that option 1 we should also check that option 1 should not be equal to 0 option 1 should not be equal to 0 and option 2 is greater than 0 so these ok let me now submit it and hopefully i ok let me now submit it and hopefully i will be getting tle this time so the time limit is is being exceeded why because we will be having so many repetitions in this so as we can see if we have 1 1 1 1 and so on so what we can do is we can break it as one one one one one one one one one one or we can break it as 11 or we can break it as 11 that is k and one one that is k and one one one one okay one one okay again we can break it as a and 1 1 1 1 again we can break it as a and 1 1 1 1 and then we can break it as k 1 1 and then we can break it as k 1 1 1 yes 1 yes now we will have to compute this again now we will have to compute this again but this is also being computed here but this is also being computed here so these are the reputations again we so these are the reputations again we will have a lot of repetitions here will have a lot of repetitions here so whenever we get reputations we try to so whenever we get reputations we try to store them using dynamic programming store them using dynamic programming what is the what is the state of dynamic what is the what is the state of dynamic programming the state is i programming the state is i actually i is changing in these actually i is changing in these recursive calls so we just have to recursive calls so we just have to memoize this i memoize this i so for that i will create an array so for that i will create an array of size 100 because i can go at max of size 100 because i can go at max still hundred still hundred and dp is of size and dp is of size 100 let me just initialize this with 100 let me just initialize this with something like why i'm taking 101 because of the so i want to initialize this dp so i want to initialize this dp mem set dp mem set dp minus 1 size of dp minus 1 size of dp initializing this with -1 now here if dp of i is not equal to minus 1 otherwise before returning the answer we otherwise before returning the answer we should store dp dpfi so now it is getting accepted so you should not make any global variables so that is why we should not make dp over here we're just making it here now if we if i'm making it here i should i should pass this into this function i should pass this into this function and start dp and start dp and dp here and dp here and here and and here and here see so this is how you solve dynamic programming questions you first come up with a recursive solution the regular solution was very simple we just have two things to consider the first one was to either pick up the first character alone the second thing was to pick up the first and the second character and then to add both of these this was a recursive solution now as we saw in the recursive solution there was a lot of repetition so we just used memoization now after the memorization if you want to convert into the bottom up dynamic programming you can do that as well let me just show you how you can do that so when i is greater than s dot size the answer is dp of let me just make n here int dp of let me just make n here int n is equal to s dot size should be equal to 1 now n could be 100 so i should make this dp of size 102. dp of n plus 1 is equal to 100 dp of n is equal to 1 because anything that is greater than or equal to s or size should be 1 then i will start looking at another conditions so to get the answer for the ith state i need the answer for the i plus 1 in the state and the answer for the i plus 2 state so it means that i should start generating my answers from i is equal to n minus 1 i greater than equal to 0 i minus minus to generate the answer for the if state i need the answer for the i plus one state as well as the answer for the i plus two with state that's why i am going backward now um i should create in option one this is s of i minus zero or maybe i should just copy this entire thing over here paste it over here now instead of calling this over here now instead of calling this recursive function i should just replace recursive function i should just replace it with it with dp dp of dp dp of i plus 1 and i plus 1 and remove this okay remove this okay and here instead of help of this dp of and here instead of help of this dp of i plus 2 other things here this answer should be replaced by dp dp of i plus is equal to this and i should put 0 inside this entire dp and i should put 0 inside this entire dp so for that i can just name set it so for that i can just name set it mem set dp 0 mem set dp 0 sizeofdp and finally what should i sizeofdp and finally what should i return return what should i return as i was returning this help of 0 so i should return dp of 0 no need to write this and we can just get rid of this recursive function now this is bottom of dynamic oops there is some issue option 1 option oops there is some issue option 1 option two what's the problem two what's the problem d okay dp it is giving us correct answer it is that simple to convert it a top down dynamic programming to a bottom up you just have to paste the entire code over here and then just change the recursive function to the state of tp that's it so this is it for this problem if you want more such content in future make sure you hit the like button make sure you subscribe to the channel and hit the bell icon so that you can get the notifications for the latest videos
2024-03-20 13:00:03
91
https://i.ytimg.com/vi/N…axresdefault.jpg
Leetcode 91. Decode Ways
ZLTU9yRTVqY
hey everyone today i'll be going over leak code problem 1743 you restore the leak code problem 1743 you restore the array from adjacent pairs so we have all array from adjacent pairs so we have all this junk this junk but it's actually really simple but it's actually really simple so basically we're given some adjacent so basically we're given some adjacent adjacent pairs array like this adjacent pairs array like this and it's really just edges so node two and it's really just edges so node two is connected to node one uh node three is connected to node one uh node three is connected to node four three to two is connected to node four three to two so and forth and so forth we have to so and forth and so forth we have to come up with an array and restore the come up with an array and restore the array from these edges so if you can array from these edges so if you can look here we're given this and we can look here we're given this and we can come up with this because one is come up with this because one is connected to two that's true here connected to two that's true here two is connected to three uh that's true two is connected to three uh that's true here and three is connected to four and here and three is connected to four and that's true here um so a couple things that's true here um so a couple things to note to note is uh this is always going to work out is uh this is always going to work out and it's always going to be a valid and it's always going to be a valid adjacence pairs which means that uh our adjacence pairs which means that uh our result numbs is always going to be plus result numbs is always going to be plus one length of the adjacent pairs and one length of the adjacent pairs and they actually say that right here um they actually say that right here um it's guaranteed that every adjacent it's guaranteed that every adjacent period elements numbs i and num psi plus period elements numbs i and num psi plus one will exist in the adjacent pair and one will exist in the adjacent pair and it'll say that adjacent pair is size n it'll say that adjacent pair is size n minus one where the uh resulting array minus one where the uh resulting array is of size n is of size n so a couple things we can do right away so a couple things we can do right away is we can have our result which is just is we can have our result which is just going to be a new n of adjacent pairs going to be a new n of adjacent pairs uh dot length plus one uh dot length plus one uh just one more length than that uh the uh just one more length than that uh the next thing we have to do is kind of like next thing we have to do is kind of like build a graph build a graph uh to connect these like edge nodes uh to connect these like edge nodes basically so we have to build a graph basically so we have to build a graph structure and what we'll do how we'll do structure and what we'll do how we'll do that is we'll just have like that is we'll just have like a map of integer to a list of integers a map of integer to a list of integers and just call this graph and just call this graph and this will be a new hash map and this will be a new hash map and we'll just build it up so we'll go and we'll just build it up so we'll go for it edge of adjacent pairs for it edge of adjacent pairs uh we have to like connect them so we uh we have to like connect them so we have to reference the first node with have to reference the first node with the second node and the second node with the second node and the second node with the first node so let's actually do that the first node so let's actually do that so we'll get so we'll get get our default so graph get our default so graph dot get or default the first edge node dot get or default the first edge node and then a new empty array list and then a new empty array list if it doesn't exist yet that's why we if it doesn't exist yet that's why we have to do the getter default thing have to do the getter default thing um um and then what we want to do and then what we want to do and we'll call this list and we'll call this list uh we want to just simply add the other uh we want to just simply add the other edge because it's now enabled to that edge because it's now enabled to that edge right and we have to put it back in edge right and we have to put it back in so let's actually go uh graph.put so let's actually go uh graph.put edge zero edge zero to list to list and let's copy this down because we have and let's copy this down because we have to do it for the other node here to do it for the other node here and let's just go ahead and go like that and let's just go ahead and go like that and let's change that and let's change that and let's change that and let's change and let's change that and let's change that okay so now that we have our that okay so now that we have our structure here we actually have all the structure here we actually have all the nodes that are connected to each node nodes that are connected to each node which means all we have to do is start a which means all we have to do is start a source node which is really just the source node which is really just the node that only has one neighbor every node that only has one neighbor every other node will have two neighbors right other node will have two neighbors right because if we actually look at this because if we actually look at this output here output here like so we'll see that two has two like so we'll see that two has two neighbors one and three three has two neighbors one and three three has two neighbors so we can either start at one neighbors so we can either start at one and four order doesn't matter and four order doesn't matter in this problem in this problem if you look if there's multiple if you look if there's multiple solutions we can return any of them the solutions we can return any of them the pairs can be in any order pairs can be in any order so really we just have to find a source so really we just have to find a source node now node now so how we do that it's the one that has so how we do that it's the one that has only one neighbor right only one neighbor right so let's do a stack for dfs so let's do a stack for dfs and we'll have this just be a stack and we'll have this just be a stack new stack new stack and uh we know that we'll also need this and uh we know that we'll also need this for dfs so we'll just have scene which for dfs so we'll just have scene which is going to be a new hash set is going to be a new hash set and not seen but set and not seen but set and then what we want to do first is we and then what we want to do first is we want to find uh the source node right so want to find uh the source node right so we're going to actually go through we're going to actually go through basically uh for each entry basically uh for each entry which is going to be an integer of list which is going to be an integer of list of integers of integers for each entry in our graph so an entry set here basically the one that has only one neighbor right so if and let's call this entry here so if entry dot get value which is just the list that it's mapped to uh dot size is equal to one that means it's a source node so we can just put this in the stack right off the bat and we can go entry dot get key which is like the starting node and then we can just break and then next what we want to do is we want to iterate through the stack so while not stack is empty uh we can get the curve so we can go stack dot pop uh we're going to put this in the scene so that we don't uh do a cycle and we're going to see add curve and we're going to go basically uh through each child so we're going to go for it child or neighbor you could call it uh let's actually call it neighbor instead so for each neighbor in graph dot get curve uh let's check if we've already seen it so if not scene dot contains key neighbor uh we can add it so we can go stack dot add neighbor okay so everything's good here uh the thing is is we're actually dfs into this but we're not actually filling up the res so what we actually want to do is let's have like some variable here to keep track of where we are at in our result array so uh once we do this once we get our curve we know that this is the current one so we can go um res i and we can also increment it off of that we need to occur and then at the end here we can just go ahead and return res and then i'll re-reiterate some things that might not this actually contains not contains key this actually contains not contains key let's run this and yeah it looks pretty good let's run all the test cases make sure it's fine before i talk and uh let's submit it so let's see what we got here um so it's 68 66 that's actually pretty good um so let's let's just reiterate like exactly what happened here so basically we treated these adjacent pairs of edges we built a graph out of them so we mapped every single node to its list of neighbors then we found the one with only neighbor one which will be a start node and that's because if we actually look at the array we're trying to build the start node should only have one and node should only have one neighbor as well just like an array then what we do is we add the one to the stack that only has one neighbor then we go through the stack just normal dfs you could do this recursively it doesn't matter and we increment some i and we go in order in dfs and we just fill this array so we start at the source node so we know that's the start of the array and then we go to its neighbor that's the next one then we go to that neighbor and then that's that we do this not seeing contains thing because we don't want to have a cycle or anything or add a node we've already seen because each one has actually two neighbors so we don't want to go backwards so yeah uh talking about time and space complexity uh time is actually uh just o of n uh the reason being is we're actually just going through every single adjacent pair an adjacent pair is actually bound to the length of the result array so it's just n uh we just go through that we build it once then we do a stack thing here but since we're actually keeping track of the ones we've seen we only actually process each node once so it's really like 2n which uh results to n and then uh so there's a time a space is actually o n as well for the same reason because we actually have a map and we just fill it up end times with the different nodes so yeah hope this made sense thank you for
2024-03-20 18:10:10
1,743
https://i.ytimg.com/vi/Z…axresdefault.jpg
Leetcode Solution - 1743 Restore the Array From Adjacent Pairs
DpXerXt6ZWM
going to show you how to solve this legal question 199 binary tree right legal question 199 binary tree right side view and it's a median legal side view and it's a median legal question so given root of a binary tree question so given root of a binary tree imagine yourself standing on the right imagine yourself standing on the right side of it return the value of the node side of it return the value of the node you can see ordered or from top to you can see ordered or from top to bottom so a tree look like this in bottom so a tree look like this in example one what the result that they example one what the result that they wanted you to return is the most the wanted you to return is the most the right side view so basically the output right side view so basically the output you can see you want to get is one three you can see you want to get is one three four after running the function that you four after running the function that you write and then the second example is one write and then the second example is one three um three um like like one three the left side is no and then one three the left side is no and then the result they want you to return is the result they want you to return is one three and uh if it's empty just one three and uh if it's empty just written uh written uh uh empty tree and the song constraints uh empty tree and the song constraints here and this is a here and this is a uh interview question asked by um uh interview question asked by um facebook 112 times in the last six facebook 112 times in the last six months definitely a great question to months definitely a great question to practice on practice on so so if you think about this question return if you think about this question return the right side view is not that tricky the right side view is not that tricky but the problem is that if if they want but the problem is that if if they want you to return something like um you to return something like um like a tree like one like a tree like one and then if the left side is two and then if the left side is two and uh three the most the right side of course is one three right the difficult part is that if it's the most right side view on the level it's not on the most right value let's say the child node of two has another child node of four in this case the most the right side of view although the four is on the left side the most because the four there's nothing on the right side so the most the right side is the the most the right side view so in this case that the answer they want you to retrieve is actually one three and four in this case if you imagine a tree that all the connections are connected and this is a question can be solved by both uh breakfast search and developer search but relatively speaking bradford search may be a little bit easier because bradford search is more of the level traversal instead of like that for search but breath depth research you can also do it easily by traverse to the end and you can easily do it recursively if you do i'm gonna show you how to do both ways and if you do using the buffer search what you can do is um you basically append this value to the queue right and then when the cue exists what i wanted to do is i want to pop the um most the right value so like uh like a q let's say i added the or the one to the q and then i want to pop the most the right side of value which is one after i pop this value i want to iterate through each length of q when i do that when i pop the one value after i pop it if the if the child exists i when i pop the one i want to add all its child right when i add a child if two i want to add it like this two three which is basically the next level and then what i wanted to do is i want to write the uh last value in the queue to the end result right so basically something like this and i want to make sure that i write a 3 to the result so previously i've already wrote one and i want to write three to this result and then after that i'm going to continue to pop and add pop the queue and add it to add its child as well then when i'm going to pop the two right i'm gonna add four because four is the only childhood there's nothing on the right side as well and there's nothing else left so then i'm gonna add four uh i'm gonna add a four because four is the i wanna add a last value from the queue to the result so then it's one three four right and then i'm pop the la uh three three does not have any child and then i'm gonna pop the four and a four doesn't have any child either so in the end that the queue is empty then you have the result as one three four and then if you want to do the developer search that for search is that um you want to you can easily do it reversely uh recursively and then if the you want to involve the leveling right because this is level zero when the the base condition is the length of the result equals to the leveling then you can start appending the result so let me write it for you uh lab the length of the result if length of the result equal to the leveling and you can start append the result the reason i'm saying this is because the length of the result at the beginning is zero right and the level started from zero also that's why we can simply just append the one to the end result first and then when you uh do this recursively and you want to run the same dfs function on the on the left node and the right node the tricky part is that you want to start from the right node is because you want to get the most the right view so for uh the child of one in the no right side of the note you want to when you run dfs you want to run this guy that first search first because it will ask you the right value if you run this first and when the length of the result under there's a one um because you the result the length of the result the second time when you run it the length of result equals one right and now this is level one zero here and when you go to three it's level one so that's why you're gonna append the result three here so you wanna make sure when you run the default search you wanna start the right node and then you run the left node that's the only tricky part you're gonna pay attention to and then you just call this that for search function and then you will be able to get the result that you want i'm going to show you first how to do this in code for the buffer search and we want to rule out some uh edge cases if not right and i want to return no and that's one of the example that they give to us for the breakfast search i want to use a i want to implement this queue by using oh can type by using a dq here so that i'm going to first append the real value to the dq before i start and then i'm going to assign a result basically what we need to return here to our list array here so i'll say wow q right and i want to start append the value the value i append in the example that i give to you is that i always append the most the right side of the value to the queue like um like the queue is like a one uh one right i wanna repent uh let's say let's say that you already popped the one and then you have added a three two three in this case if i want to append so q is always um first uh a first in first out so if i wanna uh after i added two right when i start popping from the cube pop left and it always pop through first but in this case i actually wanted to when i add to the result i want to add the most the right side value to the result here so here is how you do it the minus 1 is the last value from the queue and then i want to append its value to the queue that's basically what you need to do um because if you don't append the last value then it will not be able to get the three here and then then i'm gonna go through the iteration for i in um and um and i'm gonna go through each of the i'm gonna go through each of the iteration and i'm gonna uh do uh the iteration and i'm gonna uh do uh the node is q dot pop left i'm still gonna node is q dot pop left i'm still gonna popping from the queue pop popping from the queue pop left every time when i pop a value i left every time when i pop a value i want to add its child when i add its want to add its child when i add its child i'm gonna have to check if the child i'm gonna have to check if the child exists so if no dot left exists child exists so if no dot left exists all right if node.left exists i'm just all right if node.left exists i'm just gonna q dot append gonna q dot append no dot left no dot left and if node alright exists i'm gonna q and if node alright exists i'm gonna q dot dot append append no no dog right but either way every single dog right but either way every single time when you go back to the loop one time when you go back to the loop one more time you will still be able to more time you will still be able to append the most right value and then append the most right value and then while q and then in the end i want to while q and then in the end i want to return the result right return the result right and that's the and that's the breakfast search breakfast search and you can see it's uh it works and you can see it's uh it works and then i'm gonna show you how to do and then i'm gonna show you how to do this in the dapper search like this in the dapper search like recursively recursively and okay okay so uh i want to keep the edge cases so uh i want to keep the edge cases because it's essentially is the same and because it's essentially is the same and i'm going to assign a result here i'm going to assign a result here um i'm going to define our data search um i'm going to define our data search function and i'm going to pass two function and i'm going to pass two parameter one is the root uh the node parameter one is the root uh the node itself and the other one is the level itself and the other one is the level and when i uh and when i uh remember the base case i mentioned is remember the base case i mentioned is that if the length of the result that if the length of the result equals to the level equals to the level that's when i wanted to repent the that's when i wanted to repent the append the result to the to the end the append the result to the to the end the result because at the beginning right result because at the beginning right level level equals zero at the beginning and the equals zero at the beginning and the result equals to this is empty that's result equals to this is empty that's why the first value i will actually why the first value i will actually repent to the end result uh the end repent to the end result uh the end result is actually the root value which result is actually the root value which is 1 in this case and then next time is 1 in this case and then next time when i do it i'll show you the recursive when i do it i'll show you the recursive function and then so function and then so i want to run this recursively right for i want to run this recursively right for the child in the child in um um in two two items right one is the node in two two items right one is the node all right and node.left all right and node.left this is super important that you have to this is super important that you have to make sure you start from node all right make sure you start from node all right because it what it's trying to do is get because it what it's trying to do is get the node.right value the node.right value if you go through the if you go through if you go through the if you go through this recursively you will see that why this recursively you will see that why it needs to start with the node all it needs to start with the node all right because this node all right right because this node all right leveling is when you go through three leveling is when you go through three right and if you want to start the child right and if you want to start the child node three the at that time the result node three the at that time the result equals 1 and the level equals to 1. equals 1 and the level equals to 1. that's the time you're going to append that's the time you're going to append the second result but if you imagine if the second result but if you imagine if you start for child in node.left and you start for child in node.left and doll right if you start from the left doll right if you start from the left and the and the result is one and the um result is one and the um leveling is one also if you append that leveling is one also if you append that result you're gonna happen to end up result you're gonna happen to end up being uh end up appending the node or being uh end up appending the node or left which is the wrong answer so that's left which is the wrong answer so that's why you gotta have to make sure the node why you gotta have to make sure the node all right is on the uh it's the all right is on the uh it's the beginning of the list so if child if the beginning of the list so if child if the child node exists if they have if the child node exists if they have if the one has a child node right i'm gonna run one has a child node right i'm gonna run the default search on the child node the default search on the child node itself itself basically repeating the same thing but basically repeating the same thing but the leveling since i'm down one level the leveling since i'm down one level i want to say level plus one in this i want to say level plus one in this case and then that's it for the data case and then that's it for the data search function and you just wanted to search function and you just wanted to call the developer search on the node call the developer search on the node root node and the leveling star from root node and the leveling star from zero and in the end you return the zero and in the end you return the result and that should be what you are result and that should be what you are looking for essentially okay if you think that this this is helpful please like my video and subscribe to my channel and i'll see you
2024-03-21 14:38:44
199
https://i.ytimg.com/vi/D…axresdefault.jpg
LEETCODE 199 BINARY TREE RIGHT SIDE VIEW PYTHON | BFS and DFS
rD42Ym-WPUM
yes I'll be solving found six five seven called robot returned to origin I called robot returned to origin I promise it's that the robots are the in promise it's that the robots are the in position 0 0 the origin on 2d plane position 0 0 the origin on 2d plane given a sequence of moves judge if the given a sequence of moves judge if the robot ends up at 0 0 after its moves so robot ends up at 0 0 after its moves so the move sequence is represented by a the move sequence is represented by a string and the character moves I string and the character moves I represents the eyes move ballot moves represents the eyes move ballot moves our right left up down robot returns to our right left up down robot returns to the origin after finish the olives moves the origin after finish the olives moves turn true otherwise return false note turn true otherwise return false note that note the way that the robot is that note the way that the robot is facing is irrelevant so right we'll facing is irrelevant so right we'll always make them move it make the robot always make them move it make the robot move right once I will make the robot move right once I will make the robot move left also assume that the magnets move left also assume that the magnets of the robust movement are this of the robust movement are this information move so for example if the information move so for example if the road moves up and down it'll be back to road moves up and down it'll be back to the origin it's but what moves left and the origin it's but what moves left and left it would be to the exposition would left it would be to the exposition would be negative 2 so it would not be in the be negative 2 so it would not be in the same spot so if you haven't given this same spot so if you haven't given this shot pause the video and gotta solve shot pause the video and gotta solve this all right great so hopefully you've this all right great so hopefully you've cut it out so one way I think one way of cut it out so one way I think one way of doing this is that we can keep the tact doing this is that we can keep the tact of the x position and y position of the x position and y position throughout each of the moves and throughout each of the moves and whenever we seem up we'll increase the Y whenever we seem up we'll increase the Y and X or Y position and then obviously and X or Y position and then obviously down we increase the life as well so down we increase the life as well so same thing with left and right whenever same thing with left and right whenever we see the left will decrease to X or we see the left will decrease to X or niversity of life will increase the niversity of life will increase the water X and at the very end if our x and water X and at the very end if our x and y are at the border then we can say that y are at the border then we can say that the robot is back to its original spot the robot is back to its original spot so let's let's first initialize X Y to so let's let's first initialize X Y to be 0 and now wanna loop over all of you be 0 and now wanna loop over all of you if the move is equal to left and the if the move is equal to left and the world has left once and I'll Stephanie world has left once and I'll Stephanie this too right go ahead this too right go ahead that's right and if you move is down that's right and if you move is down then the rule of I had down once and then the rule of I had down once and otherwise the move must be I guess so will increase this else I can just so the very end its back to work if the accent wire is still 0 so I can just return actually y is equal to 0 so looks like it looks for that example looks like it looks for that example attracts me and looks like it's good
2024-03-20 14:54:33
657
https://i.ytimg.com/vi_w…xresdefault.webp
Robot Return to Origin - LeetCode Problem #657
3dCs1ZHDNjM
hey hey everybody this is larry this is me going with q2 of the weekly contest me going with q2 of the weekly contest 247 247 uh cynically rotating uh uh cynically rotating uh grid uh hit the like button hit the grid uh hit the like button hit the subscribe button join me on subscribe button join me on discord and we'll chat about this or discord and we'll chat about this or other contest problems in general right other contest problems in general right after the contest after the contest anyway so for this problem i think anyway so for this problem i think this is actually straightforward in that this is actually straightforward in that they tell you exactly what you they want they tell you exactly what you they want you to do you to do you just have to implement it and the you just have to implement it and the implementation is kind of yucky implementation is kind of yucky uh at least the way that i did it maybe uh at least the way that i did it maybe they'll you know maybe we'll go over they'll you know maybe we'll go over some code that is some code that is quicker later on or uh shorter to write quicker later on or uh shorter to write but but for me in contests i just try to figure for me in contests i just try to figure out you know out you know a consistent way of doing it the only a consistent way of doing it the only key trick is noticing that key trick is noticing that uh k could go up to 10 to the ninth so uh k could go up to 10 to the ninth so you cannot just do a simulation because you cannot just do a simulation because you're just running out of time you're just running out of time so you have to you know and this is not so you have to you know and this is not a hard a hard mathematical thing once you've done it a mathematical thing once you've done it a few times few times which is that you have to take the cycle which is that you have to take the cycle and then mod it by k because then that and then mod it by k because then that will will allow you to um allow you to um yeah that'll allow you to uh allow you yeah that'll allow you to uh allow you to do it to do it but yeah but this is my code i'm not but yeah but this is my code i'm not happy about it to be honest so i'm not happy about it to be honest so i'm not going to going to showcase it too much but i'll go over a showcase it too much but i'll go over a little bit little bit because a lot of it is just copy and because a lot of it is just copy and paste to be honest from i mean paste to be honest from i mean like from itself like and you could like from itself like and you could watch me stop it live during the contest watch me stop it live during the contest and even though i did spend 48 seconds and even though i did spend 48 seconds on q1 on q1 i spent 13 minutes on this one which is i spent 13 minutes on this one which is longer than actually all the other longer than actually all the other problems because i think in q4 i spent a problems because i think in q4 i spent a lot of time debugging lot of time debugging but it's still like you know like i but it's still like you know like i spent a reasonable amount of time but spent a reasonable amount of time but this one i knew like how to do it as this one i knew like how to do it as soon as i opened it and it still took me soon as i opened it and it still took me 13 minutes because it just messed right 13 minutes because it just messed right anyway so this one the way that i anyway so this one the way that i implement it implement it is just by doing this a traversal is just by doing this a traversal of the graph and then just putting them of the graph and then just putting them into a list into a list rotate it k times k mod rotate it k times k mod the length of the array times and then the length of the array times and then put it back into the grid put it back into the grid so that's basically what i did here um i so that's basically what i did here um i think you could probably think you could probably simplify this to to a for loop to be simplify this to to a for loop to be honest honest to like one for loop to have a queen of to like one for loop to have a queen of code but i i was worried about like off code but i i was worried about like off by ones and consistencies and testings by ones and consistencies and testings and stuff like that and stuff like that um it is a little bit tricky especially um it is a little bit tricky especially during a contest time because you have during a contest time because you have to make that to make that judgment of debugging because if i have judgment of debugging because if i have any typos or any weirdness any typos or any weirdness here it's it's going to be a disaster to here it's it's going to be a disaster to debug i'm not going to lie debug i'm not going to lie so that is a risk that i took versus so that is a risk that i took versus writing for loops where writing for loops where it's concise but you still may have bugs it's concise but you still may have bugs and you might still and you might still have to get older like you have to be have to get older like you have to be able to generalize it in a way that is able to generalize it in a way that is maybe hard i don't know but maybe i maybe hard i don't know but maybe i uh if i was you know if i really uh if i was you know if i really am stressed about it i would take this am stressed about it i would take this offline and offline and up solve it later by rewriting this even up solve it later by rewriting this even though i would have the correct solution though i would have the correct solution rewriting this to be cleaner and then rewriting this to be cleaner and then with that process after you do it a few with that process after you do it a few more times you begin to more times you begin to gravitate to the better um mindset gravitate to the better um mindset over time right it's not done in a day over time right it's not done in a day or whatever you just have to kind of or whatever you just have to kind of keep doing it keep doing it anyway so that's basically the idea the anyway so that's basically the idea the idea is simple idea is simple you just go around the grid layer by you just go around the grid layer by layer i start by layer i start by you know the corner from you know you know the corner from you know starting from zero zero one one two two starting from zero zero one one two two and then just and then just rotate it uh i keep track of the things rotate it uh i keep track of the things that we've done to kind of that we've done to kind of keep track of a border i go right down keep track of a border i go right down [Music] [Music] um write down left up um write down left up and then i just put everything in this and then i just put everything in this layers array layers array put it into layers um like an array of put it into layers um like an array of arrays arrays and then i just repopulated later with and then i just repopulated later with the same idea the same idea i just go okay so for each layer we i just go okay so for each layer we start at the corner start at the corner um as we said the actual k that we're um as we said the actual k that we're rotating rotating is going to be the k that is given is going to be the k that is given modded by the size of the modded by the size of the the layer and then you know the layer and then you know and then we just do the actual rotation and then we just do the actual rotation here here um and then we just walk the grid again um and then we just walk the grid again by filling it in this is exactly the by filling it in this is exactly the same code except if i change some stuff same code except if i change some stuff and you watch me solve it live you and you watch me solve it live you actually see me copy and paste it a lot actually see me copy and paste it a lot i'm not proud of that but i am i'm not proud of that but i am transparent about it and like i said transparent about it and like i said you can probably rewrite this later but you can probably rewrite this later but i just want to show you i just want to show you what quote unquote uh first draft of what quote unquote uh first draft of real code works like because once you real code works like because once you have to have to have code that works i mean i know that have code that works i mean i know that on a contest on a contest especially in the contest they have test especially in the contest they have test cases for you but cases for you but but in real life you know if as long as but in real life you know if as long as you get something that's working you get something that's working then now it becomes easier to verify then now it becomes easier to verify your unit testing your unit testing and once you verify your unit testing and once you verify your unit testing then now you can make then now you can make uh end writing more test cases for uh end writing more test cases for example example and then you can now rewrite the code and then you can now rewrite the code and then run it against those unit and then run it against those unit testing again testing again so that you can verify that you still so that you can verify that you still have to write code and that's how have to write code and that's how you know there's no regression and then you know there's no regression and then that's how you make improvements in a that's how you make improvements in a deliberate illustratively kind of way deliberate illustratively kind of way okay um that's pretty much all i have okay um that's pretty much all i have i'm just code like i said i'm not really i'm just code like i said i'm not really happy about it happy about it but it is kind of what it looks like it but it is kind of what it looks like it just you just go down just you just go down you you know you you you take the you you know you you you take the numbers out you do a rotation numbers out you do a rotation and then you put it back in so that's and then you put it back in so that's basically it uh what is the complexity basically it uh what is the complexity you may ask you may ask of course it's linear time uh roughly of course it's linear time uh roughly speaking speaking because they're at least them at most because they're at least them at most end layers end layers um and then for each layer you you do um and then for each layer you you do this this this spiral thing of course the survival this spiral thing of course the survival thing jimdo looks a lot thing jimdo looks a lot confusing for to analyst analyze um confusing for to analyst analyze um it's just linear time right because it's just linear time right because or this this for loop and the spiral or this this for loop and the spiral things combine is linear time because things combine is linear time because you can think about each cell getting you can think about each cell getting looked at once looked at once or twice depending on like boundary or twice depending on like boundary keeping and stuff like that keeping and stuff like that but like constant number of times right but like constant number of times right um and then here um and then here the same thing right um the only thing the same thing right um the only thing that that yeah i mean there's this thing which is yeah i mean there's this thing which is a little bit awkward but again that's a little bit awkward but again that's linear in the size of the input linear in the size of the input no matter what because that's bounded by no matter what because that's bounded by the length of the the length of the layer uh size so all this again is layer uh size so all this again is linear and when i say linear by the way linear and when i say linear by the way just to be clear is rows times columns just to be clear is rows times columns people you know sometimes use n times m people you know sometimes use n times m and then they say like oh n times m or n and then they say like oh n times m or n squared so you know it's quadratic squared so you know it's quadratic quadratic on the length of the side quadratic on the length of the side which is true which is true but linear in the size of the input but linear in the size of the input which is what o n refers to which is what o n refers to um in this case or more uh um in this case or more uh if you want to be pendant about it uh if you want to be pendant about it uh but yeah um but yeah um that's basically it uh that's why i have that's basically it uh that's why i have the code i don't know i mean i keep the code i don't know i mean i keep showing the code but showing the code but it really is just sometimes you're gonna it really is just sometimes you're gonna get these problems get these problems in contests or life you just have to in contests or life you just have to grind through it grind through it uh some people did get it really quickly uh some people did get it really quickly though so though so five i mean even the top people got in five i mean even the top people got in like six seven minutes and it's the like six seven minutes and it's the longest problem give or take longest problem give or take so i don't you know don't feel bad about so i don't you know don't feel bad about it but sometimes it but sometimes in life you just have to do the hard in life you just have to do the hard stuff and the hard stuff is doing stuff and the hard stuff is doing uninteresting stuff uninteresting stuff sometimes uh anyway uh that's all i have sometimes uh anyway uh that's all i have for this for now for this for now you can watch myself live next this is this seems like it could be k is 10 to the nine k is 10 to the nine i mean this isn't hard it's just i mean this isn't hard it's just annoying this is going to be like a 15 minute [Music] two so um oh 8 12 16 but i'm not getting that right oh this is such a mess i feel like there's definitely a better way to do this oh man i don't even think has to go back to nine and five i'm has to go back to nine and five i'm missing the nine and the five so oh this is five six seven eleven ten okay okay what a mess uh what a mess what a mess what a mess what a mess what [Music] uh 10 20 40 30 24 12 20 11 10 16. it seems okay it looks okay let's give it some it okay it looks okay let's give it some it okay i knew that was a good hey everybody i knew that was a good hey everybody thanks for watching thanks for watching uh hit the like button to subscribe and uh hit the like button to subscribe and join me in discord again join me in discord again where we just hang out and chat about where we just hang out and chat about contests and contests and problems and stuff like that uh i i just problems and stuff like that uh i i just like having people like having people talking the uh shop you know because talking the uh shop you know because this is my hobby this is my hobby anyway um yeah hope you enjoyed this anyway um yeah hope you enjoyed this video video so yeah uh have a great sunday have a so yeah uh have a great sunday have a great rest of the day great rest of the day or if you're watching it later just have or if you're watching it later just have a great week month whatever you need to a great week month whatever you need to do do stay good stay cool and to good mental stay good stay cool and to good mental health and i'll see you later bye bye
2024-03-25 13:03:29
1,914
https://i.ytimg.com/vi/3…axresdefault.jpg
1914. Cyclically Rotating a Grid (Leetcode Medium)
ZpbCF3MPXzQ
hey hey everybody this is Larry this is day 28 I believe of the liko day day 28 I believe of the liko day challenge hit the like button hit the challenge hit the like button hit the Subscribe button join me on Discord let Subscribe button join me on Discord let me know what you think about this me know what you think about this problem and this thing my assume is a problem and this thing my assume is a little bit big but yeah uh hit the like little bit big but yeah uh hit the like button hit a subscribe I always say that button hit a subscribe I always say that oh man I am just having I don't know oh man I am just having I don't know well either way then hit the like button well either way then hit the like button again hit the Subscribe well unless that again hit the Subscribe well unless that unclicks it anyway uh yeah do what you unclicks it anyway uh yeah do what you need to do uh today's problem is 1962. need to do uh today's problem is 1962. two we move stones to minimize the total two we move stones to minimize the total uh we have about a week left of the year uh we have about a week left of the year so hope you are having a good uh so hope you are having a good uh well I don't know for me the Year's been well I don't know for me the Year's been a little bit rough I hope y'all just a little bit rough I hope y'all just have a good the rest of the year and have a good the rest of the year and maybe you know 2023 will be a little bit maybe you know 2023 will be a little bit better better um do I have the weekly today no that's um do I have the weekly today no that's tomorrow I could never tell when it kind tomorrow I could never tell when it kind of comes out okay of comes out okay uh so yeah so let's see so we have piles uh so yeah so let's see so we have piles an energy K you want to do K times do an energy K you want to do K times do you want to take any powers and remove you want to take any powers and remove half of it half of it um and we moved four of it so that means um and we moved four of it so that means we keep the ceiling uh and then okay we we keep the ceiling uh and then okay we turn the minimum possible total number turn the minimum possible total number of stones we move remaining after of stones we move remaining after applying K operations okay did we do applying K operations okay did we do like uh I don't remember that was the like uh I don't remember that was the premium one that I did yesterday but premium one that I did yesterday but this just seems to be so this just seems to be so you know the logic here would be to kind you know the logic here would be to kind of think for what what is the operation of think for what what is the operation that you want right so to minimize the that you want right so to minimize the pot the the total number of stones pot the the total number of stones afterwards what you want is to take the afterwards what you want is to take the one with the most Stones like in a one with the most Stones like in a greedy way right and greedy way right and um you want to take one of the most um you want to take one of the most stones and then take you know we move stones and then take you know we move half of it and in this case you can half of it and in this case you can apply it multiple times so these are the apply it multiple times so these are the two things we have for this farm right two things we have for this farm right uh keep getting the Max K times and then uh keep getting the Max K times and then uh I guess put it back in but yeah right uh I guess put it back in but yeah right so so um with some experience you'll be able um with some experience you'll be able to quickly identify that this is what to quickly identify that this is what you want from a heap so let's um but you want from a heap so let's um but that's basically it really so let's that's basically it really so let's let's get to it let's get to it um you can maybe do some hipify and um you can maybe do some hipify and technically that's slightly faster but technically that's slightly faster but uh I just want to kind of write it out uh I just want to kind of write it out to be clear to be clear maybe I don't know but yeah so for X in maybe I don't know but yeah so for X in Pius uh we want to Pius uh we want to we want to push it to Heap and in this we want to push it to Heap and in this case case what we actually want is what we actually want is we want to sort by Max right and I I we want to sort by Max right and I I think in pipeline is I think in pipeline is I really wish they have like a Lambda really wish they have like a Lambda thing for push and whatever in general thing for push and whatever in general but because they don't have a cheap data but because they don't have a cheap data structure this is just a heat class structure this is just a heat class operating on an away with doing variants operating on an away with doing variants and assumptions and assumptions um it's a little bit weird so the way um it's a little bit weird so the way that I always short-handed is just by that I always short-handed is just by using the subtraction because then now using the subtraction because then now you have to minimize you have to minimize um yeah you want to minimal minimize all um yeah you want to minimal minimize all the um the um this is a Min Heap in Python so now you this is a Min Heap in Python so now you have all the Macs because it's the have all the Macs because it's the negative right and then now so while negative right and then now so while K is greater than zero K is greater than zero and you could do the two ways you can do and you could do the two ways you can do it now I suppose and I'm just you know it now I suppose and I'm just you know depends on the day maybe I would do it depends on the day maybe I would do it the other way but for example you could the other way but for example you could have the total count and then you could have the total count and then you could subtract it after you pop or you could subtract it after you pop or you could just not you know trust yourself or just not you know trust yourself or something like that that at the end something like that that at the end it'll be good so then you could just sum it'll be good so then you could just sum it up because some in this case is a it up because some in this case is a very cheap operation if you have to do very cheap operation if you have to do if the if the you know with these operations on you know with these operations on uh as trivial like if you have if you uh as trivial like if you have if you run the analysis or the the time complex run the analysis or the the time complex analysis and it's expensive to do analysis and it's expensive to do certain things then you may lean one way certain things then you may lean one way or the other in this case it doesn't or the other in this case it doesn't really matter so yeah so while K is really matter so yeah so while K is greater than zero greater than zero we want to get uh next from we want to get uh next from he pop of H and of course that's just he pop of H and of course that's just you know flip it back to the right sign you know flip it back to the right sign first first um or maybe we could just do it this way um or maybe we could just do it this way I suppose and then now you want to I suppose and then now you want to remove half of the thing right so okay remove half of the thing right so okay so you remove this and then now we we so you remove this and then now we we push it back into the Heap for future push it back into the Heap for future use say and again this is negative X use say and again this is negative X um and then at the way n um and then at the way n well you had to subtract one otherwise well you had to subtract one otherwise that's sad I guess we could have done that's sad I guess we could have done this in a for Loop this in a for Loop actually actually um I'm just very used to lighting it um I'm just very used to lighting it that way for whatever reason and then that way for whatever reason and then just some of the Heap and that's pretty just some of the Heap and that's pretty much it much it is what I would say if it's right but I is what I would say if it's right but I forget that uh we have negative numbers forget that uh we have negative numbers so uh yeah uh so uh yeah uh yeah there are no negative numbers I yeah there are no negative numbers I think I'm just absolute test though or think I'm just absolute test though or maybe even just negative really maybe even just negative really um I forgot about that but uh yeah um I forgot about that but uh yeah um you can also just pop each item but um you can also just pop each item but this is I guess linear let's give it a this is I guess linear let's give it a quick Summit and hopefully I didn't miss quick Summit and hopefully I didn't miss like a zero case or something like that like a zero case or something like that might I get a wrong answer might I get a wrong answer a year ago oh because of this thing I guess oh because of this thing I guess no oh because of that thing and I forgot to put it back into the thing so uh because it popped and then you forgot to put it back in okay silly mistake from a year ago but yeah um what is the complexity here right so I guess this is kind of optimal uh for I guess this is kind of optimal uh for that reason but let's see actually I don't know I am relatively sure it is but um yeah so I mean you could replace this with hipify and hipify like if your your library has it is you go to out of N I believe uh the way that I did it though is going to be uh and login because it's basically you know each one takes a login and then there's n of them right so yeah um and here this does K log n operations for obvious reasons uh there's K iteration and each one does again twice so it's Kayla again so in total um this is just going to be this press and again uh time and off and space just for the Heap um of course like I said you could reduce this to n and it'll be like this if you do a hit provide um and of course this is just a linear uh iteration to get a sum oh cool I think that's what I have for this one let me know what you think let me know if you have any struggles or whatever um that's what I have with this one so let me know what you think so stay good stay healthy to good mental health I'll
2024-03-25 13:31:32
1,962
https://i.ytimg.com/vi/Z…axresdefault.jpg
1962. Remove Stones to Minimize the Total - Day 28/31 Leetcode December Challenge
qFtPxGyy8Ng
And listen hello everyone welcome to my channel also in this video you will be cleaning in this video you will be cleaning this problem minimal changes to make an this problem minimal changes to make an alternating by ministry of mines alternating by ministry of mines videos winters problem entertainment and videos winters problem entertainment and print and you think absolutely taste print and you think absolutely taste selection most of the problems yes-yes that muni selection most of the problems yes-yes that muni data has data has data has Alternating Okay So Alternating Him Perfect Minimum Number Of Steps Should Stand Divided They Came Back And Chief And But Characters Withdrawal On Buff So Lets And Disabled And Lets Switch More Builder 2016 Under 101 Of Success MP3 The Meanwhile Greatest Benefit Characters Can Solve Work In The Alternating Possibilities That Can Be Possible How Sweater Intestine Alternating O King Soft Office Meeting Attend Computer Apni Life Is 1018 Can Be Easy Alternating Like This 04 2014 Inheritance Year Old Lovers Back 120 Hungry Can Hear Sunavai Fikar Operations at minimum over that supposed to convert I just try into this experiment can refer to other test now subscribe this mixture matching matching will have to take one subscribe channel subscribe suicide subscribe Did Due To Did Due To Did Due To A Gy Saffron Ki Problem No A Gy Saffron Ki Problem No Problem No Problem Subscribe Subscribe My Channel if you liked The Zandu Ka Fold Point Iodine and Iron Test Zandu Ka Fold Point Iodine and Iron Test Size Part Plus Scientist Da Know What IF YOU HAVE Size Part Plus Scientist Da Know What IF YOU HAVE A TEST FOR A TEST FOR A TEST FOR all the evening 100 numbers to subscribe my channel and please equal to receive new updates basically then indexes key and exact position and decoration returned 621 Water person in the country and number operations Water person in the country and number operations Water person in the country and number operations ok 18 on st kitts akbar subscribers ok 18 on st kitts akbar subscribers * is equal to what is the correct * is equal to what is the correct questions 101 subscribe kare subscribe kare questions 101 subscribe kare subscribe kare a point in this world will be happy avengers love quotes for the second class for Pe Pe Pe alternating jaswant singh friend 20 seconds alternating jaswant singh friend 20 seconds with this subject seconds always given with this subject seconds always given injections ruby ​​and when it is 2018 all and men injections ruby ​​and when it is 2018 all and men also time so and all events superintendent of police also time so and all events superintendent of police p 09 p 09 and king vaishno devi video edit like and king vaishno devi video edit like 0067 and even superintendent of police 2000 have 0067 and even superintendent of police 2000 have been been That End All And Push Was Not Satisfied And I That End All And Push Was Not Satisfied And I Will Be Implemented By Second Will Be Implemented By Second Operations Next King Operations Next King 202 Debit The Problem 16 Why Have Two 202 Debit The Problem 16 Why Have Two Retail Pack Twitter The Minimum Of Just One Retail Pack Twitter The Minimum Of Just One Mobile Silent Test Match Against Tower Mobile Silent Test Match Against Tower Use Testis 102 Correct Knowledge Submit Attempt Use Testis 102 Correct Knowledge Submit Attempt Working So Let's Working So Let's Working So Let's subscribe this Channel Thanks and have a subscribe this Channel Thanks and have a nice day
2024-03-22 12:31:26
1,758
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 1758. Minimum Changes To Make Alternating Binary String | Weekly Contest 228 | Explained
qvz3bcvblJA
welcome to june's leeco challenge today's problem is maximum units on a today's problem is maximum units on a truck truck you are assigned to put some amount of you are assigned to put some amount of boxes onto one truck boxes onto one truck you are given a 2d array box types where you are given a 2d array box types where box types box types i contains the number of boxes and the i contains the number of boxes and the number of units per box number of units per box now the number of boxes is the number of now the number of boxes is the number of boxes of of this type boxes of of this type and the number of units per box is the and the number of units per box is the number of units in each box number of units in each box of that type you're also given an of that type you're also given an integer truck size which is the maximum integer truck size which is the maximum number of boxes that you can put number of boxes that you can put onto the truck you can choose any of the onto the truck you can choose any of the boxes to put on the truck as long as the boxes to put on the truck as long as the number of boxes does not number of boxes does not exceed truck size return the maximum exceed truck size return the maximum total number of units that can be put on total number of units that can be put on the truck the truck so what that means is we want to get the so what that means is we want to get the maximum number of units maximum number of units regardless of type so we want to regardless of type so we want to maximize that while fitting as many maximize that while fitting as many boxes as we can onto our truck boxes as we can onto our truck so there's really no reason to so there's really no reason to complicate this if we wanted to complicate this if we wanted to do this like manually what would we do do this like manually what would we do we would take we would take the boxes with them the most units and the boxes with them the most units and put those all put those all onto the truck until we run out of space onto the truck until we run out of space or we finished all the boxes so to do this i think the best way would be to sort our boxes and types by by descending order of the total number of units per box because obviously we want to put the boxes with the most units onto our truck and then we'll just iterate down and try to fit as many boxes as we can so let's begin by first sorting our box types and we can use a lambda function say key equals lambda x which is going to be the second item on our list and we're going to make that negative to make it descending okay so now we have um we're gonna have to keep track of the capacity which is how many boxes that we put on so far it starts with zero i guess number of boxes and the i guess number of boxes and the number of units in box types what are we going to do well generally we'll be just putting as many boxes as we can right but keep in mind that we have a certain number of boxes we might not be able to put put in all those boxes into our truck depending on the truck size so what we'll do is check to see if we have enough space to begin with so we'll say pass well i guess we'll keep track of it pass well i guess we'll keep track of it in truck size we'll say truck size in truck size we'll say truck size if truck size is less than the number of boxes well actually we'll start with if it's well actually we'll start with if it's greater we'll say if it's greater or greater we'll say if it's greater or equal to the number of boxes we have equal to the number of boxes we have then all we need to do is first decrease then all we need to do is first decrease from our from our truck size however many boxes there are truck size however many boxes there are and we need to add to our capacity and we need to add to our capacity box times units now otherwise box times units now otherwise if we find that we don't have enough if we find that we don't have enough truck size for all the boxes in this truck size for all the boxes in this unit type unit type we're going to try to fit as many as we we're going to try to fit as many as we can which would just be can which would just be however many we have left our truck size however many we have left our truck size right so that would be capacity right so that would be capacity uh plus equal truck size times uh plus equal truck size times units and make sure to break here units and make sure to break here because after that we've technically run because after that we've technically run out of out of space in our truck size and i just space in our truck size and i just returned up the capacity returned up the capacity and that would be it let's see if this and that would be it let's see if this works works okay that looks like it works so submit okay that looks like it works so submit it there we go accepted there's certainly ways that you can clean up this code but it's probably the most optimal one time complexity wise it's going to be n log n and we go over this just n times so one thing that we've been able to avoid here is doing a while loop in here running it multiple times for every single box we don't need to do that we just need to see if we have enough space and then just multiply that by the number of units and if we don't then however much space is remaining multiply that by the number of units and add that and break it okay thanks for watching my channel remember do not trust me
2024-03-20 15:09:40
1,710
https://i.ytimg.com/vi_w…A/sddefault.webp
Leetcode - Maximum Units on a Truck (Python)
772231FilDE
hello and welcome to my channel so let's uh today let's look at the litco 96 uh today let's look at the litco 96 unique binary search tree unique binary search tree given integer and return the number of given integer and return the number of unique psts which has exactly n nodes of unique psts which has exactly n nodes of unique values unique values from 1 to n from 1 to n so the first example is a 1 n is 3. so the first example is a 1 n is 3. the number of unique binary is five the number of unique binary is five second second second example is one n is one second example is one n is one the number of unique binary search trees the number of unique binary search trees is one is one so the n is between one and nineteen so the n is between one and nineteen um so this question we can use a dynamic um so this question we can use a dynamic programming programming we can define a we can define a dp dp where dpi is represent to where dpi is represent to a number of unique [Music] [Music] for which has exactly i nodes so the this is to define so one and n one and n so so then we want to initialize the this so then we want to initialize the this so the dp0 the db 0 is actually there is the dp0 the db 0 is actually there is only one only one it's it's a it should be one because uh it's it's a it should be one because uh empty it is also empty it is also a uh like uh now is also a tree so we a uh like uh now is also a tree so we can can um so then we needed to have the the um so then we needed to have the the equation equation so the dpi is uh so the dpi is uh will be the sum of dp will be the sum of dp j minus 1 j minus 1 times dp times dp i minus j i minus j so so where the where j will be so so where the where j will be between one the so the this equation we can actually so the this equation we can actually think about uh we we are think about uh we we are we are either reading through all the we are either reading through all the possibilities so one when the tree is using know the one root and the one the tree is using node two as root and then like a such such until like you are using i as a root so we are adding all those together uh so it will be the uh the possibility of like a i nodes so and uh for example also like a for using 2 as a root node we actually have everything larger than 2 will be on the right side everything smaller than 2 will be on the left side on the left side there is a like dp1 on the left side there is a like dp1 which is 2 minus 1 which is 2 minus 1 is a dp1 of uh is a dp1 of uh possibility and on the right side that possibility and on the right side that will be dp will be dp i minus two so here j is two so uh in the in the equation so actually we need to multiply this too which will be the uh the number of unique pst uh using two as a root node root value so uh so actually then we i that's how we got the this transition function so the time complexity will be over n square and the space let's let's start writing the code so we define an n plus one length dp and then define dp uh initialize dp0 as well and then we can iterate i and j so the then we are we can we can just do dpi update the dpi j minus 1 times dp i minus j and then in the end just to return the dp let's check if let's check if okay okay yeah so okay yeah it passed so so this concludes today's session so if you have any question please let
2024-03-20 13:40:16
96
https://i.ytimg.com/vi/7…axresdefault.jpg
Leetcode 96. Unique Binary Search Trees (Daily Challenge 11/8/2021)
Y1EKfMXlnCo
Hai Everyone So Today I Will Like To Share The Problem Ka The Daily Cheat Code Challenge Problem Ka The Daily Cheat Code Challenge Linked List You Can Read The Problem Statement From Her The D Screenshot Of D C Plus D Screenshot Of D C Plus Solution To This Solution To This Problem It is note using other express then the time complexity of this approach will also be values, values, then we would have done the linked list which will create the time then we would have done the linked list which will create the time but after that when we will do the get random function tomorrow. but after that when we will do the get random function tomorrow. We just generated a random number We just generated a random number and returned its and returned its value to the index, so it becomes one of one. value to the index, so it becomes one of one. In this approach, the base complexity of n is reduced you can see. you can see. you can see. percentage i thi value will be zero till i minus and if we do plus one then all the value will after that if x = i it becomes that after that if x = i it becomes that means if the value of means if the value of Only then we change the rest Only then we change the rest and it has that value and if it does not happen then we shift the same t to the number. For the problem, number. For the problem, value A would be 121 meaning why the probability should be which is head and it will be definitely tight then the initial value of clarity, the value will increase that if the value of this condition matches then then brother you will be there, now what was the race i.e. if brother you will be there, now what was the race i.e. if X is not equal, you have come, then what will be We will flood ahead of the loop. Okay, so what is the probability that the saw in the last how that the probability saw in the last how that the probability is one by one. In this how we saw here that in this race one can only end We will update the rest. We will update the rest. is fine and if we want the recipe to be done then what will be its probability. The value of rest will be reached when the value of x will be reached because then we will update If it is from the value then its If it is from the value then its We know We know that we update it and what is the it must be pointing to the right, so in titration, If the condition matches If the condition matches If the condition matches then we will sign the race by 3 [Praise] Right in the [Praise] Right in the first edition there was no choice, first edition there was no choice, in the second edition we had a raha in the second edition we had a raha ki P Rijiju tu ki probability a jati ki P Rijiju tu ki probability a jati hai to to tu one, then its probability is one. We know this because we are on the third attrition, otherwise we would be coming from the second attrition, so if Okay, Whatever is the value of I then the probability is one by one or if you are the power then we somehow or if you are the power then we somehow insure through family technique insure through family technique that the probability of both of them is one by one, then we insure the property of all three. then we insure the property of all three. then we insure the property of all three. one by three and fourth when we do and
2024-03-24 11:54:56
382
https://i.ytimg.com/vi/Y…axresdefault.jpg
Leetcode 382. Linked List Random Node Problem Discussion | GDSC NSUT CP
w6WpJDIk9qQ
hello guys welcome to algorithms made easy easy today we will go through the day 9 today we will go through the day 9 problem from august lead coding problem from august lead coding challenge challenge rotting oranges please like the video rotting oranges please like the video and if you are new don't forget to and if you are new don't forget to subscribe to our channel so that you subscribe to our channel so that you never miss any update never miss any update in a given grid each cell can have one in a given grid each cell can have one of the three values of the three values the value 0 representing an empty cell the value 0 representing an empty cell the value 1 the value 1 representing a fresh orange and value 2 representing a fresh orange and value 2 representing a rotten orange representing a rotten orange every minute any fresh orange that is every minute any fresh orange that is adjacent to a rotten orange becomes adjacent to a rotten orange becomes rotten rotten return the minimum number of minutes return the minimum number of minutes that must ellipse until no cell has a that must ellipse until no cell has a fresh orange fresh orange if this is impossible written -1 in the if this is impossible written -1 in the sample example we can see how with each sample example we can see how with each passing minute fresh oranges turns passing minute fresh oranges turns rotten rotten here are two more example attached with here are two more example attached with the problem the problem let's start with our approach as we need let's start with our approach as we need to traverse all the nodes in the four to traverse all the nodes in the four direction with respect to the initial direction with respect to the initial node node we need to use a search technique which we need to use a search technique which in this case will be in this case will be bfs we'll start off with this bfs we'll start off with this example it is much more clearer when example it is much more clearer when displayed visually displayed visually now that we will be implementing bfs we now that we will be implementing bfs we will need a cube will need a cube we will also need two more variables we will also need two more variables first fresh orange which will hold the first fresh orange which will hold the number of fresh orange number of fresh orange and the minutes which will hold the and the minutes which will hold the number of minutes which has ellipse till number of minutes which has ellipse till now now we first need to know the number of we first need to know the number of fresh oranges and also the index of all fresh oranges and also the index of all the rotten ones the rotten ones so we will loop on the grid and so we will loop on the grid and increment fresh orange when the value is increment fresh orange when the value is 1 1 and add the pair of row and column into and add the pair of row and column into q when the value is 2. q when the value is 2. this gives us the fresh oranges 6 and this gives us the fresh oranges 6 and the index of the rotten into q the index of the rotten into q now we will loop till the queue becomes now we will loop till the queue becomes empty similar to bfs empty similar to bfs we will first find the size of the queue we will first find the size of the queue it comes out to be one it comes out to be one now we pop the element from the queue now we pop the element from the queue till the size variable becomes zero till the size variable becomes zero for every element popped we will update for every element popped we will update its four adjacent value to two if they its four adjacent value to two if they are one are one and add their index into the queue and and add their index into the queue and decrement the fresh orange count decrement the fresh orange count for index 0 comma 0 only these two for index 0 comma 0 only these two positions have the value 1 positions have the value 1 so we update them to 2 and add their so we update them to 2 and add their index into q index into q also decrementing the fresh orange count also decrementing the fresh orange count as size becomes zero we come out of the as size becomes zero we come out of the inner loop inner loop and then increment the minutes we repeat and then increment the minutes we repeat the same steps the same steps first by finding the size and then first by finding the size and then removing the element till the size is removing the element till the size is not zero not zero then we update the fresh oranges to then we update the fresh oranges to rotten while decrementing their count rotten while decrementing their count and adding their indexes into the queue and adding their indexes into the queue now 1 comma 0 do not have any fresh now 1 comma 0 do not have any fresh adjacent so we move ahead adjacent so we move ahead and increment minutes continuing with and increment minutes continuing with this loop till the queue becomes empty as now the queue is empty we return the result if the fresh orange is zero it means it is possible to make all the fresh orange to rotten so we written minutes otherwise we written minus one in this case we return four summarizing all the steps we first initialize the minutes variable to minus one a q and a fresh orange to 0 we loop over the grid and add index into the queue if the value is 2 or increment the fresh orange when the value is 1. if fresh orange is 0 then we return 0 we loop till the queue is not empty and then find the size of the queue we loop till the size is not zero we pop the first element and update the value in all the four directions if the value is one and add the pair into the queue at the end of the while we increment minutes if fresh orange is zero we return minutes else we return -1 the time in space complexity is often here is the actual java code snippet you can also find the link to the code in the description below thanks for watching the video if you like the video please like share and subscribe to the channel let me know in the comment section what
2024-03-25 14:48:08
994
https://i.ytimg.com/vi_w…xresdefault.webp
Rotting Oranges | Day 9 | BFS [ August LeetCoding Challenge ] [ Leetcode #994 ] [ 2020 ]
ujU-jeO1v-k
hello guys and welcome back to lead Logics this is the sign cookies problem Logics this is the sign cookies problem from lead code this is a lead code easy from lead code this is a lead code easy and the number for this is and the number for this is 455 and before starting with the 455 and before starting with the question I want to wish you all a very question I want to wish you all a very happy New Year and may may you all happy New Year and may may you all succeed in your career paths so let's succeed in your career paths so let's start with the question so in the start with the question so in the question we are given assume that you question we are given assume that you are an awesome parent and want to give are an awesome parent and want to give your child some cookies children some your child some cookies children some cookies but you should give each child cookies but you should give each child at most one at most one cookie and uh so we have cookie and uh so we have but we have a constraint that each child but we have a constraint that each child should at most get one cookie and each should at most get one cookie and each child I has a greed child I has a greed factor which is the minimum size of the factor which is the minimum size of the cookie that the child will be content cookie that the child will be content with and each cookie J has a size SJ with and each cookie J has a size SJ where if SJ is greater than G of five where if SJ is greater than G of five that is the greed factor that means we that is the greed factor that means we can assign the cookie to the child and can assign the cookie to the child and the child will be the child will be content okay so our goal is to maximize content okay so our goal is to maximize the number of your content children and the number of your content children and output the maximum number of children so output the maximum number of children so we want to maximize the number of we want to maximize the number of satisfied children and uh a children is satisfied children and uh a children is satisfied if he gets the cookie of the satisfied if he gets the cookie of the size he wants that is the greed factor size he wants that is the greed factor or Bri or Bri greater so let's see how we are going to greater so let's see how we are going to do this let's suppose we have example do this let's suppose we have example one with grd Factor equal to 1 2 3 and one with grd Factor equal to 1 2 3 and size equal to 1 1 so the gr factors are size equal to 1 1 so the gr factors are 1 2 3 and cookie size are 1 one in this 1 2 3 and cookie size are 1 one in this the gr factor and the cookie size are the gr factor and the cookie size are already sorted but for the already sorted but for the question uh where for the problems or question uh where for the problems or the test cases where the these are not the test cases where the these are not sorted we will be performing ascending sorted we will be performing ascending sort so you are going to sort in the sort so you are going to sort in the ascending order or the non decreasing ascending order or the non decreasing order so after sorting the for this order so after sorting the for this question the array Remains the Same now question the array Remains the Same now what you will do you will start one what you will do you will start one pointer at the greed factor and one pointer at the greed factor and one pointer at the cookie and check if you pointer at the cookie and check if you can assign a cookie to the child or not can assign a cookie to the child or not so if the so if the child if the child has a grid factor of child if the child has a grid factor of one and we have a cookie size of one so one and we have a cookie size of one so we can def we can def itely uh assign yes we can assign so itely uh assign yes we can assign so that's why it is assigned that's why it is assigned here here yes it is assigned yes it is assigned here and similarly we will be checking for each and every uh each and every greed factors and the cookie pairs so and at every point of time where the greed factor that is this condition we have that the cookie size is greater than the greed factor that means we can assign the cookie to the child and thus we will increase our maximum content children so in this case for one we have increased and uh the rest the grade factors are two and three and we still have the cookie size of only one that means we cannot assign more cookies so the maximum number of content children is one only in this case and you can solve it for similarly the second example like you have the great factor of 1 and two and we have cookie sizes of 1 2 and three so this two can get either a cookie of size of two or three and one can get a cookie size of one and two if this two takes three so that means both the children can be satisfied in this case and the output is so let's come to the code section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel so first of all we'll take a num and we initialize it with the num and we initialize it with the length and length and if cookies nums zero if it is equal equal to Z we will zero if it is equal equal to Z we will return a return a zero no zero no possible arrays do possible arrays do sort the gr factors and also arrays not sure the size of the cookies and then we have in num and then we have a cookie index the cookie index uh we'll be starting from the back so we'll be taking one and uh we having a chck index like will which child will be given with which cookie so that also we are having you can also do it from the starting it doesn't matter case now we'll check like if cookies case now we'll check like if cookies index so what is the first first index so what is the first first condition cookies index is greater than condition cookies index is greater than equal to zero equal to zero and and then then children or I think the child index is children or I think the child index is also greater than equal to also greater than equal to Z so what we'll Z so what we'll do do if if the previous condition is true and if if the previous condition is true and then the cie size the P size is greater than or equal to the G factor of the child this the GRE factor of the child so we are checking the main condition now if it is correct then Max nums Max num Plus+ this is our final answer counter and the cookie uh cookie num cookie index can be reduced because we have used the cookie reduced because we have used the cookie and we have allocated the cookie to the and we have allocated the cookie to the child so we can move both to the left child so we can move both to the left because we were moving from the right so because we were moving from the right so this is how performs if we don't this is how performs if we don't allocate the cookie to the child then allocate the cookie to the child then only the child is shifted not the only the child is shifted not the kogi and finally we can return kogi and finally we can return the max nums the max nums num let's see if it runs therey and uh some spelling mistakes there you can see it passes for the there you can see it passes for the sample test cases let's Le for the sample test cases let's Le for the hidden test cases as well my last solution was uh pretty good let's try to submit again so the time complexity for this solution is O of n log n and the space complexity is O of n this is a very much optimized approach if you are talking about in an interview the interviewer will be very happy with you if you tell this solution it although it doesn't passes this 100% beats 100% but it is still the one of the most optimized solution because you are not using a space and you are just sorting the uh the arrays so this is a very much optimized approach I hope you understood the logic this is very simple to understand please do like the video share it with your friends and subscribe to the channel thank you for watching the video have a nice
2024-03-22 14:43:26
455
https://i.ytimg.com/vi/u…-k/sddefault.jpg
✅ Assign Cookies - LeetCode 455 - Two Pointers - Sorting - Explained
48iJEar4kW4
hey guys welcome back to this video in this video we're going to work in this video we're going to work through the intuition through the intuition to find the minimum depth of a binary to find the minimum depth of a binary tree tree for example if you're given this binary for example if you're given this binary tree tree we have to return to because the minimum we have to return to because the minimum depth of this binary tree depth of this binary tree is two and this path is two and this path okay now how we can find minimum depth okay now how we can find minimum depth of a binary tree we're going to traverse of a binary tree we're going to traverse the given binary tree the given binary tree in dfs manner first we'll visit the left in dfs manner first we'll visit the left most most node okay the left most node here we node okay the left most node here we have two have two here we have null and here we have now here we have null and here we have now for null node for null node we have depth 0 okay that means we have we have depth 0 okay that means we have nothing nothing there is no depth so for null node will there is no depth so for null node will return 0. return 0. for this null node it will return 0 and for this null node it will return 0 and for this null node will return zero for this null node will return zero now we have to find out the now we have to find out the minimum depth for this node two how can minimum depth for this node two how can find that find that to find that we're going to get the to find that we're going to get the minimum minimum of left and right minimum of left and of left and right minimum of left and right is right is zero because minimum of zero and zero is zero because minimum of zero and zero is zero zero we get the minimum then we're going to we get the minimum then we're going to add one add one why because we have here one node right why because we have here one node right so zero plus one is one the minimum so zero plus one is one the minimum depth depth for this node two is one here we have for this node two is one here we have found found the minimum depth for the left subtree the minimum depth for the left subtree of this node one of this node one now let's find out the minimum depth for now let's find out the minimum depth for the right subtree of this the right subtree of this node one okay here we have three then we node one okay here we have three then we have four have four okay here we have two download so we'll okay here we have two download so we'll return zero return zero here as well zero because now node here as well zero because now node means nothing so there is no existent means nothing so there is no existent so that is zero now for this so that is zero now for this node four now we're going to get the node four now we're going to get the minimum of zero and zero that is zero minimum of zero and zero that is zero and one that is one so we'll return here and one that is one so we'll return here one one and here we clearly see that the depth and here we clearly see that the depth of this node four of this node four is one now let's go to right here we is one now let's go to right here we have five left is null have five left is null so for left node zero for right node as so for left node zero for right node as well zero well zero the minimum of left and right for this the minimum of left and right for this node five is zero node five is zero so zero plus 1 is 1 for this node 5 will so zero plus 1 is 1 for this node 5 will return 1 return 1 okay now for this node 3 we found okay now for this node 3 we found minimum depth for the left sub 3 and minimum depth for the left sub 3 and minimum depth for the right subtree minimum depth for the right subtree now let's get the minimum of them so now let's get the minimum of them so minimum of minimum of one and one is one so one plus one is one and one is one so one plus one is two two well we're adding one because when you well we're adding one because when you are encountering are encountering a node that means we'll have a depth a node that means we'll have a depth one for that node that's why we're one for that node that's why we're adding one adding one and here we have found the minimum depth and here we have found the minimum depth two two for the right subtree of this node one for the right subtree of this node one now let's get the now let's get the minimum of left subtree and right minimum of left subtree and right subtree the minimum of one and two is subtree the minimum of one and two is one one so one plus one is two so we'll return 2 so one plus one is two so we'll return 2 for this given binary 3 if you are given this binary tree we have to return 2 because the minimum depth we see here two now how we can solve this problem now let me go through the intuition first our goal is to find the minimum depth for the left subtree of this root node okay so here we have two then here you have null so for null will return zero now so minimum plus one that is one okay here we have found the minimum depth for the left subtree of this node one now for right subtree here we have three then we have here four then we have four okay so it will return zero now node it will return zero minimum of zero and zero is zero zero plus one is one then this node 5 we have null so it will return 0 here it will return 0 because this is a download so minimum of 0 and 0 is 0 0 plus 1 is 1 then for this node we found the minimum depth for left subtree that is one and minimum depth of right subtree that is one so let's get the minimum so minimum of one and one is one one plus one is two then this sub three now so it will return zero here now it will return zero so minimum of zero and zero is zero zero plus one is one now for this node we have found the minimum depth for left sub tree and minimum depth for right subtree so let's get the minimum and the minimum of two and one is one and 1 plus 1 is 2 all right and for this node we found the minimum depth for left sub 3 and minimum depth of right subtree all right the minimum depth of right subtree of this node 1 is 2 so minimum of 2 and 1 is 1 and 1 plus 1 is 2 and we will return 2 for this given binary tree and this is how we can solve this problem the solution will takes figure of n time complexity since we are visiting is nodes in the given binary tree once and this solution also takes big of end time complexity for the recursion call stack because we'll traverse this binary tree using dfs source and this is how we can solve this problem i'm not going to go through the pseudo code i have attached the source code to this video link in the description check that out i have another video to this problem i'll link that video in the description as well you can check that out all right guys this is my solution to this problem if you want more video like this stay
2024-03-21 10:39:48
111
https://i.ytimg.com/vi/4…axresdefault.jpg
LeetCode 111. Minimum Depth of Binary Tree | Minimum Depth of Binary Tree LeetCode
YomUVyA8nIw
welcome to june's leeco challenge today's problem is redundant connection today's problem is redundant connection in this problem a tree is an undirected in this problem a tree is an undirected graph that is connected and has graph that is connected and has no cycles you are given a graph that no cycles you are given a graph that started as a tree with n nodes started as a tree with n nodes labeled from 1 to n with one additional labeled from 1 to n with one additional edge added edge added the added edge has two different the added edge has two different vertices chosen from one to n vertices chosen from one to n and was not an edge that already existed and was not an edge that already existed the graph is represented as an array the graph is represented as an array edges of length n where edges i edges of length n where edges i has two nodes a and b indicating that has two nodes a and b indicating that there's an edge between there's an edge between nodes a and b return an edge that can be nodes a and b return an edge that can be removed removed so that the resulting graph is a tree of so that the resulting graph is a tree of n nodes n nodes if there are multiple answers return the if there are multiple answers return the answer that occurs last in the input answer that occurs last in the input so i feel like this should be marked as so i feel like this should be marked as hard because hard because i had personally no idea how to do it i had personally no idea how to do it but after looking it up i get the idea but after looking it up i get the idea here's what we're going to do we're here's what we're going to do we're going to move through our edges going to move through our edges build up our tree and find the edge that build up our tree and find the edge that creates a cycle creates a cycle now why is that well you can imagine if now why is that well you can imagine if we're building up this tree we're building up this tree we start with one and two then we add we start with one and two then we add one and three one and three but as soon as we add two and three here but as soon as we add two and three here we find that there's a cycle here right we find that there's a cycle here right that means that this one has to be that means that this one has to be removed because as soon as we have a removed because as soon as we have a cycle there's no way that this can be a cycle there's no way that this can be a tree tree so essentially really the question is so essentially really the question is what edge what edge when we add creates a cycle and then when we add creates a cycle and then just return that edge just return that edge now we how do we uh formulate that well now we how do we uh formulate that well what we're going to do is create an what we're going to do is create an array array that marks each node here and say that that marks each node here and say that we start with one and two we start with one and two what we'll do is see if each node is what we'll do is see if each node is pointing what what it's pointing to as pointing what what it's pointing to as its parent and right now currently each its parent and right now currently each node is just pointing to itself node is just pointing to itself but when we say one and two what we'll but when we say one and two what we'll do is just update do is just update one um like you can choose arbitrarily one um like you can choose arbitrarily but let's say we'll mark but let's say we'll mark the y like we'll mark this one's parent the y like we'll mark this one's parent as as two so this way we kind of know that we two so this way we kind of know that we marked these two marked these two these two are like union together these two are like union together so we add one and three we have to check so we add one and three we have to check hey do these have the same parent or the hey do these have the same parent or the same marker same marker that these are like unions of the same that these are like unions of the same tree now tree now here with one we see one has root of two here with one we see one has root of two and three has root of and three has root of itself three so it's not it's the same itself three so it's not it's the same so what we'll do is so what we'll do is if it's pointing to itself we'll merge if it's pointing to itself we'll merge it with this this part it with this this part so this one will not be a two now as so this one will not be a two now as soon as we get to two and three we find soon as we get to two and three we find that well these have the same parent so that well these have the same parent so adding this is going to adding this is going to create a cycle right so that's what we create a cycle right so that's what we do we return this do we return this and we could find the parent by just and we could find the parent by just recursively recursively calling up to see what the highest mark calling up to see what the highest mark note is and each time we update note is and each time we update everything and everything and eventually all all these should be the eventually all all these should be the same if there was if there was no cycle same if there was if there was no cycle in the same way let's look at this in the same way let's look at this example uh we'll have some sort of lookup that marks each one of these nodes we start with line two update one to two two and three uh update this two three and four three and four update this two one and four oh where we where we know the same parent right and that's when we return one and four and you can see the answer it indeed is one and four it makes sense right because we had one and two we had two and three we had three and four but as soon as we add one at four what what happened here this created a cycle so they can't have the same parent okay so let's begin by first figuring out what our n is n is just going to be the length of a set of all our edges and what we'll do is just use the chain function passing in the edges that should give us all so i'm just going to call it root even though that's kind of a misnomer but this will indicate to us what that representative node is of of this tree so i'll say 4 i in range of n plus one and i realized that zero is going to be in there but we'll just ignore that because i mean you know it's zero indexed so okay next let's have a function that's going to recursively call up what the parent is so let's say we pass in a value we'll say if root.x equals x well just return x but otherwise um return we're going to recursively call the root.x to see how far up we can get to the parents here yes okay so four let's call it x and y and edges let's find the representative and i'll just call it xr for x root and y root and this will be recursively called x and this because we call y so at this point if x r equals y r we've found a cycle right so that's when we just return x and y immediately now otherwise if the parents aren't equal we need to set all these we should set the one node that's by itself if it is to the rest of the unioned you know nodes so let's see if uh x r which is the x then we will set root of then we will set root of x to equal y x to equal y r and the other way around as well if y r and the other way around as well if y equals equals y r by itself and set the y to equal to y r by itself and set the y to equal to x r now finally if x r now finally if none of these are true dot x r equal to dot x r equal to y r so that's kind of arbitrary but y r so that's kind of arbitrary but it shouldn't matter at this point all it shouldn't matter at this point all right finally right finally that should be it like we can assume that should be it like we can assume that there is a cycle in here no matter that there is a cycle in here no matter what what and the given graph is connected so this and the given graph is connected so this algorithm should return something in the algorithm should return something in the end end so let's see if this works all right so i think that's working let's go and submit it and there we go accepted so time complexity wise it's going to be and worst case n squared because of this recursive call now there is a method where you could reduce this down to o of n by using disjoint set unions but that requires like some stuff that i just didn't understand i didn't want to you know put that in here without really understanding it and sometimes like it works and to me this is confusing enough so i'm just going to end it here maybe someday i'll go back to you know try and understand that this joint said even better so all right hope that helps thanks for watching my channel and remember do not trust me i know
2024-03-20 16:07:25
684
https://i.ytimg.com/vi/Y…Iw/sddefault.jpg
Leetcode - Redundant Connection (Python)
MlqPkVV0SLM
In this video, we friends shop appropriate agency are going to solve this question, appropriate agency are going to solve this question, we have a question which is quite we have a question which is quite fantastic, brother-in-law are people on social fantastic, brother-in-law are people on social media website, you are living and waiting, error is where the age of I is, the media website, you are living and waiting, error is where the age of I is, the age of I is the day after tomorrow, age of I is the day after tomorrow, we have we have we have and we are given an area whose where jo i the day after tomorrow ko dino does right n day after tomorrow x they bill note send n friend request tu n the day before yesterday same D The following conditions are true: A who is What is written in the note? No date It is It is not that the one who is A will also do the same to What to do is how many total friend requests have been received, what do we have to do with it, do we have to return it, so let me explain the question to you in a very simple way and tell you how you will be able to do it very easily, so what we have given is the area of ​​an agent. And we have been 16, 17 and 18 are more than 100 and when X is less than 100 If he is If he is 16, he can represent 17 or not, this has to be checked and the one who is 16, can he send a request to 18 or not, this will have to be done right, so first of all, if I call him X, then What will I do, I will start What will I do, I will start What will I do, I will start checking these three conditions, what will checking these three conditions, what will happen if our first turn is A is 17 So I will be able to check, So I will be able to check, for this I cannot send a friend request, for this I cannot send a friend request, 16 can do 17, now for 16, 16 can do 17, now for 16, I will check with 18, from 18, now I will check with 18, from 18, now what has happened to me, which has become A, here 89 A will what has happened to me, which has become A, here 89 A will go, okay then I go, okay then I go, okay then I which area is applicable, give 18 li, equal tu hai kitna, we will have to check our water from 8 plus 7, nor can we make a friend request on 18, that means even one is not true here, so what will I have to do now, pay What will I have to do, I will What will I have to do, I will tell you now what will have to be done, till then you have to understand the video carefully, only then you will understand, otherwise you will not understand, as if I am telling you again and again, okay, so what will I do now, I will move it to X, now I will create this and A will become our A I will create this and A will become our A I will create this and A will become our A and this will become our A. Okay because and this will become our A. Okay because if our What What happened A Now again I will check the condition Now happened A Now again I will check the condition Now what will I do Again I will check the condition what will I do Again I will check the condition Look now how much is our ≥ is not means all three conditions are true. When all three You You can send a friend request on 17 and 16, one condition has become true for us, okay now what will I do, here we are 16, we have 16, now I will update the value of A, now I will check on 18, If I check, then If I check, then If I check, then what will I do now? What is the value of A? 18 of 18 is equal to you. Half of Jo Jo is 17. Ca n't send friend request on 17th and 18th, that means till now our request has been received. Okay, check the condition again check the condition again and will adopt again, now I have met my love, and will adopt again, now I have met my love, you are mine. Ca How much has n't send friend request 18 which is 16 ca n't send friend request 18 which is 16 ca n't send friend request ok n't send friend request ok now I will check 18 and enemy A = now I will check 18 and enemy A = how much is 17 ok now what is 70 how much is 17 ok now what is 70 give li equal tu 9 plus 7 ke hi give li equal tu 9 plus 7 ke hi How much is the condition, give it greater than 18, How much is the condition, give it greater than 18, what else, who is 18, then I think you must have understood this explanation, then I think you must have understood this explanation, what will I do, I will what will I do, I will catch one, I will accept it, X, you have to catch one, I will accept it, X, you have to understand carefully, what will I do If it is I will consider this as true then what will I do, I will not update the request and will return it last and friend, if you have not subscribed the channel yet and are watching the video, then please subscribe because there are many thoughts, I am making a video for you No brothers, there are No brothers, there are No brothers, there are 726 questions of Bhaiya, I have solved this in a much better 726 questions of Bhaiya, I have solved this in a much better way only plus plus and where way only plus plus and where I have solved many questions, so I have solved many questions, so see that too and if you have any doubt then see that too and if you have any doubt then comment me. Link comment me. Link of WhatsApp group. Link of Telegram group. of WhatsApp group. Link of Telegram group. of WhatsApp group. Link of Telegram group. join it, type it, see what we did, how the solution will be made You will check this condition for everyone and You will check this condition for everyone and what you will do, you will take out the output, then O what you will do, you will take out the output, then O of n² will come out, of n² will come out, okay and space is not yours, I will give okay and space is not yours, I will give you a you a you a why is the map made because look, if there are 16, 17 and 18, then have we counted the number, who are the people of Solar Age, how many are there, how many are there from 17, how many are there from 18, whatever further group is given. I have to count the frequency of everyone so that I can know how many people are there. I don't have to send anything to my friend. Once you know that all of them are unique, then I have to compare them. If If it remains the same then there will be a If it remains the same then there will be a If it remains the same then there will be a problem. problem. Okay, so what will I do? For this, if Okay, so what will I do? For this, if you want, you can create a count area, you want, you can create a count area, Count A Ray, which will establish the frequency of each element, Count A Ray, which will establish the frequency of each element, or if you or if you want, I will do it, which is the best want, I will do it, which is the best solution for you. solution for you. solution for you. is a relief, it counts and stores it, okay then the result is saved, now what to do is to catch an element, like catch 16, if you catch 16, then 18 18 18 catch it, okay, so what have I done, I have got one element, I have got one element, so first of all, what will I do? First of all, Once I have counted the frequency of 17, I have Once I have counted the frequency of 17, I have counted one element, one is 18. counted one element, one is 18. counted one element, one is 18. here, now what will I do, I will catch the first level of both because this is our next, its frequency, so we mean otherwise, what should I do, I will catch 16 and 17 and send both of them to it and have Its Its Its first element means 16 here and 17 first element means 16 here and 17 here. If you want then send it to Listen here. If you want then send it to Listen and you can also check 16 along with 16 and you can also check 16 along with 16 because you must be seeing in the question because you must be seeing in the question what is yours that only two elements have been given. what is yours that only two elements have been given. what is yours that only two elements have been given. or send it to 16. Whatever bill you send, it will or send it to 16. Whatever bill you send, it will go into the bill function. The go into the bill function. The request function here is of flower type, it will request function here is of flower type, it will check all the three conditions as a result, the note is written here, meaning you have to water. If any of them is true then and copy its value from one to and copy its value from one to our increment and finally our increment and finally return the result then this is our solution return the result then this is our solution which is a perfect solution in itself for this It is fine for questions, if It is fine for questions, if It is fine for questions, if time solution is required for this type of question, time solution is required for this type of question, then how much will it be n², if the size is the maximum then how much will it be n², if the size is the maximum length of the edit, its length of the edit, its timing will timing will not be anything, then it will be of one, not be anything, then it will be of one, Show Show Show again what we have done since 17, what we have done since 18, what again what we have done since 17, what we have done since 18, what we have done since 17, what we have done since 16, what we have we have done since 17, what we have done since 16, what we have done here, the done here, the same thing is happening here with you, by the way, I same thing is happening here with you, by the way, I can make it here, but If you If you If you understand the video solution of DISA, then understand the video solution of DISA, then you can take this force of DISA. If you enter any of these two phone codes, then you enter any of these two phone codes, then you can apply can apply and take the maximum discount in which you get. and take the maximum discount in which you get. and take the maximum discount in which you get. best DSP in the world is available in both C+Plus and Java languages, so what will I do now, I will turn it to you and then you have to go and take whatever you like in the description. Now I will show you the code of C plus plus, I will show you the code of C plus plus, I will show you the code of C plus plus, see what I will do because it is raining a lot, you will please pause the video, you will write yourself and please try run, if you do not try run then you will not understand You will be wondering You will be wondering You will be wondering who is the best video, the best video is who is the best video, the best video is fine tomorrow, if you have any doubt, if you want to comment then fine tomorrow, if you have any doubt, if you want to comment then please subscribe the channel and like the video please subscribe the channel and like the video because we are going to come up with all such because we are going to come up with all such questions in a very fierce manner, questions in a very fierce manner, see you in the next video. see you in the next video. Cup support with such steamy videos
2024-03-22 14:32:29
825
https://i.ytimg.com/vi/M…axresdefault.jpg
825. Friends Of Appropriate Ages | Friends of Appropriate Ages | Coder Army Sheet |Triloki IndIAwAle
Uxuf8YXqexE
hello everyone welcome to coding culture this channel will contain those programs this channel will contain those programs whose explanation is either not present whose explanation is either not present on youtube or the explanation is present on youtube or the explanation is present but not up to the mark so without but not up to the mark so without wasting time let's get started so wasting time let's get started so today's question is the sudoku solver so today's question is the sudoku solver so which is also the daily question of 21 which is also the daily question of 21 of august so we must have solved sudoku of august so we must have solved sudoku in our childhood and most of us will be in our childhood and most of us will be solving it today also and it is a very solving it today also and it is a very interesting game so in this question interesting game so in this question what we have to do is that we will be what we have to do is that we will be given an incomplete sudoku 9x9 table and given an incomplete sudoku 9x9 table and we have to complete it we have to complete it okay so those who don't know what is okay so those who don't know what is sudoku and how it is solved i have sudoku and how it is solved i have already explained it in its in the already explained it in its in the previous video and i will provide you previous video and i will provide you the link and the link and i will provide you the link and you can i will provide you the link and you can go there and understand what is sudoku go there and understand what is sudoku and how it is played okay and how it is played okay so i i will not be explaining it in so i i will not be explaining it in detail in this detail in this question because the questions video question because the questions video will become long and most people will will become long and most people will get bored okay so i will provide the get bored okay so i will provide the link but i will explain it a bit so what link but i will explain it a bit so what is sudoku in sudoku there are nine rows is sudoku in sudoku there are nine rows and nine columns and nine columns so how we have to fill it is that in so how we have to fill it is that in each row there should not be repeating each row there should not be repeating element or we can say that in each row element or we can say that in each row there should be one to nine numbers each there should be one to nine numbers each time like every time one time one number time like every time one time one number like there's one should be present one like there's one should be present one time two should be present one time in time two should be present one time in each row and in each column and in each each row and in each column and in each three by three sub matrix three by three sub matrix it's a box okay so three by three it it's a box okay so three by three it doesn't mean that every three by three doesn't mean that every three by three first three by three and next six first three by three and next six four five sixth rows and three columns four five sixth rows and three columns and in this way three three three this and in this way three three three this the highlighted boxes like this box and the highlighted boxes like this box and this and in these boxes also there this and in these boxes also there should not be any repetitive number and should not be any repetitive number and should not be any repetitive number and should not be any repetitive number and each number should be present one once each number should be present one once okay so if it's if the number is not okay so if it's if the number is not repetitive it will be every number will repetitive it will be every number will be present at least once yeah it's a be present at least once yeah it's a both both same thing okay so yeah now how we will same thing okay so yeah now how we will solve it so this question is a classic solve it so this question is a classic example of the backtracking and is also example of the backtracking and is also very important question if you want to very important question if you want to understand backtracking and want to understand backtracking and want to impress impress children like you can solve sudoku children like you can solve sudoku easily in seconds with this easily in seconds with this program by by running this program okay program by by running this program okay so so now let's uh first of all let's talk now let's uh first of all let's talk about the approach and then we will go about the approach and then we will go to the code section and try to code it to the code section and try to code it okay first of all be patient this video okay first of all be patient this video may become longer as it uh it's a bit a may become longer as it uh it's a bit a long long question and uh at the coding the question and uh at the coding the solution will also be long but i assure solution will also be long but i assure you if you will keep patience you if you will keep patience i will you will understand bit by bit of i will you will understand bit by bit of this program and you will be able to do this program and you will be able to do it anytime okay it anytime okay so first of all how we will do it okay so first of all how we will do it okay so i will put one here in in such a so i will put one here in in such a backtracking box in this way i will put backtracking box in this way i will put one here and then i will move to the one here and then i will move to the next row and i will check if next row and i will check if one is or if one is already present yes one is or if one is already present yes one is present so i will there the one is present so i will there the cursor is in at this point i will place cursor is in at this point i will place 2 2 because 2 is not present then i will because 2 is not present then i will move here it is 7 it is filled then i move here it is 7 it is filled then i will come here here what will be dot will come here here what will be dot okay so empty space is okay so empty space is denoted by a dot here i will check one denoted by a dot here i will check one is already present here two is present is already present here two is present here three is present here and i will here three is present here and i will put four here okay put four here okay in this way i will put five is already in this way i will put five is already present six seven is present eight and present six seven is present eight and nine okay so this row is complete now i nine okay so this row is complete now i will check this row and in okay so if will check this row and in okay so if any ones is not complete if any any ones is not complete if any there can be many possibilities like i there can be many possibilities like i put one here put one here and but if one is also present here and but if one is also present here maybe then i should i will have to maybe then i should i will have to remove one and i will have to place two remove one and i will have to place two here okay so how we will tackle it by here okay so how we will tackle it by returning false i will check if returning false i will check if furthermore is returning true then okay furthermore is returning true then okay and if it is returning false then what and if it is returning false then what we will do i will move i will move it to we will do i will move i will move it to the next and next value to it okay so the next and next value to it okay so i think that you may not get to the i think that you may not get to the point now but when i will code it point now but when i will code it you will be very much sure what i want you will be very much sure what i want to say okay so let's try to code it and to say okay so let's try to code it and then you will understand okay so we will then you will understand okay so we will start okay so i will make a function start okay so i will make a function solve and solve and what we will add it in it i will add a what we will add it in it i will add a bold zeroth row and zero column static void static void and the function name is solve and and the function name is solve and the parameters will be the parameters will be no no it will be boolean it will be boolean why because we want to know if the values i filled is good or not okay if the values i have filled it is correct or not okay so when i will code more and with the coding i will explain you will get why i have taken it boolean so what parameters here parameters here bold into bold into say say r and intersect c okay and now what i r and intersect c okay and now what i will okay so will okay so if yeah so first of all let's uh if yeah so first of all let's uh try to check if the road if the try to check if the road if the cell is already filled then we have to cell is already filled then we have to do nothing do nothing so now what i will do is if so now what i will do is if board board i i word r word r c not equal to dot it means it is filled then what i will do i will i will what i will return i will see it i will what i will return i will see it later later and otherwise if it is not filled and otherwise if it is not filled then what i will do then i will have to then what i will do then i will have to fill it fill it and how i will fill it i will check and how i will fill it i will check from where we i started to fill it i from where we i started to fill it i will start to fill from one will start to fill from one and and let's say okay it is a character array let's say okay it is a character array so i will take care so i will take care there and there and let's name the variable val and it's a let's name the variable val and it's a val one and how long we will run it i val one and how long we will run it i will run till will run till val is less than val is less than yeah or equal to nine yeah or equal to nine and and val plus plus okay val plus plus okay so now the major thing is if so now the major thing is if if i will pass this value and the roth if i will pass this value and the roth and column to and column to uh uh checker to a checker and to check if it checker to a checker and to check if it is correct in the row column and sub is correct in the row column and sub matrix it is not present okay if it is matrix it is not present okay if it is not present then we will move forward not present then we will move forward otherwise we will otherwise we will run this loop once again so okay so run this loop once again so okay so let's take see if is valid is a function let's take see if is valid is a function that will return you don't mind the that will return you don't mind the function here function here that what how we will make this function that what how we will make this function just let it be okay just keep in mind that it will return that if it is correct or not so bold i j and which value well if it is valid then what i will do i will put board okay oh sorry r okay oh sorry r c c c equal to what equal to val c equal to what equal to val yeah it's a good that uh if it is valid yeah it's a good that uh if it is valid then i can put it here okay then i can put it here okay now what i will do yes now what i will do is a very good question here okay now what i will do i will move on i will move forward and i will again call the same function solve and here what i will do i will pass board and now there is a problem here the problem is if i move till this row this cell then if i will do c plus 1 then it will move out so what i will do i will check if it is equal to the last cell or the last column then what i will do i will add a value in r otherwise i will add a value in the c itself okay so yeah i think you have got it so i will not explain it more and first of all okay so now let's check into okay so let's check enter n i equal to 0 and n j equal to 0 and now what i will do i will check if c equal to what bold c dot length bold zero dot length this is the way i we will check the column yeah you must have know it if you are solving this hard level problem okay you must have known it and then what i will do i will do n i equal to r plus 1 and n j equal to 0 yeah it's uh obvious otherwise what we will do is otherwise what we will do is i will simply and i equal to the same i will simply and i equal to the same row which row r through and n j equal to row which row r through and n j equal to what another next column what another next column c plus one so yeah it's a good and if c plus one so yeah it's a good and if okay now let's fill this also if we are okay now let's fill this also if we are doing so if doing so if it is filled so what we will do we will it is filled so what we will do we will move to the next gel and move to the next gel and next cell is next cell is bold ni comma nj okay and otherwise if this if it is valid i have already told you then i will put the value in the board and i will move further okay so move further means ni comma and j then then if this is true if this is true it means that it means that by putting the value one or two whatever by putting the value one or two whatever it is at this cell we can move on and we it is at this cell we can move on and we will get true then what i will do i will will get true then what i will do i will return return true otherwise true otherwise otherwise what otherwise what otherwise i will otherwise i will again again put the value of bold r and put the value of bold r and c equal to c equal to dot dot which means that it is not true and now which means that it is not true and now move on and again what i will do i will move on and again what i will do i will this loop will run again this loop will run again yeah this rope yeah this rope other if this is true then it will other if this is true then it will return true and this loop will not run return true and this loop will not run again but it is not true then this loop again but it is not true then this loop will run again will run again okay okay so yeah and so yeah and we will return we will return false here if we can't put any value false here if we can't put any value then what i will do will return false then what i will do will return false like we can't put 1 here we can't put 2 like we can't put 1 here we can't put 2 here we can't put 3 here and here we can't put 3 here and it mean till 9 we can't put here it mean till 9 we can't put here everything is present either in sub everything is present either in sub matrix or the row or the column then we matrix or the row or the column then we will return false and this false will be will return false and this false will be accepted by the previous accepted by the previous is valid function no solve function okay is valid function no solve function okay and then whatever it will do it will and then whatever it will do it will change the value so it's like a change the value so it's like a chain to the previous ancestors chain to the previous ancestors this is simply backtracking okay this is simply backtracking okay so so let's now okay so the only one thing is let's now okay so the only one thing is remaining now and that is that is what remaining now and that is that is what that is to make the is valid function that is to make the is valid function and is valid function is a bit and is valid function is a bit very easy i will not explain it more as very easy i will not explain it more as i have already explained in the previous i have already explained in the previous video and i will provide you the link video and i will provide you the link there already okay so is valid and there already okay so is valid and what are the parameters bold rc and well and okay so what we will check i will run the loop for equal to zero for the row if this element what val is already if this element what val is already present in that row so how we will check present in that row so how we will check it it bold bold i in which row in the row equal to val it means it is already present we will return false similarly the same thing we will i and what is the column co i and what is the column co so basically it is checking for each so basically it is checking for each column column for the same row okay for column and for the same row okay for column and this is checking for the row and now this is checking for the row and now what we will have to do we will have to what we will have to do we will have to check for the check for the the sub boxes of three by three so how the sub boxes of three by three so how we will check it i will take into a we will check it i will take into a small i small i semi semi row row by three into by three into three and three and similarly for the column i will explain similarly for the column i will explain it it don't don't panic i will explain smj panic i will explain smj column and what now column and what now for the column smi and smg okay for the column smi and smg okay so let's uh run the loop that will be always 3x3 you can do it in okay and now okay and now if if board smi board smi plus i plus i yeah yeah yeah yeah and sm and sm j plus j j plus j yeah yeah equal to equal to val it means it is equal to equal to val it means it is already present and then what return already present and then what return false false if all these conditions are true then if all these conditions are true then what then return what then return true true okay so now let's talk about this point okay so now let's talk about this point here here suppose my row is suppose my row is suppose my suppose my row i have given is 2 row i have given is 2 and and column is column is one one so second row and first column second so second row and first column second row this row this and second row is this row and first and second row is this row and first column is this so it is nine it is column is this so it is nine it is filled here okay let's suppose this filled here okay let's suppose this column okay now column okay now which sub box we will check it will be which sub box we will check it will be given by this given by this it will be given by this okay row by 3 it will be given by this okay row by 3 into 3 so my row is what my row is second and column let's suppose zero then our s m i will be will be row by three two by three it's zero into three it is zero column is zero so column by three into now okay we can simply traverse this way now okay we can simply traverse this way yeah we can do it yeah we can do it smi plus i zero for once it will 0 1 2 smi plus i zero for once it will 0 1 2 and then okay i hope you have got it and then okay i hope you have got it now suppose now suppose my row is 4 and my column is 6. my row is 4 and my column is 6. let's go to the array and check 4th row let's go to the array and check 4th row and and sixth column okay sixth column okay fourth row fourth row and sixth column this and sixth column this now it is in what now it is in what my smi what will be my smi my smi should my smi what will be my smi my smi should be four be four and my smj column it should be 4th now and my smj column it should be 4th now let's check if it is true or not smi 4 let's check if it is true or not smi 4 by 3 it is 1 by 3 it is 1 into 3 yeah it is 3 ok so into 3 yeah it is 3 ok so i was right here and let's check for the i was right here and let's check for the column column six by three six by three into three into three two into three is six okay i think that i have okay yeah this column six is this i should have taken it five here to check it in this way it is six and my row is four okay so yeah it should be good and this will be our row and column so smi is zero into three three and column should be what zero one two three four five six three and six i think i should have got it let's comment it out and check if it is executing correctly or no i should i think that it should run oh okay oh yes my way is not it's a capital and it is not here no problem and we will try to run it again okay i think i have done something wrong here and let me ch oh yes so what i forgot is the end condition when we will terminate the end condition when we will terminate it so when we will terminate it is if it so when we will terminate it is if i equal to what okay so when we will i equal to what okay so when we will terminate is is when i equal to what i terminate is is when i equal to what i equal to my bold dot length equal to my bold dot length ball dot length means it has come out ball dot length means it has come out all the columns are covered and the last all the columns are covered and the last row is also covered then what we will do row is also covered then what we will do we will return we will return true now it will run true now it will run it will run comfort oh oh run moja please yeah it's running and run moja please yeah it's running and let's try to check if it is accepting or let's try to check if it is accepting or not it should be accepted yeah it's not it should be accepted yeah it's accepted so yeah that's it that was accepted so yeah that's it that was today's video hope you have liked if you today's video hope you have liked if you have liked please like the channel and have liked please like the channel and subscribe it and do the comments as it subscribe it and do the comments as it motivates the creators like us to do motivates the creators like us to do more hard work and then more hard work and then keep on coding and keep on coding and yeah keep on coding enjoy okay bye
2024-03-20 09:01:51
37
https://i.ytimg.com/vi/U…axresdefault.jpg
Sudoku Solver Leetcode 37 || Coding Culture || Leetcode Daily Challenge
37KddCEdv3s
Hello everyone, welcome to 10 off DSL practice and as promised, I will practice this week practice and as promised, I will practice this week too, whether it is New Year or too, whether it is New Year or whatever, I will not leave you, I have to whatever, I will not leave you, I have to practice for 5 days, is it okay, so the practice for 5 days, is it okay, so the question you asked today. question you asked today. question you asked today. asked is the search suggestion system. What is the question inside it? It is a very simple question but it is not easy to do, so if we look at this question, what the question is saying in it is that it has given us a list of words like mobile. Mouse Mani Pot Monitor Mouse Word Okay, now we have given a search word mouse, so we have to implement the type as it is. For example, when the user entered M, top three characters printed we have to show. top three characters printed we have to show. top three characters printed we have to show. manner, so now here you will see which are the mobile manipot monitors from M, so it is in this increase in and three top three, we have to show and three top three, we have to show then when the user entered M O, okay, The mouse is so you understand that we have to implement the type system, so you understand that we have to implement the type system, as the user keeps as the user keeps entering word characters, we have to show its entering word characters, we have to show its top three which are in sorted manner. top three which are in sorted manner. Okay, so whenever such a Okay, so whenever such a question arises. question arises. question arises. approaches, I am telling you, one is with try and one is with pointer, it is okay, time complexity of both of them etc. will also be seen, the first strike of mine was in mind, whenever try is If you If you If you search anything of character then try it, it is search anything of character then try it, it is very simple to make it, right, so now see very simple to make it, right, so now see what I did first, here I am what I did first, here I am telling you the first one to try, this one is fine, telling you the first one to try, this one is fine, time complexity is also off, wait, I will time complexity is also off, wait, I will tell you. tell you. tell you. implement try? Here I have made the simplest tree. Here we have zero to 25. We will take one which will be treated as a character. Okay, now what will we do inside this tree, we will Mani pot Mani pot Mani pot monitor mouse post, which are all our words, monitor mouse post, which are all our words, we will put them in the tree in this, okay and we will put them in the tree in this, okay and you know in which way we will you know in which way we will put this like for example first time put this like for example first time mobile let's insert mobile in this try so the mobile let's insert mobile in this try so the first is M so here for example first is M so here for example first is M so here for example then here is here inside this also for this also for this also its which way Okay so here you see so Okay so here you see so how I have taken try string word meaning how I have taken try string word meaning with each one up to here now word what with each one up to here now word what with each one up to here now word what yahan pe mat hai yahan pe also, now my word is empty mat hai whenever one word of mine is finished, I will say to the here pe word that Han what has become mine, so here I have taken the word and try to search The arrear has been taken from 26 type, okay, The arrear has been taken from 26 type, okay, The arrear has been taken from 26 type, okay, so now what I am doing here first of all, I am trying to so now what I am doing here first of all, I am trying to fill it, how I am fill it, how I am filling it, I will iterate from here, filling it, I will iterate from here, okay, this is the one who has given me the lace, okay, this is the one who has given me the lace, I am doing this. I am doing this. I am doing this. I will insert each and every word, so that means I will have to draw on the characters inside each word, so let's create a filter tree here, so Pass Pass Pass is the word in it, now is the word in it, now I am inserting each product, so now I am inserting each product, so now look here at each character for look here at each character for example, first what is mobile, now the example, first what is mobile, now the characters inside the mobile and I am characters inside the mobile and I am inserting the characters and they are like this. inserting the characters and they are like this. I am going to enter and as soon as my I am going to enter and as soon as my whole word is finished, what am I doing, I will put this group on the word, okay, in this way I will store all the words, I will put this group on the word, okay, in this way I will store all the words, okay, so my try will be okay, so my try will be created first, okay now I created first, okay now I created first, okay now I less I have to implement this type ahead mouse so now I'm doing M first so what's my M now this is my search search word mouse so right now what's the first thing is M okay so now I'm doing M so M I will search in this I will search in this I will search in this inside try okay so now here I go here inside try okay so now here I go here search string so far search string so far what is my prefix M okay so now I will what is my prefix M okay so now I will go to this M first okay so this is mine I am I am I am fine here because I want top three, fine here because I want top three, so maybe there is a word from here too, there is a word here too, word here too, okay if there is a word here too, then what am I doing, I will implement it from here inside DFS after M. will implement it from here inside DFS after M. will implement it from here inside DFS after M. find three characters in which I will get the 26 where I will find its word, 26 where I will find its word, I will stop there where the I will stop there where the word is not equals, you will be null, I am stopping, okay and in the same manner. okay and in the same manner. okay and in the same manner. man, let's go, when I come to O, what is my prefix, so now I will first prefix, so now I will first go here from M, then from O, now from here I will go here from M, then from O, now from here I will start searching, from here I will start searching, from here I will implement DFS and from here I will take three implement DFS and from here I will take three words. words. words. find the word. Ok so coding is simple. Try key is a little big but it's always good. You implement tree. I get a little handsome. What is the time complexity? First try creation key and How many words How many words How many words are there, this are there, this is 12345, okay, and each one has to iterate my word, write is 12345, okay, and each one has to iterate my word, write each length of what, so each length of what, so n * average length of what, so this is my try n * average length of what, so this is my try for creation, after that I have to for creation, after that I have to search, right then o of. search, right then o of. search, right then o of. this d length of query string because I have to search on every single query string on every single mouse and then one more thing I forgot plus the time complexity of DFS I am doing it I am doing it okay, here I have to search three words, that is, I have to search three times, but every 26 times I have to go into its depth. Okay, so here plus here, forgot the time complexity, here You will have to do it, You will have to do it, You will have to do it, okay, so this is our try one, okay, so this is our try one, now there is another simple method other than this, okay now there is another simple method other than this, okay now what is that first, do the now what is that first, do the sorting of the world in it, okay, what was there, I used the mobile mouse okay, what was there, I used the mobile mouse mani pot, so this is the first one. mani pot, so this is the first one. mani pot, so this is the first one. write here, right here, I so now first of all, what am I saying, so now first of all, what am I saying, how will we solve it, first of all, let's how will we solve it, first of all, let's open this word. open this word. Short [Music] So now I am shortening the word, so here it here it became mobile, then it became Mani Pot, okay, then it became your mouse, okay, okay, But I put the right point But I put the right point But I put the right point [music] [music] Right here, my right point, now I'm iterating Right here, my right point, now I'm iterating on the mouse, which is my search word, on the mouse, which is my search word, mouse, now where I am at first is MP, mouse, now where I am at first is MP, okay, now I will search, which is its okay, now I will search, which is its index, which is zero now. index, which is zero now. index, which is zero now. search its zero if MK is there then if it is not then I will badhaunga left if it is equal then I will keep it here. Similarly I will check with the right pointer whether it is equal to it or not. If not then I will check the right pointer. If there is then I will keep it equal. Now if it is from M then now I will increase then A has gone I. What has this one this one will also be from [music] so I will print the top 3 from here, the top three from left to right I will go on printing I will go on printing I will go on printing [Music] Is this the third index of this which is equal to you, otherwise it is left, here is means left is right, from here I am as means left is right, from here I am as many threes as possible. many threes as possible. many threes as possible. then we have two, so empty two will be printed here, okay, then what came U, then came S, what is the third index, Han, so the left will remain here, this is also equal, this will also remain the same, I will give second time also, this I will give second time also, this I will give second time also, this got printed and then came last. If we do not read back and forth from both then it will remain in this manner. Okay, first of all I have shortened its word. Okay, I have shortened it. After that, assign the left and Okay, now Okay, now Okay, now I'm trading on the word. This I'm trading on the word. This word [music] is important because for example, this is your search string, it can be very big, mouse word monitor can be a very big string Okay, so when you Okay, so when you Okay, so when you go to man, here it is being indexed, go to man, here it is being indexed, these are some seven and here there is only empty four, these are some seven and here there is only empty four, so it should not go out of index, okay, so so it should not go out of index, okay, so this thing is necessary to save the exception and then where and then where and then where from there I just have to take out three outputs and group them into outputs. Okay, so what is its time complexity? Big Boss, n people, plus n * m for sorting, why because I have to iterate over all the words in it. Okay, total number of words and m is d length because here I am taking left and right pointer because I have to iterate the left pointer also, I have to iterate the right pointer also. What is the worst case that the left pointer And the right pointer should go all the way up, And the right pointer should go all the way up, And the right pointer should go all the way up, okay, so once Puri can be seen, N okay, so once Puri can be seen, N * N means here also, I am searching for a trick, * N means here also, I am searching for a trick, okay, so the length of D okay, so the length of D string is N * M plus O off string is N * M plus O off which is this character. which is this character. which is this character. then this is its time complexity and but then this is its time complexity and but both the methods, this is a little sample both the methods, this is a little sample on implementation, but you can also implement a little with try and you can see the coding, maybe it looks like this, but you have to and you can see the coding, maybe it looks like this, but you have to understand it once. understand it once. understand it once. go right, so let me browse a cursor a little, then you practice tomorrow too, you will practice tomorrow too, you will do the day after tomorrow too, just empty New Year, do the day after tomorrow too, just empty New Year, this time also keep practicing your good this time also keep practicing your good butt, Happy New Year, Happy Christmas, enjoy. butt, Happy New Year, Happy Christmas, enjoy. Do phuli, if you can spare half an hour, then you can spare an hour. Do phuli, if you can spare half an hour, then you can spare an hour. Tree and best but enjoy the holidays. Tree and best but enjoy the holidays. Property Gauge. I was just saying, I was joking Property Gauge. I was just saying, I was joking that you will do your daily practice. Enjoy the that you will do your daily practice. Enjoy the holiday time holiday time but if you can spare one hour, then enjoy yours. but if you can spare one hour, then enjoy yours. but if you can spare one hour, then enjoy yours. can also ask a question, ok gas,
2024-03-19 17:55:35
1,268
https://i.ytimg.com/vi/3…axresdefault.jpg
1268. Search Suggestions System | LeetCode | Java Solution | LeetCode Hindi
5JPMFv5Cd_M
this is the question 349 intersection of two arrays question 349 intersection of two arrays what it has is that you have two arrays what it has is that you have two arrays and you want to find the intersection of and you want to find the intersection of them and the output should not be any them and the output should not be any element that is repeated like it should element that is repeated like it should be all unique values be all unique values so let's do this so let's do this so i want to use a so i want to use a set high step set high step equals to set equals to set and then and then i'm looking i'm going to loop through i'm looking i'm going to loop through the first array the first array and get all the values that are and get all the values that are unique unique yeah that's it we're going to get all yeah that's it we're going to get all the values that are in four idx actually i don't really need to enumerate i can just do for num in numbers one if num not in then hash set then hash set dot add so that's dot add so that's how you add to a set um that's what you do and then if you print this out a hash set you would see that there is one and two which are the unrepeated values their unique values of this array let's run this see that there's one and two here okay so we don't need this print statement anymore the next thing is that i want to output an outset another set this is the output set and the reason i'm using a set instead of an array is that i think i don't want to do another set at the end because if i have an array uh there might be this uh problem of um repeating values added so if they're if these repeated values are inside array 2 or nums 2. so let's move over numbers to now so we loop through numbers 1 we got the values that are not repeated they're unique values now we want to see if those values are in numbers one numbers two which is which will give us the intersection so for num in numbers 2 now if none in [Music] set outset dot add and that's it uh so and that's it uh so what does this do let's let's just do it what does this do let's let's just do it return outside first so return outside first so this one looks really nice to the array this one looks really nice to the array it says it says if this if this number um each of these numbers are number um each of these numbers are inside high set just add it to the inside high set just add it to the outset and then return outside so that outset and then return outside so that would give us the would give us the actual value actual value and that's it so you can see that this and that's it so you can see that this is accepted and uh it's going to is accepted and uh it's going to end here and then another end here so end here and then another end here so two minutes
2024-03-24 11:13:36
349
https://i.ytimg.com/vi_w…M/hqdefault.webp
Leetcode: 349. Intersection of Two Arrays
POUMNJou4vc
In this video channel today's video, we In this video channel today's video, we solve the skyline problem that the solve the skyline problem that the suicide problem asks something in such a way that on suicide problem asks something in such a way that on one side it seems that the girls have that one side it seems that the girls have that their start point and end point is given by the nutrition channel their start point and end point is given by the nutrition channel which is required from rectangle 1 2 which is required from rectangle 1 2 80 for 3 minutes Next rectangle 80 for 3 minutes Next rectangle is 327 Friends, we have many is 327 Friends, we have many rectangles Governor, some of them are boiled, you are rectangles Governor, some of them are boiled, you are able to see all of them that now you have been able to see all of them that now you have been asked to print its length, you asked to print its length, you will get its will get its powder outline basically. powder outline basically. powder outline basically. asked you to paint the outline on the plane, but it is a pimple, but a salary. If I ask you to print this complete outline, when will you start printing infinite points or some lines, dots etc. Collectors got If this If this If this outline is to be printed then it is outline is to be printed then it is very difficult to convert it into the form of obscene output, then the very difficult to convert it into the form of obscene output, then the provident has given such provident has given such that this is a chord of the points you want to make, there is a that this is a chord of the points you want to make, there is a one quarter procedure, you will one quarter procedure, you will follow it, what is that? follow it, what is that? follow it, what is that? points, then don't give me a complete outline. If you give me only points, then which points at which you want to change the side, if I change the height of all those points, then the outline is created, that is, Let me Let me Let me show you, it's something like this, if you click on it, it is cat 210 show you, it's something like this, if you click on it, it is cat 210 338, then it is 210. 338, then it is 210. Loot may be a wooden scientist Ram Sir, he has given you the answer. Boss has said, 'How can I convert? Man, what should I do? Now he will be chatting online. It will start from 0 and onwards there will be years. He must have put one point here or Answer: OK Answer. How to convert in hotel?' That's what I am showing, so that 210 210 means that the match is going on this line, I am going on the site like a simple two, I will get the height tanning dark then convert it to 2-3 minutes and then Then next time I will Then next time I will Then next time I will get free electricity like electricity, then the side get free electricity like electricity, then the side effects will also go away, then I will move effects will also go away, then I will move forward that if forward that if a simple thing like Naxalism gets time, then I will go on the light bill a simple thing like Naxalism gets time, then I will go on the light bill and automatically I have got and automatically I have got this line to grow from here. this line to grow from here. this line to grow from here. ventures said that I will do it myself, you just tell me the position where you want to change something, go to zero with a film like Side Effects, then make that change, you tell me the rest to go ahead and I will tell you in the work, then there I will tell you in the work, then there I will tell you in the work, then there is a button of three, then the temperature on the team in just is a button of three, then the temperature on the team in just 120 comments on the printer for the last two days, 120 comments on the printer for the last two days, Chairman PL Punia And so we have to Chairman PL Punia And so we have to print only those points of that outline print only those points of that outline where you want to change that you where you want to change that you want to change. want to change. want to change. want to change the energy that now we want to do this so I told them that while following this project the up output is something like this which if I really follow it then it is a complete One thing, if you One thing, if you One thing, if you remove it from this side, I am from Abhishek Chopra on behalf of the director 's police team, when how can we do this, how can we do it, if I have been asked to print only from the point that changes the line, that Here someone's start will be closed, Here someone's start will be closed, Here someone's start will be closed, friends, apart from this, friends, apart from this, it can be anyone here, so it can be anyone here, so here you will not change, you are available in me, then from below it upwards, not possible, you Hisar to enter. Hisar to enter. Hisar to enter. process all the stars and ends meaningfully, no, I will separate one point and think whether something is increasing at this point, what is the If there is a If there is a If there is a need, I will separate the stars and need, I will separate the stars and process all the rectangles, process all the rectangles, then I said, start point then I said, start point S2 less than 80, then in this amendment, S2 less than 80, then in this amendment, make one rectangle for 2 minutes. make one rectangle for 2 minutes. If the lips are in the conversation, then one more thing has been given, cotton If the lips are in the conversation, then one more thing has been given, cotton hippy has been given. hippy has been given. hippy has been given. Teamwork Tank and print comment So if I wrote to everyone like this then I would not be able to know that according to which is the start point of the rectangle which is the endpoint because because I could have guessed whether it is 2009 then is 2009 then we do not know 507 someone we do not know 507 someone What should I do to reduce the pension point from this? What should I do to reduce the pension point from this? Now I could have kept the item bullion, one sabri Ankit Now I could have kept the item bullion, one sabri Ankit Bhai, tell me the city is two, if there is a point fall, then I will Bhai, tell me the city is two, if there is a point fall, then I will make end points par class, these two make end points par class, these two things, then the stomach will be covered with that, better than that, I things, then the stomach will be covered with that, better than that, I will make the height negative because the height will make the height negative because the height will make the height negative because the height yoga drop if someone's so many get even number to start point now log this is what you do why don't you make food or do this less many education sass handle weeks that I will tell in April wipes second acting inside the obscene rectangle be good Answer: If you make the start point Answer: If you make the start point Answer: If you make the start point negative then it will automatically go to Hundu. As per the negative then it will automatically go to Hundu. As per the clear explanation at this time, clear explanation at this time, 2010 has been there only. If I 2010 has been there only. If I delete it, then I will come to know about it. delete it, then I will come to know about it. Torch light, they would like more that Torch light, they would like more that online. online. online. - 15th Amendment Come on 16th Voice Mail 5 Comments Paris Oil Must 3 - 01 2010 that now do these do set two sort that now do these do set two sort needles in the answer is to give increasing order. needles in the answer is to give increasing order. Can't it be said that this tree Can't it be said that this tree Can't it be said that this tree put it at the end first and then put the one you want to change later because in the same way and said to the mint that we are one way, I will check your answer and here I will see it in the change, If I change it, then If I change it, then If I change it, then increasing and tummy are required. Said that you will make all these increasing and tummy are required. Said that you will make all these points famous in increase in wards, only points famous in increase in wards, only then if the answer comes then if the answer comes out in the increasing heart, then make half an inch in increase in out in the increasing heart, then make half an inch in increase in wards. If you make wards. If you make its best friend in increase secondary, then you will get its best friend in increase secondary, then you will get six points. six points. six points. that the answer depends on the export, then after that when I do the prince, then you will - nothing, first turn to a nanny, you will find this 117 less 10 on 117 less 10 on 9 not 9 not till the day of 20 till the day of 20 till the day of 20 Ajay Ko MP3 Ko - MP3 Ko - 09 - 800 124 Computer Jhaal Hips And I have set it now Jhaal Hips And I have set it now soft I have made it butt main Ishq India Twenty-20 & Twenty 459 till hotspot closed Not going to happen, Not going to happen, I am not going to answer all these points, shut up friend, no, like this point is the setting point of the triangle, it is also according to the starting point of the one, no, why friend, because it is over honey and because of this, there is a distortion Due to this point, the campaign Due to this point, the campaign Due to this point, the campaign cannot be cemented tight, so how did we cannot be cemented tight, so how did we lag behind, what will be felt, will lag behind, what will be felt, will not benefit, it is simple, not benefit, it is simple, what should I do, will I give a current affair, do thank, what difference does it what should I do, will I give a current affair, do thank, what difference does it mean, mean, what height am I now, then and online like now what height am I now, then and online like now what height am I now, then and online like now which height is the line drawn by Suji Rohit Prudential Life or like me because in the increasing and draft, it is on me, like me to you - this is the starting point of the tender, now a new rectangle is starting here. is tight so I will do something like that I still have a new rectangle storage on the divider whose height enter and because we have to draw the outline if you look at the quantum, museum wisdom I want to do that whose height If you want to do this, then If you want to do this, then how can you start traveling on the side which has the highest triangle meat out of all the active tenders, then where would you be traveling to this point for one reason, that is, you want to make an outline and make a style. Whose one will be the highest and will be posted on the porn site at this point, all the times active and among them whose heater will not leak out the most, the Dubai rectangle will remain, whose height is the highest, all those active rectangles remain, so as I process it, let me Felt that now I have activated a Bangalore first Felt that now I have activated a Bangalore first Felt that now I have activated a Bangalore first year plug and now I travel at zero. year plug and now I travel at zero. Its high-tech is its maximum height. Its high-tech is its maximum height. Whose m-cap is it? You will get to know. Well, if you Whose m-cap is it? You will get to know. Well, if you comment and make a change, X is comment and make a change, X is equal to two, but make a change on that side. equal to two, but make a change on that side. equal to two, but make a change on that side. tank, I have to take it, which is the maximum brother panel among all the active rectangles, then I will move ahead, the next 12323, from the month it was 2.5 feet more from the point and there are 1000 e. Now why five months leave? are 1000 e. Now why five months leave? are 1000 e. Now why five months leave? person, this is the maximum, so there toys us for a long time at this point, 15th change free foot, my answer is 350 na jaaye ka or a mixture of freedom of Kunwar chiffon, let's go to the next 555, one came my love How to understand the How to understand the How to understand the good of height in negative effect, if one good of height in negative effect, if one mode setting is on then there is another active mode setting is on then there is another active rectangle in it, how many up in it, all the rectangle in it, how many up in it, all the active rectangles in it, the maximum is active rectangles in it, the maximum is how much is the holiday, you are how much is the holiday, you are absolutely right in 2015 and how many types of rice are there in us now. absolutely right in 2015 and how many types of rice are there in us now. Whoever is doing it on the team, because of this, there will be Whoever is doing it on the team, because of this, there will be no need to do any tricks or side effects. no need to do any tricks or side effects. Children, in this event, the Children, in this event, the next change point is, I am next change point is, I am 1000 height to positive a height positive, it 1000 height to positive a height positive, it means a rectangle and it is happening that means a rectangle and it is happening that means a rectangle and it is happening that removing a rectangle, you are going to keep one, you are removing its height, you remove an active rectangle, basically, you use this height as your butt SIM, now we maximize which one is 12th among all the active rectangles, so now your But let's put it and on fifteen the But let's put it and on fifteen the But let's put it and on fifteen the meaning is changing here too. If you have to make any meaning is changing here too. If you have to make any change then to what extent are you changing this point. The reason is that change then to what extent are you changing this point. The reason is that some rectangle some rectangle is coming to an end now because of that the fight is coming to an end now because of that the fight is going on. Its picture and setting. is going on. Its picture and setting. is going on. Its picture and setting. looking for and at what height will I go, all the activated triangles, why is its maximum, if it is stylishly becoming the maximum one, then I will see Candy Crush playlist and drinking water, I will maintain the set alarm, the next nearest point of this rectangle, Appointment Back Side Positive Appointment Back Side Positive Appointment Back Side Positive Meaning and Appointment End Points So Meaning and Appointment End Points So you are removing a rectangle, you remove its height, it is you are removing a rectangle, you remove its height, it is not an active rectangle, the not an active rectangle, the knowledge is absolutely correct knowledge is absolutely correct that now among all the active likes, that now among all the active likes, who has the maximum 12:00 that you can do this who has the maximum 12:00 that you can do this experiment experiment experiment who has changed anything with his skill and not even Kushwaha, please keep it, what is it now, next welcome meaning make a height because positive one hangal's encounter meaning someone is removing all your manifest Get up at any time from the angles and Get up at any time from the angles and Get up at any time from the angles and remove the circle, this is absolutely true, now we remove the circle, this is absolutely true, now we maximize all the actives, whose is it, maximize all the actives, whose is it, I don't have any active, I had kept it in one hero so that I don't have any active, I had kept it in one hero so that Jio comes out, so many collections are Jio comes out, so many collections are friendly to the family, the good feeling is zero now. friendly to the family, the good feeling is zero now. We are on the play list, so what We are on the play list, so what needs to be changed, you are on this coordinator, needs to be changed, you are on this coordinator, which hyper will I go to, in all the articles, which hyper will I go to, in all the articles, which must be up to the maximum, which must be up to the maximum, then start moving forward that I have started the step then start moving forward that I have started the step starting point together, if a new color is clear. Do it otherwise, as many as 1000 active election live channels have scattered them or this coordinate has now been changed or placed on you, this flower is now purchased in this cord, as many team relative me, maximum light, when they melt, Our current current hide and Our current current hide and Our current current hide and maximize different is that the money goes to maximize different is that the money goes to next 99831 nor sunshine will get spent on nominates point because inch 9 m that not one comment how to reserve it from month try starting point 19 - 600 No and No and No and I will add saffron interesting point, I will add saffron interesting point, maximum retail in as many active, maximum retail in as many active, which site am I on now, near the temple, which site am I on now, near the temple, then to do something to maintain the children of the world, then to do something to maintain the children of the world, this is the encounter because only this is the encounter because only positive one, remove it, positive one, remove it, put 132 to the friends. put 132 to the friends. put 132 to the friends. which sites will take some changes in my maximum night and after the clans, I will have to add that the squad has snatched the chain and which one we want to go to, all the active in the next flight comment. in the next flight comment. in the next flight comment. remove the positive now that we have become whose rice now, the same rice does the same and now what is the maximum height, zero, there has been some change, because of this there has been a change in 2014 and now the maximum height is zero, Gotta recognize now look at this quickly Gotta recognize now look at this quickly Gotta recognize now look at this quickly quickly let me show you what so let's quickly let me show you what so let's just have one item okay 15742 just have one item okay 15742 help welcome 10 help welcome 10 13 talking about Enfield looting in the ballot boxes 13 talking about Enfield looting in the ballot boxes this butt this butt is nothing else this cut and something is nothing else this cut and something is nothing else this cut and something priority but why do we still have to find the maximum, so I will make the maximum practical, I will keep one current height, this is what I control right now, till when there is a point, I will add the height to the penalty key, but their maximum. And check the karma type, have you ever seen which one came then I will have to see if there is no change which one I will talk about if after removing some hair the current is in the last match then there is no need to do anything If it comes, you will If it comes, you will If it comes, you will remove its height from it, that remove its height from it, that side will not be necessary top, that IS not side will not be necessary top, that IS not necessary toe will be played, if I necessary toe will be played, if I know you about this point then what should I say in the party, know you about this point then what should I say in the party, you will know it once quickly I will tell you will know it once quickly I will tell you and you and you and what I am trying to say, then when I come to the security maximum, when I come to the ace endpoint, it could not be removed from the back remove. Platinum Singh, more names, what am I keep it aside - 10.00, then we will get this. keep it aside - 10.00, then we will get this. keep it aside - 10.00, then we will get this. answer is, if you have contacted me, then we will go to this channel subscribe, because of different differences and do the because of different differences and do the maximum maximum typing, it has come in handy, typing, it has come in handy, where did you add the twelfth train and set it. where did you add the twelfth train and set it. I drank the country right and Maximo, there is I drank the country right and Maximo, there is no difference in doing this, no difference in doing this, after all it after all it is St. Martin, if the is St. Martin, if the Bluetooth settings are turned off, then Bluetooth settings are turned off, then remove the positive one, now it is ₹ 15 parfait maximum na remove the positive one, now it is ₹ 15 parfait maximum na grind, then I said to print it, then grind, then I said to print it, then remove it. remove it. remove it. removed on its own, which is not difficult to remove on its own, maximum, due to which height, some change is needed in this team, a simple one, there will be a change on seven, you will change maximum 512, then you will start its alliance, maximum, previous Se Shyam Se Shyam Se Shyam Tere Naam Next Do not maintain this line Tere Naam Next Do not maintain this line because tank positive PM points, you want to because tank positive PM points, you want to remove it, murder priority remove it, murder priority because then who knows only the feet, because then who knows only the feet, when and what can't you do, you ca when and what can't you do, you ca n't remove the guy that time and n't remove the guy that time and sign sign sign a number on tut free mode in which I will write the letter that time, then I will write the properties, the place to remove the pet, find the find it, Keep in mind Keep in mind that although now one more thing that I want to tell you before crowning is that I have sorted the institute according to increasing difficulty marks then all should be coordinated at water but in this beginning those tips But I will give you an example But I will give you an example But I will give you an example that here I have two rectangles 624, so these six pieces will be cut from it 10th board Tenth Chapter 600 600 Subscribe for 1 minute 600 600 Subscribe for 1 minute from this point for from this point for specific information about specific information about increasing the height from if. increasing the height from if. But it will be here, But it will be here, here I had appointed the starting point, here I had appointed the starting point, so it is very useful here, so it is very useful here, like if I wanted to mean two hundred of it, then in the way, I can do it from here on mutton 608 first iterates it's here on mutton 608 first iterates it's commit later I write commit later I write recording this. recording this. recording this. will show it to the criminals by driving, points will be charged, why open it subscribe Free, if you don't drive in it before now then you will get this my front, this is my friend tight gyan-02 got the maintenance starting point, if it is 10:00 I 10:00 I 10:00 I alarmed in half an hour, there is a difference between the two, the alarmed in half an hour, there is a difference between the two, the correction is maximum, it is different, it correction is maximum, it is different, it needs to be changed, till now I will permit needs to be changed, till now I will permit you, Ravana - set your luck, starting point you, Ravana - set your luck, starting point 86869000, different rules, so keep rice on this, 86869000, different rules, so keep rice on this, rule six comments, then subscribe to our channel. rule six comments, then subscribe to our channel. Subscribe now and Subscribe now and give different in the mix, change yours and give different in the mix, change yours and follow the show as maximum item, then follow the show as maximum item, then commit six and remove one. If different in correct commit six and remove one. If different in correct sentence, six less 10 sentence, six less 10 kya hua tha to aapne bola tu par temple chali kya hua tha to aapne bola tu par temple chali jaaye request. jaaye request. jaaye request. your last six pack shrunk to 268, go to this wrong post, look at this, you have to go here, that erase the mixture aspect, not the stopping point here, you have to add, you have to force the six to be written in. Don't add points. Ok 600, you can go. Bring it for you. Sorry, definitely see. Six food, zero. Will you add staff awards? Commendation. Get set first and ask to avoid these points every day. After all, the artist will leave from here if we do second shopping. How does this expiry date happen, if you make it 7th in different wards of this height, now let's see how it will work, it is absolutely a good method, then in the FD account - channel, I have added Amla height different and what is the maximum that can be extended that which There is no Mexico, There is no Mexico, There is no Mexico, remove dad, first Play Store remove dad, first Play Store Google, I have to do two quits, then time, I remove Google, I have to do two quits, then time, I remove clothes, remove tan, clothes, remove tan, now different has come, maximized now different has come, maximized will join, tension so x is equal to will join, tension so x is equal to six, you need to go to zero. six, you need to go to zero. And the point is over, then the matter has been made, so this is And the point is over, then the matter has been made, so this is your correct approaches, how will you your correct approaches, how will you sleep, how sleep, how can you subscribe, this will work in this, can you subscribe, this will work in this, kiss Brian, I will show you the kiss Brian, I will show you the information commissioner from the wound, try it once, then you will information commissioner from the wound, try it once, then you will get the ID like this guy. get the ID like this guy. get the ID like this guy. both are ending at the same point but it is important that both are starting, if you do the range in the increasing day then in the right way we are starting lighter, then you need to tell this point daily. If you If you If you go, then go for the go, then go for the loot, there is no need to point this here, loot, there is no need to point this here, when you increase the height increase in these wards, if you when you increase the height increase in these wards, if you do it in your style, then do it in your style, then it will also come against you, as you it will also come against you, as you can see, make some examples and check the can see, make some examples and check the cup. cup. cup. us is becoming the other, if in this also because both of them have SIM in 101st place, if you do increasing in water marriage, then things will take years, if you do it in decreasing or not, then it is his own creation, so Shark slide problem, Shark slide problem, Shark slide problem, turn it quickly, if you all turn it quickly, if you all complete it, then it will be absolutely fun, complete it, then it will be absolutely fun, one drop, two call, loot site, hello viewers, viewers, Ajay has one, this is dishonor, sexy juice, you are worried Can do it Can do it Can do it yes son do it yes son do it to Ajay to Ajay Jhaal video has happened Jhaal to Ajay to Ajay to Ajay that this class is supported friend I have six only two But in this model, I told you that ok, I will soften it, if I ever get a final chance on the decision of space class, if I keep it, now there is a skirt, then the first thing I will think of is that I need a play list, I need an address, and if it is ten, I will give him the Chanur list. A question: What will be kept in the new tariff list, what will be written in it, because here we have given the toys toys for it combination, first of all we have separated this, the one who separates them is that all these cords are island these cords are island building good thought loop I plus building good thought loop I plus It's new background so I will tell this It's new background so I will tell this for that I need start points for that I need start points 8083 but 8083 but building fennel free mode on ke building fennel free mode on ke din paun inch right hu din paun inch right hu invented invented that these were teachers now I have to do only to I I I will pass the number in the new leg, think about it, will pass the number in the new leg, think about it, because I am on it, start because I am on it, start point with negative file and quite point with negative file and quite impressed, add point in it with hydrogen, impressed, add point in it with hydrogen, fixed limit, fixed limit, now 100 tattoo collection sports ki Laxman spotless, now we have to set a pin So let's find So let's find So let's find one and make one, which I request. The answer is equal to one answer is equal to one that New Year, a steam, a plate, now we will rice on it, I went to them, Max Player, Tubelight Solid, all these active rectangles, The The The situation is to new poverty why situation is to new poverty why then one Sim's karma brother to friend thank then one Sim's karma brother to friend thank 120 only now the problem is in the list so this 120 only now the problem is in the list so this was my 471 120 Scotland list start was my 471 120 Scotland list start speech speech that I plus one more that I plus one more add one more to the low priority queue and set it to add one more to the low priority queue and set it to zero zero zero is in the western street, then I have a maximum of zero, that child, when the news came, then I started doing rice, then the contact will come out after having fun, then list dot that I do not acid, I have taken one. I have taken a me this or so much that I have taken out 2012latest Cancer has happened that this I returned took a stay for father now things two things variety of top cosmopolitan meaning starting point and white skirt amazon places points I another newton start I another newton start I another newton start made in the active rectangle then I will add it in the wells, the height from the butts is negative, I have placed it, so one is this positive, then try to come to the ground, this is the starting point 10 top 10 news on TV August solution I will August solution I will August solution I will remove the positive APN point, I will not just remove the positive APN point, I will not just write like this, the one with the back is not mobile write like this, the one with the back is not mobile that I will finalize the height or those who do Taimur that I will finalize the height or those who do Taimur and soldier complex video love oo and soldier complex video love oo now you have to check, so what should you now you have to check, so what should you check, whatever time brother do. check, whatever time brother do. check, whatever time brother do. Juppy Chuke is tied on the felt tip and the life tube is made by me in its collection. Start the revolver. I want to do something different from Ghr Ghr. That these teacher type tamping to new address were on a pedestal, first of all I will find you, which contract, where will I change my life, I will come together and investigate, what will I do in a week, I am going to give you the maximum of the taught laddus, In the maximum In the maximum In the maximum liter you have, it changed after doing it and on liter you have, it changed after doing it and on which site you should spend time. which site you should spend time. Now let us simply slide it and add it to take Now let us simply slide it and add it to take Yadav. I have a Yadav. I have a small one on it, I have not given it to Temple Run. small one on it, I have not given it to Temple Run. In that ex-cop wanted to go to PT, made In that ex-cop wanted to go to PT, made a perspective and gave it a list of two sizes to the a perspective and gave it a list of two sizes to the play list, he gave his blessings, friend, in this play list, he gave his blessings, friend, in this list of lists across the state, it is white, sat for 15 minutes, now covered it, is white, sat for 15 minutes, now covered it, take it and fiber current you. take it and fiber current you. take it and fiber current you. half an hour of your decision in some corner, half an hour of your decision in some corner, Com has also added 30 which are activated, see from Com has also added 30 which are activated, see from everywhere or have done Snapdeal. Dear everywhere or have done Snapdeal. Dear friends, it's like you will come out from here and friends, it's like you will come out from here and start touching it. start touching it. start touching it. Malfunction in time, College Monday, as soon as possible, Lipsy, I did something, Ajay, Ajay should Ajay should that a ball has fallen from the building, that a ball has fallen from the building, here English language language here English language language Language I made it a priority, I made it a priority, which one has which one has previous song Phir Phir Cross Samadhi Jhal 2013 I week - Previous is blank 2013 I week - Previous is blank MP3 MP3 is a matter of importance to Ajay, The The The problem is problem is that Ajay can get the electrolyte that Ajay can get the electrolyte without any problem in the mix video.
2024-03-22 10:47:03
218
https://i.ytimg.com/vi/P…axresdefault.jpg
The Skyline Problem || Leetcode
VBvPsvwSifw
this question is question number 350 intersection of two arrays two given two intersection of two arrays two given two integer integer arrays numbers one and numbers two arrays numbers one and numbers two return an array of their intersection return an array of their intersection each element in the result must appear each element in the result must appear as many times as it shows in both arrays as many times as it shows in both arrays and you may return the result in any and you may return the result in any order order so uh let's say we have something like so uh let's say we have something like num is a one num is one num is a one num is one equal to equal to one two one two two one and plus 2 two one and plus 2 equal to equal to 2 and 2. 2 and 2. so the intersection is 2 and 2 here so the intersection is 2 and 2 here or if you have something like numbers on or if you have something like numbers on 495 and number 2 9 4 nine eight four 495 and number 2 9 4 nine eight four interception is four nine or nine four interception is four nine or nine four okay so okay so um um how am i going to solve this there might how am i going to solve this there might be different ways to do this be different ways to do this uh the way that uh the way that first of all came to my mind was two first of all came to my mind was two pointers pointers um um so that's what i'm going to do so that's what i'm going to do before that i want to sort the array before that i want to sort the array so so the complexity of sorting it is not the complexity of sorting it is not going to be that bad going to be that bad compared to compared to um um going over the whole thing going over the whole thing uh all of them uh all of them so let's uh so let's uh do that let's just say number one equal do that let's just say number one equal to to sorted uh nuns one and sorted uh nuns one and numbs two nickel two sword numbs two nickel two sword numbers two so these are the two numbers two so these are the two uh sort of arrays that we have and after uh sort of arrays that we have and after that so this this will give you that so this this will give you something like something like uh let's say uh uh let's say uh one one one one two two two two two two i'm gonna delete this one two two i'm gonna delete this one and also this one so let me join with the other one so i'm going to delete these two here and say the other one would be after sorting the little tool too so uh i need two pointers i equals to uh zero and j close to zero and i'm gonna have a list of the list [Music] equals to nothing and i want to look through the uh the arrays okay so i'm going to say while i is less than len of the first one number one and j less than of number two when i say that that means that whatever is the smaller one i'll just end at that point part like if this gets bigger or equal then it just stops there bigger or equal then it just stops there so it will just loop over the smaller so it will just loop over the smaller one basically okay so while we're one basically okay so while we're looping over we start with one and two looping over we start with one and two we check if these are equal or not we check if these are equal or not uh so we want to see the intersection uh so we want to see the intersection right so we have to check if it's equal right so we have to check if it's equal or not so let's say they are equal or not so let's say they are equal if uh if uh is one is one i i equally equal to numbers to equally equal to numbers to j j then what do you do you basically say then what do you do you basically say output dot append you want to have to output dot append you want to have to the output the output array array uh that numbers of 1 i or minus 2j uh that numbers of 1 i or minus 2j doesn't matter either of them because doesn't matter either of them because they're equal and then i just uh add to they're equal and then i just uh add to it one time it one time back to the both uh back to the both uh pointers here pointers here if there are duplicates like let's say if there are duplicates like let's say here here let's say i is here and j is here these let's say i is here and j is here these are equal are equal then you you go to the next one they're then you you go to the next one they're they're again the same thing you will they're again the same thing you will just add the same thing again just add the same thing again so so uh uh the question earth the question earth uh each element in the result must uh each element in the result must appear as many times as it shows in both appear as many times as it shows in both arrays so that's something we want okay arrays so that's something we want okay lf um lf um this is this is not equal anymore and not equal anymore and let's say this one is smaller let's say this one is smaller if not i is smaller then what do you do if not i is smaller then what do you do you basically say hey you basically say hey all right well it's difficult with one all right well it's difficult with one so so one is smaller you just go to the next one is smaller you just go to the next one one is smaller than you go to the one one is smaller than you go to the next one next one okay else okay else else would give you else would give you i'm not uh i'm not uh explaining explaining the next condition i'm not saying lf is the next condition i'm not saying lf is because else is the because else is the only condition only condition that is remaining which is that is remaining which is uh one eye bigger than those two i uh one eye bigger than those two i thought let's say this is three let's say let's say we had something like this actually we had something like this actually three and three three and three if this is uh three then you just go to if this is uh three then you just go to the next one the next one um um you just uh yeah you basically say you just uh yeah you basically say this goes to the next one basically j this goes to the next one basically j plus equal to one yeah so that you want plus equal to one yeah so that you want to see that if there's a bigger one to see that if there's a bigger one something like this let's say something like this let's say you had something like this you had something like this so you say this equals to this so you say this equals to this now this is bigger then you go to this now this is bigger then you go to this one with this now this is uh bigger then one with this now this is uh bigger then you go to this one then so you go to this one then so yeah this one is satisfied then you go yeah this one is satisfied then you go loop through this one loop through this one equal equal i mean i mean and that's done basically because this and that's done basically because this one is done yeah so it's done one is done yeah so it's done so this is it this is uh so this is it this is uh the whole thing the whole loop the whole thing the whole loop and you return output here and you return output here that should work yep it worked and if you submit this you'll say see that it works so this is the answer to question number 350 intersection of two arrays two we did it with two pointers we sorted
2024-03-24 11:16:51
350
https://i.ytimg.com/vi/V…fw/hqdefault.jpg
Leetcode: 350. Intersection of Two Arrays II
gfw86duEa8k
this is the 35th leeco Challenge and it is called search insert position give an is called search insert position give an assorted array of distinct integers and assorted array of distinct integers and a Target value return the index if the a Target value return the index if the target is found if not return the index target is found if not return the index where it would be if it were inserted in where it would be if it were inserted in order you must write an algorithm with order you must write an algorithm with olog and runtime complexity so if you olog and runtime complexity so if you get one three five six and the target is get one three five six and the target is 2 the output will be one because 2 the output will be one because currently at index 2 or index 1 is 3 but currently at index 2 or index 1 is 3 but 3 is greater than two so two would be 3 is greater than two so two would be there instead and three would be pushed there instead and three would be pushed upwards if you I skipped one up here so upwards if you I skipped one up here so if you get Target five that just returns if you get Target five that just returns two because that's where it is if you two because that's where it is if you have Target seven have Target seven that would be four because there would that would be four because there would have to be an extra spot up here so zero have to be an extra spot up here so zero one two three one two three seven is greater than six so I put seven is greater than six so I put before okay let's get started okay so before okay let's get started okay so first things this is going to be another first things this is going to be another band research one band research one so we'll do int lower equals zero and so we'll do int lower equals zero and upper nums minus one so some things we upper nums minus one so some things we can do straight right if can do straight right if nums lower nums lower is is greater than not equal to Target greater than not equal to Target turns zero turns zero if nums upper if nums upper is less than Target is less than Target return num's length return num's length and I guess we can just also do if it and I guess we can just also do if it equals Target equals Target turn upper Okay so turn upper Okay so we'll do while we'll do while lower is lower is less than upper less than upper we then need to do int current equals we then need to do int current equals upper minus upper minus upper minus lower upper minus lower then divided by two then divided by two its current is less than lower do that its current is less than lower do that if if current is current is a Target a Target current is less than Target current is less than Target yeah lower equals Target yeah lower equals Target if current nums there we go if current nums there we go we do that if nums current equals Target turn current also add a check the top f lower equals upper minus one return low I think or would this be returned upper I think so that actually even turn upper because we're kind of Shifting it up and then in which they return upper so let's run it just to see what outputs we'll get and we've got the correct outputs cool okay let's copy this put into liquid and see if it works with all the other ones so put it here run it just make sure with the test cases if those are all good which they also now submit okay cool that was the solution sorry that's the 35th leaky challenge called search insert position if you like this video make sure to like And
2024-03-20 08:53:32
35
https://i.ytimg.com/vi/g…axresdefault.jpg
LeetCode in C# | 35. Search Insert Position
wjdrjFKyalk
hello all right let's uh code minimum all right let's uh code minimum deletions to make string balance done deletions to make string balance done this before but don't think i've made a this before but don't think i've made a video about it you're given a string s video about it you're given a string s consisting only of characters a and b consisting only of characters a and b you can delete any number of characters you can delete any number of characters in s to make s balance s is balanced if in s to make s balance s is balanced if there is no pair of indices i j such there is no pair of indices i j such that i is less than j and s i is equal that i is less than j and s i is equal to b and s j is equal to a return the to b and s j is equal to a return the minimum number of deletions to make s minimum number of deletions to make s balance no pair of indices such that balance no pair of indices such that there is a b before an a so for this one there is a b before an a so for this one i know i definitely have to remove i know i definitely have to remove either this b or this a here definitely either this b or this a here definitely all the deletions would be somewhere all the deletions would be somewhere within this range here because you have within this range here because you have two a's here i don't need to do anything two a's here i don't need to do anything with those the b at the end don't have with those the b at the end don't have to do anything with those that for sure to do anything with those that for sure so out of this range here what do i need so out of this range here what do i need to delete well i could either delete to delete well i could either delete three b's or two a's so it would be two three b's or two a's so it would be two now is there a problem with that logic now is there a problem with that logic um i have a feeling i'm oversimplifying um i have a feeling i'm oversimplifying it hey i just realized um it hey i just realized um there there must be must be some some examples where i have to move number of examples where i have to move number of a's and a number of b if i have a a a b a's and a number of b if i have a a a b b b b and i replace this with an a b b b and i replace this with an a replace this with a b replace this with a b moving all either all a's or b's is moving all either all a's or b's is definitely not the optimal solution in definitely not the optimal solution in this case here it's best to just remove this case here it's best to just remove this b and this a i see i see this is a this b and this a i see i see this is a somewhat difficult question how do i somewhat difficult question how do i actually figure that out think it all actually figure that out think it all depends on depends on finding a split point so for any finding a split point so for any position i want to find out position i want to find out what happens if i remove all b's from what happens if i remove all b's from this substring and remove all a's from this substring and remove all a's from this substring now does that work for this substring now does that work for this case here yes it does this split this case here yes it does this split would be here and here so in this case would be here and here so in this case i'm removing all a's from here and i'm removing all a's from here and removing all b's from here which is not removing all b's from here which is not so it's all about finding a split which so it's all about finding a split which means i can have some prefix means i can have some prefix sums for the number of a's given a split sums for the number of a's given a split and a number of b's given a split okay and a number of b's given a split okay let's implement this i need to keep let's implement this i need to keep track of the prefix track of the prefix sums sums of size s dot size plus one and have two of size s dot size plus one and have two of these should i initialize it to zero of these should i initialize it to zero no i don't need to i just have to say p0 no i don't need to i just have to say p0 at zero is equal to zero p1 at zero is at zero is equal to zero p1 at zero is equal to zero and then go through each equal to zero and then go through each character in the string and say ps of i character in the string and say ps of i plus 1 plus 1 is equal to ps of i plus is equal to ps of i plus whether or not this whether or not this character here at s character here at s is equal to is equal to a or not a or not this one here would be equal to whether this one here would be equal to whether or not it's equal to b um and then we or not it's equal to b um and then we can go through each of the positions and can go through each of the positions and check so check so given that your string has let's say a given that your string has let's say a a b there's actually many different a b there's actually many different positions so we have zero positions so we have zero one two three four let's say zero one two three four let's say zero represents removing all a's from the represents removing all a's from the string and the feet and four represents string and the feet and four represents moving all b's from the string and one moving all b's from the string and one represents moving all b's from this represents moving all b's from this substring here just a substring here just a there's none so that's fine in fact there's none so that's fine in fact i don't need the 4 here because when i'm i don't need the 4 here because when i'm at the 3 that's inclusive of 3 at the 3 that's inclusive of 3 the left sub string less than or equal to s size plus plus i so for zero basically asking how many in the left substring will be ps of zero or how many b's in the left substring so ps of one at i minus ps of one at zero i didn't need that's always zero so i just i didn't need to subtract that the right on the other hand is everything up to the end minus minus ps of zero ps of zero so not including i so not including i i think that's correct i think that's correct and then and then we keep track of an answer we keep track of an answer to be to be equal to the whole string and then do equal to the whole string and then do answers equal to min of the answer and answers equal to min of the answer and the left plus the right the left plus the right and then return and then return enter enter this should be this should be zero zero and it should be one the answer is 2 here and i'm thinking that the answers is 2 all right let's let's give that a run all right let's let's give that a run and see awesome that uh seems to work time complexity would be o of n space is also o of n because of the prefix sums which is definitely good enough thanks for watching if you have any questions leave it in the comments leave a like and subscribe and i'll see
2024-03-19 18:31:11
1,653
https://i.ytimg.com/vi/w…axresdefault.jpg
1653. Minimum Deletions to Make String Balanced - Daily Leetcode (Day 56)
i9Pg99oNK18
Hi gas welcome and welcome back to my channel so today our problem is remove stones so today our problem is remove stones you minimize the total so this is the problem you minimize the total so this is the problem statement what have they given us here they have statement what have they given us here they have given us a wait called Piles given us a wait called Piles where your Piles I represent. where your Piles I represent. Here is the number of stones Hindi rectangle file ok Here is the number of stones Hindi rectangle file ok and here we have given you a wait and here we have given you a wait so what can you do here you so what can you do here you can perform exactly the operation can perform exactly the operation this operation is yours what if someone this operation is yours what if someone piles i pay and number of stones is there piles i pay and number of stones is there piles i pay and number of stones is there what you can do is, you can remove as many stones as the fluid value of N/2 from there. Okay, so what you have to find, here you have to find the minimum possible total number of stones remaining after applying the So So So you have to perform these operations and examples of finding the minimum possible number are this is your pie, what is in it is examples of finding the minimum possible number are this is your pie, what is in it is your forest and what is this second yellow paper your forest and what is this second yellow paper nine stones are okay what you nine stones are okay what you can do is you can perform an operation here. can do is you can perform an operation here. Inside which, when you do what, if Inside which, when you do what, if you have n number of stones on any yellow, you have n number of stones on any yellow, then what will be the floor value of it and by then what will be the floor value of it and by you, okay, this much, what can I do from here, you, okay, this much, what can I do from here, can you mine, okay, can you mine, okay, what can you do with this, mines? what can you do with this, mines? look here twice you can reduce this either you look here twice you can reduce this either you do this or do this or do this or do this do this or do this or do this or do this or do this do this then if or do this do this then if here you have to reduce here you have to reduce here you have to reduce stones, then in which operation will you perform it? Which one will have more names? Which one will have the maximum number of stones? I will perform it first so that you will think about reducing it. What answer do you have to do? How to find the answer? Finding the If yes, then If yes, then If yes, then when will be the minimum? When you halve a big number and when will be the minimum? When you halve a big number and mince it, then what will be the biggest mince it, then what will be the biggest number here? If the smallest number here? If the smallest number is nine, then what will be the half of nine? The number is nine, then what will be the half of nine? The fluid value of 9/2 here. fluid value of 9/2 here. This will be your four, right, so This will be your four, right, so if we remove four number of students from here, if we remove four number of students from here, then how much will be left here, this then how much will be left here, this five will be left, okay, now what happened to the five will be left, okay, now what happened to the stones you have, five is four, five is stones you have, five is four, five is right, now you have one operation. right, now you have one operation. right, now you have one operation. now how much operation do you have left, one more is left, so now you have the option, which of these three would you like to do? There is a five here too, here there is also a 5, here there is a four, so we will do it only on the one with five because If this will reduce the loss to half then we can do either of these two things. Otherwise, if we remove the floor of five from here, the flop value of 5/2 will be Or Or Or do it from here, let's do it from here, so it will be three, so do it from here, let's do it from here, so it will be three, so what will be the total, once 3 4 7 5 what will be the total, once 3 4 7 5 12, then in the end, this will be your minimum amount, this will be the total amount 12, then in the end, this will be your minimum amount, this will be the total amount left left after performing this operation, that will be your after performing this operation, that will be your answer, you will add. answer, you will add. answer, you will add. how much will you get if you add here, you will get 12, you will return 12, okay, let us also look at this example, how many operations can we perform here, you can perform three operations, you have the You can do it You can do it You can do it here, you can do it here, you can do it here, you can do it here, you can do it here, you can do it here, you can do it here, but you can only do three, so here, but you can only do three, so now who should give preference, if we remove the floor value of 7 - 2 What will be the floral value of ? What will be the floral value of ? What will be the floral value of ? If it is three, then here 4 will be left, so this is If it is three, then here 4 will be left, so this is done, your 4 is already four, this three is done, your 4 is already four, this three is six, now you will have to perform the second operation six, now you will have to perform the second operation because now you will have two operations because now you will have two operations saved because you have done one right, so saved because you have done one right, so one. one. one. like to do it in six because it is the highest otherwise if you do it here then what will you be left with? The load value of six minus six by tu will be your three. Six minus three equals tu three so here Now you have one more Now you have one more Now you have one more operation left. Now where will you perform? operation left. Now where will you perform? Here, there is a four. Here, there is also a four. Here, there is a four. Here, there is also a four. Both are maximum, so you Both are maximum, so you can do it on any of these two. So, here, four by four. can do it on any of these two. So, here, four by four. Minus. Minus. Minus. left. Okay, so what will be your total? 2 3 5 538 84 12, right? What can we do in this way, if we can solve this problem, then how will we know For this, For this, For this, what will we do, will we give it a priority, what will we do, will we give it a priority, what will we do, we will put all the data in it, what will we do, we will put all the data in it, so here let's look at this example, so here let's look at this example, if we put the second one here, then we will give it the maximum priority of 7, then it will be on top. give it the maximum priority of 7, then it will be on top. give it the maximum priority of 7, then it will be on top. then yours will be three, then what will be yours, what will be four? How many times will we perform this operation, we can do it three times, so when we do it for the first time, the top element will be the maximum, we know that because the maximum priority of the priority The element on the top is The element on the top is The element on the top is maximum, so if maximum, so if we find from here, we will get 7, then what will we do from 7 by 7 we find from here, we will get 7, then what will we do from 7 by 7 by 2, if we subtract it, then by 2, if we subtract it, then how much will be left, your 7 - 3 / 2 is ok, it will Given Given Given four here, if you insert four, then four will come somewhere here, right then now how much operation do you have left, two are left, then you can do it with three, then where will you get the maximum element at the top, then you will put it at the top, You will mine the top half of it, You will mine the top half of it, You will mine the top half of it, three will be left, then you will insert it, then three will be left, then you will insert it, then where will the three come, here will the four come where will the three come, here will the four come on your top, otherwise you will have only one on your top, otherwise you will have only one operation left, now you can do only one, then the operation left, now you can do only one, then the top will come out, 4 will come out, 4 by 4. top will come out, 4 will come out, 4 by 4. top will come out, 4 will come out, 4 by 4. do four minus four by you, then 2 will come out here, so what will you do with this tu, if you insert it here, it will be somewhere here, you do not have any operation left, so you will not do this further, What will we do? We will What will we do? We will What will we do? We will take each one out and add it, then take each one out and add it, then four plus three plus three by plus you, four plus three plus three by plus you, then what will happen here is 7310 you 12. If this is then what will happen here is 7310 you 12. If this is done, done, then I hope you must have understood this, we would have then I hope you must have understood this, we would have seen its code also. see here, what will we do here, see here, what will we do here, why will we take a priority and what will we do in it? First of all, we will insert all the elements in it. Right, so here we have taken the priority by the name PK and what have we done by inserting all the elements in it? Okay, after that what will we do by taking a Vile loop - - This means what operation will we perform in it, what will we do in it, will the top element come out, okay, we will also pop it, then what we will do is push it in Floor Floor We will add it in one element, We will add it in one element, okay, we will keep adding it till our PK i.e. okay, we will keep adding it till our PK i.e. priority is not being done, then we will add all the elements in all, then what will we do in the last, add all the elements in all, then what will we do in the last, we will return it, okay that is ours. we will return it, okay that is ours. What will be the remaining stones because if it is What will be the remaining stones because if it is minimum then I hope you have understood this. minimum then I hope you have understood this. If you liked the video then If you liked the video then please like, share and subscribe. please like, share and subscribe. Thank you.
2024-03-25 13:32:20
1,962
https://i.ytimg.com/vi/i…axresdefault.jpg
1962. Remove Stones to Minimize the Total
iBGv2HsoK4M
welcome to Pomodoro Joe for Friday February 24th 2023 February 24th 2023 today we're looking at lead code problem today we're looking at lead code problem 1675 minimize deviation in Array this is 1675 minimize deviation in Array this is a hard one a hard one you're given an array nums of n positive you're given an array nums of n positive integers integers you can perform two types of operations you can perform two types of operations on any element in the array any number on any element in the array any number of times if the element is even you can of times if the element is even you can divide it by two divide it by two if the element is odd you can multiply if the element is odd you can multiply it by two it by two the deviation of the array is the the deviation of the array is the maximum difference between any two maximum difference between any two elements in the array return the minimum elements in the array return the minimum deviation the array can have after deviation the array can have after performing some number of operations performing some number of operations okay okay and let's see we have at least two and let's see we have at least two elements but fewer than five times ten elements but fewer than five times ten to the fourth to the fourth and the elements can range from 1 to 10 and the elements can range from 1 to 10 to the ninth that's a big range to the ninth that's a big range all right so we'll put 25 minutes on the all right so we'll put 25 minutes on the Pomodoro Timer and get started all right first thing I always like to do is create some result placeholders let's start with that and now I'm looking for the minimum value so I'm going to set this to infinite to start with and we'll work our way down and then we'll return okay so I'll walk you through this step okay so I'll walk you through this step by step we'll build this up from basic by step we'll build this up from basic principles until we have a working principles until we have a working solution solution now the first thing we need to do is now the first thing we need to do is figure out how do we approach this figure out how do we approach this problem problem so in this problem we just have this so in this problem we just have this list of nums and we're trying to find list of nums and we're trying to find the minimum deviation between any two the minimum deviation between any two elements elements so I think the first thing that I'll do so I think the first thing that I'll do is is figure out the current minimum deviation figure out the current minimum deviation before performing any operations before performing any operations and for that let's see we could compare and for that let's see we could compare all the elements to each other but I all the elements to each other but I don't think we need to do that we really don't think we need to do that we really just need to find the maximum element just need to find the maximum element and the minimum element and that's going and the minimum element and that's going to be our to be our minimum deviation that the array can minimum deviation that the array can have have so that's pretty straightforward we just so that's pretty straightforward we just Source the numbers and now we can set our result to this so the sorted numbers are going to go so the sorted numbers are going to go from lowest to highest so we'll take the from lowest to highest so we'll take the highest element and we'll subtract the highest element and we'll subtract the lowest element and that gives us our current result so we can actually get rid of this up so we can actually get rid of this up here because we already have a better here because we already have a better answer the next thing I think I want to do is figure out how do we use these operations to impact our minimum deviation here looks like we have two operations we can do we can divide even Elements by two or we can multiply odd Elements by two okay so here's a little diagram of our goal here and some high value and we want to bring and some high value and we want to bring those two closer together those two closer together that's basically all it comes down to we that's basically all it comes down to we have a low value a high value that's our have a low value a high value that's our current minimum deviation I need to current minimum deviation I need to bring these two closer together to get a bring these two closer together to get a smaller minimum deviation now from the low end we can make these go higher and from the high end we can make them go lower so we can take the lowest element and multiply by two to get it higher we can take the highest element and divide it by 2 to make it go lower so let's see on the low end with odd numbers we can multiply by two and on the other end we can make even and on the other end we can make even numbers go lower by dividing by two so this is kind of a diagram that illustrates where we're going with this we can bring our lower values toward the high we can bring our higher values toward the low but only odd values can increase and only even values can decrease so we'll basically look for odd values at the beginning of our sorted nums and push them higher and we'll look for even values at the large end of our nums and push them lower that's pretty much all we can do so all right let's start by pushing the all right let's start by pushing the lower numbers higher so let's see lower numbers higher so let's see while the numbers at the low end are odd while the numbers at the low end are odd we can push them higher so I'll sort of nums at 0 mod 2 is equal to one then we can push this higher so we'll just multiply that lowest number we'll just multiply that lowest number by two by two oh but now that we've changed this oh but now that we've changed this number we have to resort okay that's already a red flag we'll so sorting over and over and over again so sorting over and over and over again is already an indicator that we probably is already an indicator that we probably need to do this a different way okay so now we've brought our lower end towards our upper end okay so now while our highest number is okay so now while our highest number is even let's divide it by two to bring it even let's divide it by two to bring it lower and again because we've changed this value we're going to have to resort okay now we've brought our highest value okay now we've brought our highest value lower and our lowest value higher let's lower and our lowest value higher let's calculate a new result calculate a new result so let's see our result now will be so let's see our result now will be well we'll probably need the minimum of well we'll probably need the minimum of either the result or this new Range so either the result or this new Range so what will that be okay so this is pretty good I think we might need to actually do some recalculation of our result sooner for example this could be bringing for example this could be bringing numbers down that give us a smaller numbers down that give us a smaller result result before we finish this entire Loop there before we finish this entire Loop there could be some intermediary results that could be some intermediary results that are actually lower than our current are actually lower than our current result so let's recalculate this result result so let's recalculate this result every time we go through that way we catch any minimum results okay we pass okay we pass so again we're just sorting our numbers so again we're just sorting our numbers finding the biggest number the smallest finding the biggest number the smallest number and the difference in between number and the difference in between then we're going to take all of the odd then we're going to take all of the odd numbers that are on the low side and numbers that are on the low side and we're going to bring them up by we're going to bring them up by multiplying them by two so we'll bring multiplying them by two so we'll bring them closer to the high end and then them closer to the high end and then we'll find all the even numbers on the we'll find all the even numbers on the high end and we'll bring them lower by high end and we'll bring them lower by dividing by two dividing by two let's submit this and see how we do foreign but we do get a wrong answer in here so we beat 59 out of 75 but we've got one wrong answer now I think that one wrong answer could be because we're not calculating this result while we're changing our minimum values we're only calculating it while we're changing our high values we might need to do okay so we didn't get any wrong answers okay so we didn't get any wrong answers this time this time but we do run out of time but we do run out of time we only go through 72 out of 75 test we only go through 72 out of 75 test cases although 72 out of 75 is pretty cases although 72 out of 75 is pretty good we're really close we just need to good we're really close we just need to pick up those last three test cases pick up those last three test cases okay so how do we optimize this we have okay so how do we optimize this we have a decent solution it just needs to be a decent solution it just needs to be optimized optimized it all comes back to this one red flag it all comes back to this one red flag here now resorting these numbers over here now resorting these numbers over and over again is a lot of extra work and over again is a lot of extra work especially because they're mostly sorted especially because they're mostly sorted all we're doing is changing one element all we're doing is changing one element now there's a data structure that we can now there's a data structure that we can use that will help us with this that's a use that will help us with this that's a heap heap the Heap is a sorted data structure that the Heap is a sorted data structure that sorts on insert so it remains sorted the sorts on insert so it remains sorted the entire time we don't have to resort entire time we don't have to resort every single element every single element so let's use a heap all right so now we will transform this all right so now we will transform this whole thing to use a heap instead of whole thing to use a heap instead of sorted nums this is going to get a sorted nums this is going to get a little bit complicated so let's break little bit complicated so let's break this down this down now in the very beginning well we're now in the very beginning well we're bringing lower numbers higher we'll want bringing lower numbers higher we'll want to use a Min Heap that means we'll be to use a Min Heap that means we'll be able to find the minimum numbers very able to find the minimum numbers very quickly quickly so let's create our Min heat to start so let's create our Min heat to start with so to create a heap you just call on a list so in this case it's our on a list so in this case it's our sorted nums and that's it to create our Min Heap okay now the mean Heap will always have the minimum value at the zero index so instead of saying sorted nums here we and then this will be replaced so I'll and then this will be replaced so I'll just comment these out so in this case we actually have to do a is a heat pop on our main Heap and then instead of having to sort our and then instead of having to sort our nums we just will do a heat push and nums we just will do a heat push and that keeps everything sorted all right this looks pretty good so while the smallest number on our Heap is odd we'll pop it multiply it by two and push it back onto our Heat all right what about this now the sorted numbers was sorted every time so we could get our max value really easily and our Min value we can still get our Min value here really but this max value is not the same we're but this max value is not the same we're changing our values inside our mint Heap changing our values inside our mint Heap we can't get the max value that easily we can't get the max value that easily so we'll just have to keep track of that so we'll just have to keep track of that ourselves so we'll set it equal to our maximum and then we'll have to just keep track and then we'll have to just keep track of our new values that we're pushing in of our new values that we're pushing in and possibly replace our max value because we're multiplying this Min num by two it's possible that we will exceed our Max num so we'll want to keep track of that and then down here this will be Max num minus our Min heaps minimum value so that takes care of the low end what about the high end we'll have to do something similar for the high end but the high end gets a little bit more complicated because this needs a Max Heap now python doesn't give you a Min Heap and a Max Heap they just give you a heap that is a Min Heap by default in order to get a Max Heap you have to basically set your values to their negative which means that the largest value will be the most negative value or the minimum value so let's write some helper functions to okay so to help us with the higher side okay so to help us with the higher side the maximum side I wrote some Max Heap the maximum side I wrote some Max Heap push Max Heap pop and Max Heap Peak push Max Heap pop and Max Heap Peak so these helper functions essentially so these helper functions essentially just convert our items from positive to just convert our items from positive to negative values while they're stored in negative values while they're stored in the Heap and then returns them as the Heap and then returns them as positive values when we pop them out so positive values when we pop them out so now we need to create our Max Heap let's now we need to create our Max Heap let's do that here so in this case we actually need to so that gets our Max Heap initialized so that gets our Max Heap initialized then we'll heapify and I think we'll need to do the same and I think we'll need to do the same thing we did up here with keeping track thing we did up here with keeping track of our Max num I think we'll need to of our Max num I think we'll need to keep track of our Min num so let's do keep track of our Min num so let's do that here okay and now instead of looking at our sorted nums at the largest value we need to get the largest value from our Max on our Max Heap on our Max Heap and just as we did with the minimum and just as we did with the minimum we'll change these guys all right so we'll do a Max heat pop on our Max Heap to get the largest value and then we'll and then we'll check our Min num again and then we'll check our Min num again when we divide this maximum by two we when we divide this maximum by two we could be going below our minimum value could be going below our minimum value so let's just keep track of that minimum so let's just keep track of that minimum value and then instead of having to do the or Max Heap and then in here we need to change these so this is going to be our maximum number now which is just our Max Heap and this will be our minimum value our and this will be our minimum value our minimum okay let's see I did something wrong here oh right the Min Heap needs to be equal to so that was setting it equal to the function which is not what we want we need to actually initialize our midheat and then we heapify it okay I am running low on time so okay that works let's see if we can pass and we pass we don't do very well with our run time here we only beat 41 for runtime and we beat 64 from memory so we pass we don't do great but we pass one thing we can do which I didn't do initially so we have these sorted numbers there could be duplicates in here we don't know so let's remove our duplicates before we start doing all this so one way to remove duplicates is so one way to remove duplicates is creating a set so we create a set that will remove duplicates then we turn that into a list and we sort them so that's going to remove whatever duplicates we have in and I am almost out of time and I am almost out of time see if this gains us anything and we gain a huge increase we beat 100 for runtime and 31 from memory that is fantastic I'm super pleased with that all right that's it for me hope you had fun hope you enjoyed this hope you learned something hope you can try this one on your own this is definitely a tricky problem so check this one out all
2024-03-20 10:58:42
1,675
https://i.ytimg.com/vi/i…axresdefault.jpg
Pomodoro Joe - LeetCode 1675 - hard - (BEATS 100%!)
B8t_npBf1oQ
problem number 43 in this we multiply problem number 43 in this we multiply two strings welcome to the video let us two strings welcome to the video let us begin we are given two non-empty begin we are given two non-empty non-negative strings consisting of non-negative strings consisting of digits only digits only they don't have any leading zeros except they don't have any leading zeros except when the number is itself 0. we have to when the number is itself 0. we have to find the product of the two strings find the product of the two strings without using big integer Library without using big integer Library maximum length of each string is 200. maximum length of each string is 200. the first method is a computer the first method is a computer simulation of elementary math simulation of elementary math we multiply numbers in str1 and str2 to we multiply numbers in str1 and str2 to get a new string get a new string first we check and Edge case first we check and Edge case if either of these strings is 0 the if either of these strings is 0 the result is also zero result is also zero consider the two numbers their consider the two numbers their multiplication is shown here multiplication is shown here for convenience we reverse these things for convenience we reverse these things and call them first and second and call them first and second we Define a list card products we Define a list card products turn button we will append three turn button we will append three products in this list products in this list in a loop we fetch the digits in the in a loop we fetch the digits in the second string and also their indices second string and also their indices at index 0 digit is 7 we will find at index 0 digit is 7 we will find product of 7 with the first string product of 7 with the first string for which we call the function get for which we call the function get product product in the first call of this function index in the first call of this function index is 0 D2 is 7 and the string first is 983 is 0 D2 is 7 and the string first is 983 we Define carry equal to 0 and we Define we Define carry equal to 0 and we Define a list called Product a list called Product as index is 0 no 0 is appended to it as index is 0 no 0 is appended to it in a loop we fetch characters from first in a loop we fetch characters from first one by one and call them D1 in the first one by one and call them D1 in the first iteration D1 is 9. iteration D1 is 9. multiplication of D1 and D2 plus carry multiplication of D1 and D2 plus carry is 63. 6 becomes carry and 3 is appended is 63. 6 becomes carry and 3 is appended to the product to the product in the next iteration D1 is 8 so in the next iteration D1 is 8 so multiplication plus carry is 62. so multiplication plus carry is 62. so carry becomes 6 and 2 is appended to the carry becomes 6 and 2 is appended to the product product in the third iteration D1 is 3 so in the third iteration D1 is 3 so multiplication plus carry is 27. multiplication plus carry is 27. so 2 becomes carry and 7 is appended to so 2 becomes carry and 7 is appended to the product the product when we come out of the loop carry is 2 when we come out of the loop carry is 2 Note Note it will always be a single digit it will always be a single digit if this carry is not 0 we append it to if this carry is not 0 we append it to the product the product finally product is returned to the main finally product is returned to the main function function and is appended to the list products and is appended to the list products in the second iteration of the main in the second iteration of the main function index is 1 so 1 0 is appended function index is 1 so 1 0 is appended to the product at the beginning to the product at the beginning D2 is 6 in this iteration D2 is 6 in this iteration at the end of the get product function 0 at the end of the get product function 0 4 3 3 2 is appended to products and in 4 3 3 2 is appended to products and in the third iteration the third list is the third iteration the third list is appended which has two leading zeros appended which has two leading zeros at this point the loop ends and we have at this point the loop ends and we have computed all the three products now we computed all the three products now we have to add these integer lists to get have to add these integer lists to get the final answer the final answer we call another function named add we call another function named add products which adds all these products products which adds all these products in the list in the list there is always at least one list there is always at least one list present in products we pop out the last present in products we pop out the last list from products and save it as total list from products and save it as total this reduces one entry in products this reduces one entry in products all the remaining lists in products are all the remaining lists in products are processed one by one in a for Loop processed one by one in a for Loop in the first iteration the first list is in the first iteration the first list is called Product called Product next we Define carry with initial value next we Define carry with initial value 0 and an empty list called new Total 0 and an empty list called new Total next we take zip longest of total and next we take zip longest of total and product which also fills zeros to make product which also fills zeros to make them of equal length them of equal length and we start a loop that runs over all and we start a loop that runs over all the digits in them the digits in them we add digits of total product and carry we add digits of total product and carry in the first iteration the sum is three in the first iteration the sum is three so we append 3 to new Total and zero so we append 3 to new Total and zero becomes next carry in the second becomes next carry in the second iteration the sum is 2 iteration the sum is 2 2 is appended to new Total and 0 is the 2 is appended to new Total and 0 is the next carry in the third iteration sum is next carry in the third iteration sum is 16 so 6 is appended to new Total and one 16 so 6 is appended to new Total and one becomes the next carry at the end of the becomes the next carry at the end of the loop we get this loop we get this if carry is not 0 it is appended to new if carry is not 0 it is appended to new Total Total in the last statement of the outer loop in the last statement of the outer loop new Total is saved in total new Total is saved in total in the next iteration of the outer loop in the next iteration of the outer loop process is repeated with next product process is repeated with next product and the new Total is obtained and the new Total is obtained at the end of the outer loop total of at the end of the outer loop total of all the three products is obtained which all the three products is obtained which is returned to the main program is returned to the main program and is saved as result and is saved as result in the end we process the digits in the in the end we process the digits in the reverse order convert the digits to reverse order convert the digits to characters and join them as a single characters and join them as a single string which is returned as the final string which is returned as the final solution solution M digits of first and N digits of second M digits of first and N digits of second are multiplied with each other in time M are multiplied with each other in time M into n then M products of length M plus into n then M products of length M plus n are added to each other so time n are added to each other so time complexity is M into M plus n complexity is M into M plus n reversing of strings at beginning and reversing of strings at beginning and end is of the order of M plus n which is end is of the order of M plus n which is negligible compared to the squared terms negligible compared to the squared terms M products are saved each has length M M products are saved each has length M plus n so space complexity is of the plus n so space complexity is of the order of order of M into M plus n M into M plus n there is a scope for space optimization there is a scope for space optimization in this method without any change in its in this method without any change in its time complexity time complexity so now we will discuss the space so now we will discuss the space optimization of the earlier method optimization of the earlier method instead of saving all the products we instead of saving all the products we can find each product and immediately can find each product and immediately add it to the final result add it to the final result once again we consider the edge case once again we consider the edge case if either of the strings is 0 the result if either of the strings is 0 the result is also zero is also zero consider the same problem consider the same problem once again we ensure that both the once again we ensure that both the numbers are on zero and then reverse numbers are on zero and then reverse them them we now create space for result we know we now create space for result we know that the maximum size of result will be that the maximum size of result will be M plus n so we append six zeros to M plus n so we append six zeros to result result next we iterate next we iterate over the digits in second over the digits in second in the first iteration index is 0 and in the first iteration index is 0 and digit is 7. we use the same function get digit is 7. we use the same function get product to get the product of 7 with 983 product to get the product of 7 with 983 and store the result in the list product and store the result in the list product next we add this product to result next we add this product to result we use the same add strings function we use the same add strings function used previously used previously and the new value of result is obtained and the new value of result is obtained in the second iteration the old value of in the second iteration the old value of product is not needed product is not needed so product of 6 with 983 is stored in so product of 6 with 983 is stored in the same memory area the same memory area note that this product has one leading note that this product has one leading zero zero this product is also added to result and this product is also added to result and the result becomes as shown the result becomes as shown product in the third iteration is 1 into product in the third iteration is 1 into 983 983 with two leading zeros with two leading zeros this product is also saved in the same this product is also saved in the same memory area and added to result memory area and added to result this becomes the final value of result this becomes the final value of result before proceeding further we must remove before proceeding further we must remove any trailing zeros present in the result any trailing zeros present in the result we notice that one extra zero is present we notice that one extra zero is present in the result we pop out that zero in the result we pop out that zero now we join the character form of the now we join the character form of the digits in the Reversed order digits in the Reversed order and get the desired string which is and get the desired string which is returned to the main program returned to the main program the computation is same as before so the computation is same as before so time complexity is unchanged time complexity is unchanged extra memory is used only by product and extra memory is used only by product and result both are of size less than or result both are of size less than or equal to M plus n equal to M plus n same is the size of the output string so same is the size of the output string so space complexity becomes M plus n space complexity becomes M plus n so far we have been finding a product of so far we have been finding a product of all the digits and then adding it to the all the digits and then adding it to the result result with a simple change in logic we can add with a simple change in logic we can add the products of the digits directly into the products of the digits directly into result result once again we ensure that neither of the once again we ensure that neither of the two strings is zero we make room for two strings is zero we make room for result and reverse the strings result and reverse the strings we Define a loop within a loop to get we Define a loop within a loop to get all the pairs of digits in the two all the pairs of digits in the two strings strings next we find the position in result next we find the position in result where the entry is to be updated where the entry is to be updated in the first iteration both the indices in the first iteration both the indices are 0 so position is the beginning of are 0 so position is the beginning of result result old value of the result at pause is the old value of the result at pause is the carry carry 9 into 7 plus 0 is 63. 3 goes to the 9 into 7 plus 0 is 63. 3 goes to the result at pause and 6 is added to result result at pause and 6 is added to result at pause Plus 1. at pause Plus 1. in the next iteration index 1 becomes 1 in the next iteration index 1 becomes 1 while index 2 remains a 0. pause is the while index 2 remains a 0. pause is the sum of the two indices so pause becomes sum of the two indices so pause becomes one one eight into seven plus six is 62. 2 goes eight into seven plus six is 62. 2 goes to cos and 6 is carry that is added at to cos and 6 is carry that is added at plus plus one in the next iteration plus plus one in the next iteration index 1 is 2. index 1 is 2. 7 into 3 plus 6 is 27. 7 into 3 plus 6 is 27. 7 goes to pause and 2 is carry 7 goes to pause and 2 is carry in the second iteration of the outer in the second iteration of the outer loop index 2 is 1 so starting value of loop index 2 is 1 so starting value of pause is 1 and not 0. 9 into 6 plus 2 is pause is 1 and not 0. 9 into 6 plus 2 is 56. 6 goes to pause and 5 as carry is 56. 6 goes to pause and 5 as carry is added to result at pause Plus 1. do not added to result at pause Plus 1. do not worry if an entry after carry is of worry if an entry after carry is of double digits it will be taken care of double digits it will be taken care of in the subsequent iterations now 8 into 6 plus 12 is 60. 0 goes to pause and 6 added to pause Plus 1. in the next iteration value is 26 6 goes to pause and 2 is carry process continues at the end of the two Loops the result next we remove the zero if it is present next we remove the zero if it is present at the end at the end and return the result after joining all and return the result after joining all the digits in the reverse order in the the digits in the reverse order in the form of a string form of a string constant work is done in the double Loop constant work is done in the double Loop so time complexity is the number of so time complexity is the number of pairs of digits that is of the order of pairs of digits that is of the order of M into n M into n there is some saving in space because there is some saving in space because products are not saved separately products are not saved separately however this phase complexity remains however this phase complexity remains same which is the size of the output same which is the size of the output string string I have modified the program further I have modified the program further we only add products in the result in we only add products in the result in the double Loop the double Loop and carry updations are done only once and carry updations are done only once in a single Loop in a single Loop execution time is one third of the execution time is one third of the earlier program but overall time earlier program but overall time complexity remains same complexity remains same as the max length of strings is 200 as the max length of strings is 200 characters there is no risk of overflow characters there is no risk of overflow in the results in the results the sum is much less than 32767 which is the sum is much less than 32767 which is the limit even in two byte integers thanks for watching my videos and supporting my work
2024-03-20 09:24:01
43
https://i.ytimg.com/vi/B…axresdefault.jpg
Multiply Strings | Leetcode #43
uBADVKTpbV8
Hello everyone, Evgeniy Sulima nov is with you and today we are looking at solving the problem today we are looking at solving the problem easily from number 100 cm3, easily from number 100 cm3, according to the conditions of this problem, I was given two according to the conditions of this problem, I was given two binary trees and I must implement a binary trees and I must implement a method that checks method that checks whether these two trees are at peace with themselves or not, whether these two trees are at peace with themselves or not, that is, for example, there are two trees that is, for example, there are two trees 123 123 and I understand that these two detmers 123 123 and I understand that these two detmers would be equal because the structure is would be equal because the structure is the same and correspond and are also the same and correspond and are also equal to each other in the second example I have a equal to each other in the second example I have a discrepancy in the structure, that is, here the discrepancy in the structure, that is, here the left is not equal to 2, the right is driven away and here the left is not equal to 2, the right is driven away and here the mirror left is equal to nope is equal to the right mirror left is equal to nope is equal to the right is equal to 2 therefore is equal to 2 therefore is equal to 2 therefore answer falls in the third, which means that we see that the two trees have the same structure, but the correspondence between the meaning of the raccoons is not observed, that is, here the left one is equal to 2 and here Libya is equal to 1 and vice versa for the right ones, but yes, class class class friends at the entrance I get like a friends at the entrance I get like a router, that is, the top router, that is, the top left and right element here I drink and Beijing is indicated, left and right element here I drink and Beijing is indicated, each not has three fields for itself, this is and each not has three fields for itself, this is and we'll try not love 3 well, troit, that is, a we'll try not love 3 well, troit, that is, a link to the left and to the right element, link to the left and to the right element, then we'll think about it then we'll think about it then we'll think about it problem, then a recursive approach directly suggests itself, that is, I can very easily understand at each iteration for two mods whether day 2 died by itself or not, that is, I say that if at some point you are In this case, I In this case, I In this case, I boldly say that 32 trees are not equal, that boldly say that 32 trees are not equal, that is, I rotate falls further if at is, I rotate falls further if at some point I understand that one is not some point I understand that one is not aravind and the second is not equal, so in this aravind and the second is not equal, so in this case, then I also say that these two case, then I also say that these two trees are not equal to each other, that is trees are not equal to each other, that is trees are not equal to each other, that is is equal to 0 or Q is equal, otherwise in this case I say that two trees with them are unequal ranfors and are equal to 2. In fact, we will be with each other only when I perform the same checks for each floor, that is, for each level for each and I will come to the very end of the end, and I will come to the very end of the end, and I will come to the very end of the end, will I start so that will I start so that the elements become equal to cash, that is, I the elements become equal to cash, that is, I say that and p is equal to and drink is say that and p is equal to and drink is equal to and then in this case I return equal to and then in this case I return the pipes now I want or perform all this logic the pipes now I want or perform all this logic for each pair for each pair I this I this I this write red top is so in two and that is, call the same function for pi lift and you left and you also created the same function for pi right and kai. right everything seems to be correct, that is, we look at the example let's say on successful I come to this floor I ask you both are equal cash don't play no failure to do what one of you is equal to all he says no we're fine we move on between your each other are not equal each other are not equal each other are not equal to each other yes no equal everything is good to each other yes no equal everything is good excellent let's move on we perform this excellent let's move on we perform this operation for each floor, that is, here operation for each floor, that is, here for two twos and for three threes, that for two twos and for three threes, that is, they are equal, so we get pipes for the is, they are equal, so we get pipes for the second example and for the first yes, it’s a pity and second example and for the first yes, it’s a pity and everything is fine, but here everything is fine, but here everything is fine, but here I come and understand that here I have the left one not, I have a two and the right one is on y, that is, this condition is met, I return the phones in this one, my legs are on the second floor, here they work out the conditions translated is not equal to q in let's try build that there build that there build that there are no compilation errors from forum forum we think and everything is fine, that is, it worked now he doesn’t know how and Torina is considered good form in years in algorithmic problems, she is considered good form in commercial work, now it’s not good form what I’ll do the code the code the code is essential, that is, we know that is essential, that is, we know that according to the specification for each we don’t according to the specification for each we don’t need parentheses if we are working with one line, need parentheses if we are working with one line, then here I write about the true turn here I then here I write about the true turn here I return for in a hurry removing the parentheses here I return for in a hurry removing the parentheses here I also remove the parentheses I write aratorna falls also remove the parentheses I write aratorna falls and you can even use these and you can even use these and you can even use these will be fine, and according to the results, I have four more lines of code to publish through, let’s run this solution so that we don’t make mistakes, and after that he tries the solution to combine the I missed it I missed it I missed it here, the compilation was yes, everything was fine, now I click farm to run it through different test cases and the project, everything was fine, we see that the problem was successfully solved quite quickly, that is, the complexity of this solution is that is, we must go through the slim that is, we must go through the slim that is, we must go through the slim case for all memory elements, we case for all memory elements, we select one of them for a new memory, that is, are we select one of them for a new memory, that is, are we working with the same nodes, working with the same nodes, and with this we finish, I say goodbye to and with this we finish, I say goodbye to you until we meet again
2024-03-20 13:54:04
100
https://i.ytimg.com/vi_w…8/sddefault.webp
LeetCode #100 - Same Tree
xLibToO6l_o
Hello hello everybody welcome to my channel it's all the very famous problem tourism it's all the very famous problem tourism delinquent problem number 520 this delinquent problem number 520 this problem given energy of India has written in problem given energy of India has written in basis of two numbers given to specific basis of two numbers given to specific target that they have one solution and you may not use this target that they have one solution and you may not use this element sorry for example element sorry for example 1327 1115 That's Not Every Element So What We 1327 1115 That's Not Every Element So What We Will Do And 09 2014 Festival To Constipation Will Do And 09 2014 Festival To Constipation Simple Solution And Have To 10 And At Mid Simple Solution And Have To 10 And At Mid 200 Cold Increase Targets Nine Show Vijay 200 Cold Increase Targets Nine Show Vijay Simply Root For Children Tools 143 From Simply Root For Children Tools 143 From 202 Number Of Element Sister - Vanshdhar Insisted 202 Number Of Element Sister - Vanshdhar Insisted You For You For You For will check the independent se names of ideal place for a day that is equal to target TV and notice will return i costing repair and will regret for all subscribe to strengthen at the same time complexity of dissolution inside the time Subscribe to Subscribe Subscribe to Subscribe Subscribe to Subscribe button on Thursday button on Thursday 191 Father Optimized This Show As they know about 191 Father Optimized This Show As they know about solution is the time no1 Space to Space Can we do something like solution is the time no1 Space to Space Can we do something like Aadha No time Aadha No time complexity Subscribe We can increase the places to try to complexity Subscribe We can increase the places to try to reduce the time reduce the time complexity subscribe our Channel and 1000 and one to three will feel the values ​​into a trip basically Sotheby's to visit in 100 trip basically Sotheby's to visit in 100 index valve widget index 2nd ed 2nd index valve widget index 2nd ed 2nd T20 - 2 eggs contain acid attacks from witch T20 - 2 eggs contain acid attacks from witch app is not equal to the lava the map That dot net of target - number basically to just e did not inform and they will drop oil member solution time will explain that teaser map and which day is lies with new that teaser map and which day is lies with new house map and evaluation pass for in tie house map and evaluation pass for in tie 2202 Popular Tower Map And Electronic 2202 Popular Tower Map And Electronic Plus simplymarry.com Neither Any Sacrifice Plus simplymarry.com Neither Any Sacrifice Will Use This Is The Temperature Of Side Map Will Use This Is The Temperature Of Side Map Don It Contains Key For Target 900 Fiber The Don It Contains Key For Target 900 Fiber The Bank Will Also Have Checked In Text Bank Will Also Have Checked In Text Mod A Call I Not Equal To Map Dot Net Mod A Call I Not Equal To Map Dot Net Target Target Target swift truth on Vijay Seervi new in top player icon considered map.com a target - Names of I Dhowe literate and Vijay written a b road and problem and ladies sexual more return to compile tower up solution hai Pipad City has compiled and Pipad City has compiled and Pipad City has compiled and submitted that Addison updates what is the time complexity of this is one rupee each year in the sequence of butter give one time complexity maps open to all elements in first time complexity maps open to all elements in first time complexity and complexity of and complexity of dissolution and is open dissolution and is open So Acid * Pass Can We Do It In This Way So Acid * Pass Can We Do It In This Way Can Do Not Wick And Which Aims To Be Written Can Do Not Wick And Which Aims To Be Written Enfield NSS Edison To The Number White 56001 On Enfield NSS Edison To The Number White 56001 On Thursday Share Thank you liked The Thursday Share Thank you liked The Video then subscribe to the Page if you Video then subscribe to the Page if you liked The Video then subscribe liked The Video then subscribe liked The Video then subscribe Channel press Bell Icon to get
2024-03-18 09:38:50
1
https://i.ytimg.com/vi/x…axresdefault.jpg
Two Sum | 2 Sum leetcode | Leetcode 1| Array HashMap | Google Amazon Facebook Microsoft Apple
7rF5IFCT4iI
all right howdy guys this is uh Josh here with another Elite code question so here with another Elite code question so today we're doing leak code uh question today we're doing leak code uh question number 1844 replace all digits with number 1844 replace all digits with characters you are given a zero index characters you are given a zero index string s that has lowercase English string s that has lowercase English letters and it's even indices and digits letters and it's even indices and digits and it's odd indices there's a function and it's odd indices there's a function shift c x where C is a character and X shift c x where C is a character and X is a digit that Returns the X character is a digit that Returns the X character after C for example shift a Char a and after C for example shift a Char a and then into five equals F and then shift then into five equals F and then shift at Char X zero equals X at Char X zero equals X for every odd index I you want to for every odd index I you want to replace the digit s i with shift s i replace the digit s i with shift s i minus 1 and S I return s after replacing minus 1 and S I return s after replacing all digits it is guaranteed that shift s all digits it is guaranteed that shift s i minus 1 and S I will never exceed Z i minus 1 and S I will never exceed Z alright so this one's alright so this one's um this is marked as easy it's pretty um this is marked as easy it's pretty easy one I'm gonna go ahead and fling a easy one I'm gonna go ahead and fling a like on in like that like on in like that um um yeah so here we have the example here so yeah so here we have the example here so this is the character and then this is this is the character and then this is how many characters how many characters um um after the um the first character that we want to give so one character after a is B and then one character after c is should be D and then yeah as you see here e and then f so so yeah so the way I this is this is gonna be my solution it's not like the most uh fastest one but uh this is this helped me learn about um ASCII digits kind of a bit more because whenever I do these liko questions I always see like a I always see people type this they'll do like an equation so like we'll do like resolve plus equals s I and then I'll always see this this like minus Char zero I always wondered like what this Maya 0 represents and so um yeah so today if you in case you're new to leak code or you're curious about like doing this question this is pretty much my answer and this is how I solved it so first let's go ahead and make this variable here or this function the shift function um so we'll do we want to return a char as it says here so we want to have two parameters so we want to have shift and then we ought to have um the first parameter be a Char and then the second would be an integer so we're not going to do anything too crazy here we'll just call it shift and then Char a or I'll do Char C actually on that integer number and then here it's fairly straightforward so in my last video we talked about ASCII characters and the same applies for this question here um we're going to want to know how to convert a a Char variable into a like a integer so so here we go so we'll do just we could just do this C plus number all right so for those of you that didn't see the last video um let me go ahead and write this it's going to be a quick little edit here okay now we're back so I went ahead and um create this variable called ASCII and we're sending it to the representation of a char so on the surface you'd think you know if you're new to programming you'd think oh okay well uh shouldn't it be this I shouldn't our variable be like something like this shouldn't be a Char but actually all characters and programming are actually number representations using the um using ASCII and so what we can even do here we get set Char to 90. which we'll do ASCII to I don't remember exactly what uh result the Springs out but we'll find out in a ASCII to undefined because I added two ASCII to undefined because I added two C's instead of two eyes C's instead of two eyes that's unfortunate that's unfortunate so I guess I'll make this a bit clearer so I guess I'll make this a bit clearer so when we hit run here as you see we so when we hit run here as you see we don't get any errors I should have used don't get any errors I should have used inline that sucks so as you can see here inline that sucks so as you can see here we have 97 and this is the integer so we have 97 and this is the integer so the integer representation of the a Char the integer representation of the a Char or a character is 97 and ASCII or a character is 97 and ASCII and then for the actual character and then for the actual character um the number 90 oops the number 90 um the number 90 oops the number 90 represents the letter Z here let me let represents the letter Z here let me let me all right I made a brief edit here me all right I made a brief edit here just to make it a bit easier to read just to make it a bit easier to read um added the end line here um added the end line here but as you can see here but as you can see here 97 is 97 is the uh ASCII representation of the a the uh ASCII representation of the a character and as you can see here this character and as you can see here this is the Char variable so ASCII 2 90 is is the Char variable so ASCII 2 90 is the representation of the letter z the representation of the letter z so with this knowledge what we can do so with this knowledge what we can do is we can make this function here is we can make this function here whereas Char where it turns a Char and whereas Char where it turns a Char and then we just simply add the character then we just simply add the character plus the number plus the number um so this number here is going to be um so this number here is going to be pretty much the equivalent of right here pretty much the equivalent of right here s dot i s dot i and this should be the placement of the and this should be the placement of the string which is here string which is here and yeah so and yeah so let's go ahead and we went to our main let's go ahead and we went to our main function here we'll do string result function here we'll do string result equals equals we'll just make it blank for now we'll just make it blank for now just initialize it blank just initialize it blank um um so since so since we have to go through a list of we have to go through a list of characters we want to whenever you have characters we want to whenever you have to go through something always keep in to go through something always keep in mind like okay we have to do either a mind like okay we have to do either a for Loop or for each Loop for us it's for Loop or for each Loop for us it's better to do a for Loop here because it better to do a for Loop here because it pretty much tells us here that we're pretty much tells us here that we're going to want to use the going to want to use the wherever we're at in the loop we want we wherever we're at in the loop we want we want to keep track of wherever we're at want to keep track of wherever we're at in the loop and it's easier to do that in the loop and it's easier to do that with a for Loop instead of like a for with a for Loop instead of like a for each Loop each Loop um so let's do um so let's do we're not going to do anything too crazy we're not going to do anything too crazy here so I is less than S size here so I is less than S size and then I plus plus and then I plus plus all right so now what we want to do is all right so now what we want to do is we want to make an integer we're going we want to make an integer we're going to do number and we're going to set this to do number and we're going to set this to to s i s i minus zero minus zero so you're probably wondering like okay so you're probably wondering like okay well why are we doing this why are we well why are we doing this why are we subtracting minus by zero so the reason subtracting minus by zero so the reason why we're doing this is because why we're doing this is because remember this as key equivalent that we remember this as key equivalent that we have so what's happening is have so what's happening is when this function gets called it's when this function gets called it's going to take the character and it's going to take the character and it's going to take the ASCII equivalent of going to take the ASCII equivalent of that character that character the number and it's going to add this the number and it's going to add this number to it so number to it so the reason why we we're going to the reason why we we're going to subtract 0 subtract 0 we're actually subtracting the character we're actually subtracting the character representation the ASCII representation representation the ASCII representation of zero this is pretty much a quick way of zero this is pretty much a quick way to convert a chart to convert a chart data type into an integer data type so data type into an integer data type so now what we do is we just do an if now what we do is we just do an if statement here so if statement here so if uh s dot i uh s dot i oops we'll do s i modulus oops we'll do s i modulus so the modulus operator pretty much the so the modulus operator pretty much the remainder the remainder the remainder of remainder the remainder the remainder of whatever this is if it's as long as it's whatever this is if it's as long as it's not zero not zero or if it's not zero but what we want to or if it's not zero but what we want to do is we want to do is we want to have result plus equals um shift and then I want to do our I minus one and then the number all right and then we want to else and then for the else statement let's do plus c we just go ahead and add whatever's in the string or just add it to our result variable to our result variable and then from there on we do is just and then from there on we do is just return our result return our result so to recap and we went ahead and made a so to recap and we went ahead and made a new function called shift new function called shift uh pretty much copying the parameters uh pretty much copying the parameters required required um on this sentence here um on this sentence here so we have one character and then we so we have one character and then we pretty much what we're doing is we're pretty much what we're doing is we're adding the ASCII representation of these adding the ASCII representation of these together together and so and so um um and so what this will do is this will and so what this will do is this will give us the give us the alphabetical number or alphabetical alphabetical number or alphabetical representation and the Char format representation and the Char format so so so then we made that and then we went so then we made that and then we went ahead and you know placed our create a ahead and you know placed our create a variable and memory so we can store our variable and memory so we can store our result result create a for each Loop since we have to create a for each Loop since we have to iterate through all the characters iterate through all the characters and the string and so the reason why we and the string and so the reason why we put this here so we have s i minus Char put this here so we have s i minus Char zero we do this because this is actually zero we do this because this is actually a Char representation of an ASCII uh a Char representation of an ASCII uh number number so so whatever character this is the s i is whatever character this is the s i is so let's say a we're going to subtract so let's say a we're going to subtract uh Char Zero from it to get the uh uh Char Zero from it to get the uh integer representation of integer representation of this number so this number so then what we do is we do run our if then what we do is we do run our if statement so if I modulus 2 statement so if I modulus 2 does not equal zero does not equal zero so this pretty much checks if the I is so this pretty much checks if the I is even or odd so if it's even this is even or odd so if it's even this is going to return zero but if it's odd going to return zero but if it's odd it's going to return it's going to return um um it's going to turn a number that's it's going to turn a number that's greater than zero or greater than zero or anything other than zero and so once it anything other than zero and so once it does that then we know that it's an odd does that then we know that it's an odd number and then we go ahead and we run number and then we go ahead and we run our function here our function here our shift function that we made and then our shift function that we made and then anything else it just gets returned as anything else it just gets returned as um the string the string that's already present so like for example a so a sense a is in the zeroth position it'll this will probably return zero and so we just do the else and then we'll just do um it'll just return the a character so if we run this we get accepted and yeah and then that should be all she wrote yep so yeah hopefully guys you found that helpful yeah it's definitely not the uh it's not the cleanest of solutions but this is what I came up with uh the oh the time complexity for this should be o of n because we're iterating through all of the pretty much iterating through every single um character in the string function and so the bigger that the string parameter that gets fed into it the more time it's going to take so it's going to be o of n so yeah hopefully you guys enjoy it and hopefully you found it
2024-03-25 10:20:42
1,844
https://i.ytimg.com/vi/7…axresdefault.jpg
Leetcode #1844 Replace All Digits with Characters | C++ Solution Explained
w8FF2fTmolI
Hello friends uh very happy New Year so in this video we will solve lead code in this video we will solve lead code daily challenge problem one that is the daily challenge problem one that is the first day of January and the problem first day of January and the problem named is word pattern so we are given a named is word pattern so we are given a pattern and a string s and we need to pattern and a string s and we need to find if string as follows the same find if string as follows the same pattern so here follows means a full pattern so here follows means a full match and there is a bijection between a match and there is a bijection between a letter and pattern and known empty word letter and pattern and known empty word in s okay so let me take the first in s okay so let me take the first example example the first example is a b b a and my word the first example is a b b a and my word is dog cat cat dog okay dog is dog cat cat dog okay dog cat cat and dog right so this is my cat cat and dog right so this is my string and this is my pattern right so I string and this is my pattern right so I just need to check if my string follows just need to check if my string follows the pattern and pattern follows the the pattern and pattern follows the string means I mean that there is a string means I mean that there is a bijection between both of them so what bijection between both of them so what do you mean by bijection so here do you mean by bijection so here initially the first position is a and initially the first position is a and the last position is a so in this the last position is a so in this pattern or in my word the same thing pattern or in my word the same thing should be there so dog and dog are should be there so dog and dog are already present similarly B and B so already present similarly B and B so here should it should be the same word here should it should be the same word means it it is not required that it means it it is not required that it should be the cat only it can be should be the cat only it can be anything it can be ABC ABC so that this anything it can be ABC ABC so that this is also a correct solution so this is is also a correct solution so this is called bijection and similarly if I called bijection and similarly if I check if I first start checking from check if I first start checking from here then dog here then dog there are two dogs I mean first and the there are two dogs I mean first and the fourth position there is a dog so in the fourth position there is a dog so in the similar similar fashion in my pattern also the first and fashion in my pattern also the first and the last position uh letters should be the last position uh letters should be the same the same so here it is letters here we have so here it is letters here we have letters and we here we have words okay letters and we here we have words okay so yeah it if the problem looks simple so yeah it if the problem looks simple yeah it is a good I would say yeah it is a good I would say combination of I would say hash map and combination of I would say hash map and uh uh One More Concept so yeah it is a good One More Concept so yeah it is a good combination of that you you could think combination of that you you could think directly of solving it using an hash map directly of solving it using an hash map but uh yeah you would get stuck when you but uh yeah you would get stuck when you have to check by both ways right see if have to check by both ways right see if you had to check only if the string you had to check only if the string follows the pattern then you could have follows the pattern then you could have done in using simple way and yeah that done in using simple way and yeah that is we all know right but now how would is we all know right but now how would you solve this problem okay there would you solve this problem okay there would be a possibility so yeah we would use a be a possibility so yeah we would use a combination of hazmap and set okay yeah combination of hazmap and set okay yeah you could think of a much more different you could think of a much more different ways brute force and all that but this ways brute force and all that but this is not uh I would say this is problem is is not uh I would say this is problem is stacked as an easy category problem so stacked as an easy category problem so we can I'm directly telling you the we can I'm directly telling you the solution so solution so uh initially I would first of all see uh initially I would first of all see this this is this is given as a string this this is this is given as a string okay this this entire what is given as a okay this this entire what is given as a string separated with a space okay so we string separated with a space okay so we just need to convert this string to just need to convert this string to Vector of string y because we need to uh Vector of string y because we need to uh maintain the indexes right so we need to maintain the indexes right so we need to maintain the index of this I need to maintain the index of this I need to change to Vector of string so for that I change to Vector of string so for that I will use C plus plus STL Library will use C plus plus STL Library function I stream function I stream which will convert this space separated which will convert this space separated string to Vector of string okay so that string to Vector of string okay so that is uh this is so this is a zero Index is uh this is so this is a zero Index this is first second and third correct this is first second and third correct and similarly for the pattern this is and similarly for the pattern this is our these all are letters so we need we our these all are letters so we need we will require a map right would we will require a map right would we require a map to see that c require a map to see that c first of all I would start iterating now first of all I would start iterating now I would start iterating from my pattern I would start iterating from my pattern okay I would start iterating from my okay I would start iterating from my pattern so initially I am at a right I pattern so initially I am at a right I would check if my a exists in my map or would check if my a exists in my map or not means either a is mapped to any of not means either a is mapped to any of the words or not so initially a is not the words or not so initially a is not mapped to any of the words so I would mapped to any of the words so I would map it to dog okay and similarly at the map it to dog okay and similarly at the same time I would in insert the word in same time I would in insert the word in my set so in my set I have a till now my set so in my set I have a till now okay now why I am doing this it is a okay now why I am doing this it is a very important thing to notice right so very important thing to notice right so if before inserting into my map I would if before inserting into my map I would check if my set has already that one check if my set has already that one present or not I would say that letter present or not I would say that letter present or not and if that letter is present or not and if that letter is already present that means that there already present that means that there exists already a mapping means a was exists already a mapping means a was previously mapped to some other previously mapped to some other character right but now it is mapping to character right but now it is mapping to some other character so I would directly some other character so I would directly return a false from there so if my if my return a false from there so if my if my current character is present in my set current character is present in my set okay then I would find file see first okay then I would find file see first thing to find out is that if it is thing to find out is that if it is present in map if it is not present in present in map if it is not present in map then it should not have been present map then it should not have been present in set also right but if if we find out in set also right but if if we find out that if it is present in set that means that if it is present in set that means that it was mapped to an uh some another that it was mapped to an uh some another character previously so a would have map character previously so a would have map a would have been mapped to some let's a would have been mapped to some let's say cat okay now it is inside okay and say cat okay now it is inside okay and it is in map also right but it I mean it is in map also right but it I mean what in map in my map I would need to what in map in my map I would need to check if a is mapping to dock right check if a is mapping to dock right because current mapping is a and Dot because current mapping is a and Dot correct so uh both we would run a loop correct so uh both we would run a loop from equal to 0 to equal to n right so I from equal to 0 to equal to n right so I would map from s of I which is my string would map from s of I which is my string and my pattern of I or pattern or and my pattern of I or pattern or whatever you need to check okay so I whatever you need to check okay so I would check for both of this right so I would check for both of this right so I would have to check for mapping a is to would have to check for mapping a is to do so if my a instead of mapping is not do so if my a instead of mapping is not present in my map and if I found that it present in my map and if I found that it is present in set a is present in set is present in set a is present in set then that that means that in my map it then that that means that in my map it there exists a mapping where a is not there exists a mapping where a is not mapped to dock but a is mapped to cat mapped to dock but a is mapped to cat and finally here I would directly return and finally here I would directly return false okay and if none of the cases is false okay and if none of the cases is this then I would insert in my map and this then I would insert in my map and insert it myself so let me explain it to insert it myself so let me explain it to again in a simple simple words again in a simple simple words see initially see initially this is my dog this is my dog cat cat let's say base map to dog game and uh let's say base map to dog game and uh yeah again it is also mapped to dog okay yeah again it is also mapped to dog okay so this is the case okay so now a I so this is the case okay so now a I would find search for Aries to Doc would find search for Aries to Doc mapping in my map mapping in my map would be of character would be of character and string correct and string correct whatever you you can name it as it is so whatever you you can name it as it is so I would search for Ace to dog mapping it I would search for Ace to dog mapping it does not exist so in my set does not exist so in my set I would check my account if my if a I would check my account if my if a exists or not so it does not exist so I exists or not so it does not exist so I will insert it and in my map also is to will insert it and in my map also is to Doc mapping is now inserted correct now Doc mapping is now inserted correct now B is to cat mapping similar is the case B is to cat mapping similar is the case b is to get mapping does not exist in my b is to get mapping does not exist in my map and does not exist in B does not map and does not exist in B does not exist in my set I would insert it and B exist in my set I would insert it and B is to get mapping I would paste in my is to get mapping I would paste in my map now I have B is to dog mapping map now I have B is to dog mapping correct base to dog mapping is there now correct base to dog mapping is there now I am searching my map map I am searching I am searching my map map I am searching if my ma of b m a of B is equal equal to if my ma of b m a of B is equal equal to V of oh yeah this is that name this V of oh yeah this is that name this Vector as V okay V of I means current Vector as V okay V of I means current index is 2 so 0 1 and 2 and 3. so what index is 2 so 0 1 and 2 and 3. so what my Mi of B would give m a of B in my map my Mi of B would give m a of B in my map already the value stored is cat already the value stored is cat value stored is cat and what is V of I value stored is cat and what is V of I it is dog it is dog so is this equal no it is not equal that so is this equal no it is not equal that means that means in my set B would the B means that means in my set B would the B B has different mapping right that B has different mapping right that already exists in my map so here I would already exists in my map so here I would return false because this is mapping return false because this is mapping this is not a bijection right initially this is not a bijection right initially B is mapping to get now B saying that I B is mapping to get now B saying that I want to map to dog so this is the case I want to map to dog so this is the case I was explaining to you so that is the was explaining to you so that is the reason we require set and finally I reason we require set and finally I would return a false from here correct would return a false from here correct so we would break out from the loop else so we would break out from the loop else finally go to tone true I would show you finally go to tone true I would show you the code now the code now yeah so I take I took one vector B and yeah so I take I took one vector B and yeah as I told you this is a C plus plus yeah as I told you this is a C plus plus St Library function string stream ISS St Library function string stream ISS and then what I am what I am doing I am and then what I am what I am doing I am pushing each of the words in my space pushing each of the words in my space separate words in my Vector I am taking separate words in my Vector I am taking one set initially I am pretty sure that one set initially I am pretty sure that the number of correct letters in my the number of correct letters in my string pattern and the number of words string pattern and the number of words in my string should map and if if it is in my string should map and if if it is not the case I would finally here not the case I would finally here directly return a false then I told you directly return a false then I told you I am taking a map okay I am searching I am taking a map okay I am searching for my map if if the character is for my map if if the character is present in my map and then I am checking present in my map and then I am checking if the mapping is correct if it is not if the mapping is correct if it is not current then finally I will return a current then finally I will return a false over here and if a character is false over here and if a character is not present that means I am checking if not present that means I am checking if my if it is present in my set so if it my if it is present in my set so if it is present in my set and map does not is present in my set and map does not give the correct mapping then then that give the correct mapping then then that means that the previously it was matched means that the previously it was matched to some another character right so I to some another character right so I would return a false and if it is not would return a false and if it is not the case I would insert in my map and in the case I would insert in my map and in my set my set finally you would return a true correct finally you would return a true correct so the time complexity would be bigger so the time complexity would be bigger off and only yeah and in case if you off and only yeah and in case if you have any doubts comment it down I would have any doubts comment it down I would try to explain it to you again and thank try to explain it to you again and thank you for watching do not forget to like you for watching do not forget to like And subscribe to the channel for such And subscribe to the channel for such content yeah thank you
2024-03-22 14:24:00
290
https://i.ytimg.com/vi_w…xresdefault.webp
290. Word Pattern | | Leetcode Problem | | Explained | | Coding With Jenish
d8CtqW1rXAs
hello friends welcome to coding interviews channel hope you are doing interviews channel hope you are doing great great if you haven't subscribed to my channel if you haven't subscribed to my channel yet please go ahead and subscribe yet please go ahead and subscribe i have created bunch of playlists to i have created bunch of playlists to cover various categories of problems cover various categories of problems such as bfs dfs dynamic programming and such as bfs dfs dynamic programming and so on so on please check them out i have uploaded please check them out i have uploaded the code for this problem the code for this problem to the github repository you can get the to the github repository you can get the link from description link from description below this video let's jump into today's below this video let's jump into today's problem problem swapping notes in a linked list you are swapping notes in a linked list you are given the head of the link list given the head of the link list and an integer k written the head of the and an integer k written the head of the linked list after swapping the values of linked list after swapping the values of the kth node the kth node from the beginning and kth node from the from the beginning and kth node from the end the list is one index so basically end the list is one index so basically the problem statement is we are given the problem statement is we are given with a linked list and with a linked list and a value k okay and the linked list we a value k okay and the linked list we are are given with the first node basically the given with the first node basically the head node of the linked list head node of the linked list and k is denoted as basically the one and k is denoted as basically the one case starts with case starts with one index right that's what it said one index right that's what it said so essentially what we say is just like so essentially what we say is just like how you count how you count from one so one two three four from one so one two three four five right so that means this one is the five right so that means this one is the first first element in the linked list two is the element in the linked list two is the second element in the linked list second element in the linked list three the third and the element in three the third and the element in linked list and so on linked list and so on and we are given with the k value right and we are given with the k value right so we are supposed to swap the k from so we are supposed to swap the k from the the starting and kth node from the ending starting and kth node from the ending those values and then written the those values and then written the linked list right the head of the linked linked list right the head of the linked list basically right so if you look at list basically right so if you look at the example one the example one right so the head is basically one two right so the head is basically one two three four five three four five that is the order head is pointing to that is the order head is pointing to the linked list ah node with value one the linked list ah node with value one right and k is given as two so now right and k is given as two so now we have to swap the values in the we have to swap the values in the second node from the beginning and second node from the beginning and second node from the end right so what second node from the end right so what is the second node from the beginning in is the second node from the beginning in the example the example example one obviously the node two and example one obviously the node two and what is the second node what is the second node from the end of the linked list it is from the end of the linked list it is four so now we have to swap those values four so now we have to swap those values two two and four that is how and four that is how the second picture basically the second the second picture basically the second one after swapping it looks like this one after swapping it looks like this so four is going to come into the so four is going to come into the second place and two is going to go to second place and two is going to go to the fourth place so this is the linked the fourth place so this is the linked list that we are list that we are going to return so that is the reason going to return so that is the reason why output is one four two why output is one four two sorry one four three two five right so sorry one four three two five right so that's how it is going to work that's how it is going to work simply so let's simply so let's look at and try to understand more into look at and try to understand more into this problem right so now this problem right so now let's say we have n nodes in a let's say we have n nodes in a linked list but we are given the access linked list but we are given the access to to only the head node right if we want to only the head node right if we want to determine determine what is the kth node from the start and what is the kth node from the start and what is the k-th node from what is the k-th node from end there are multiple ways doing it end there are multiple ways doing it right right so for example let's go do it ah in the so for example let's go do it ah in the first way right first way right so the first way is about ok count so the first way is about ok count the nodes in linked list right so that's the nodes in linked list right so that's that's the one right so first one we can that's the one right so first one we can do count node in the do count node in the linked list right linked list right so once we do that right basically so once we do that right basically what we can essentially do is subtract k from that right subtract k from that simply right so let us call this as n nodes right and to get kth node basically from the beginning k from beginning this we can get it simply while we are counting the nodes right so that is another optimization we can do it but assume that we have n nodes that is the first pass so let us say this is pass one ah and get the kth from the beginning it is pass two right and the third step is about kth from end so what is the kth from end will become basically you need to count the k from android in this particular case there are 5 nodes right so 5 nodes and second k is equal to 2 right second from the end would be what so 5 minus 2 plus 1 right so that would give you the kth node from end right so what is 5 minus 2 plus 1 it's 4 so that's the node that we so in this particular example right the num node number and node position are matching it so happened that but yeah so we are looking at the position the position is fourth right right so this is one way right so that means we have done in three passes so basically we in the past one we were able to get the nodes count and the second pass we got the kth from beginning and third pass we got the key from end and after that we just do as the fourth step swap right so this is what we need to do right but can we do any optimization here yes definitely we can do optimization right and let's look into the approach 2 and let's look into the approach 2 right so let me take this and see right so let me take this and see if we are able to improve let me copy if we are able to improve let me copy this all right this all right and paste it and call this as approach and paste it and call this as approach 2. 2. what can we do so in the past 1 what can we do so in the past 1 we are able to do the n right so can we we are able to do the n right so can we combine pass 1 and pass 2 combine pass 1 and pass 2 so all it takes is while you are so all it takes is while you are trying to count the n right you can just trying to count the n right you can just get the kth from beginning and get the kth from beginning and in that pass one itself right so in that pass one itself right so essentially what we are saying is essentially what we are saying is we get the count of the node and we get the count of the node and what we are going to do is get this what we are going to do is get this and kth from the beginning this is all and kth from the beginning this is all we can do it in we can do it in one pass right and then we have to do one pass right and then we have to do the pass two the pass two from the kth from the end right so this from the kth from the end right so this will be our second step will be our second step right and the third step right and the third step would be basically swap so in this would be basically swap so in this particular case also since we know particular case also since we know n in this particular case n is equal to n in this particular case n is equal to five five minus two plus one so this five five minus two plus one so this will will still hold good right in order to still hold good right in order to calculate the kth from end calculate the kth from end so in this particular case what we so in this particular case what we essentially did is essentially did is we combined the step one and step two we combined the step one and step two into into one single uh pass that way one single uh pass that way we are down to two pass now we are down to two pass now can we do even better like not even can we do even better like not even going to do the second pass going to do the second pass can we do the single pass can we do the single pass and get away with the right answer and get away with the right answer yes so approach 3 right so yes so approach 3 right so in this particular case what we are in this particular case what we are going to do is going to do is we are going to count we are going to count basically the first pass will remain basically the first pass will remain same same right but we are going to add right but we are going to add addition additional logic to the first addition additional logic to the first pass itself pass itself so now count the notes so now count the notes in l linked list as n right n is where in l linked list as n right n is where we're we're counting so while we count we can do the counting so while we count we can do the kth from the beginning also right kth kth from the beginning also right kth from the beginning also from the beginning also good so now we are going to good so now we are going to store this kate from the beginning in store this kate from the beginning in some pointer some pointer let's say keith begin let's say keith begin is equal to kth from beginning right is equal to kth from beginning right k from beginning right k from beginning right let's call that and now we need to know what is kth from end right so what we are going to do is since we recorded the kth from beginning in begin that is a temporary variable now we are going to use this kth from beginning also getting updated to advance the pointer so that we will keep the kth from end right kth from end in that itself right so while we count n nodes we will keep the kth from beginning keep updating so that at the end of the linked list right at the end of the linked list kth from beginning will have keith from kate from beginning will point to keth from end like that so that is way keth from end like that so that is way and then obviously at the end we will and then obviously at the end we will have only two steps here have only two steps here swap right that's the swap right that's the third approach we can say so we started third approach we can say so we started with with three pass and then split down to two three pass and then split down to two pass and we are down to pass and we are down to one pass so now for the one pass so now for the code wise i am going to show the code code wise i am going to show the code for for approaches 2 and 3 because approach 1 is approaches 2 and 3 because approach 1 is trivial i i would say because we have to trivial i i would say because we have to do the three times passing right do the three times passing right so let's go look at the approach two and so let's go look at the approach two and approach three the code four right so approach three the code four right so let's see let's see so let's go to the two pass first so let's go to the two pass first and then we'll come down to the one pass and then we'll come down to the one pass right so we store right so we store the k ah in temporary temp value the k ah in temporary temp value value and the head will be stored in value and the head will be stored in temp head temp head and i have a previous pointer that is and i have a previous pointer that is also also pointing to the template right so while pointing to the template right so while temp is greater than zero basically temp is greater than zero basically we are looking to go past the we are looking to go past the k values right so that that is where we k values right so that that is where we have have the begin pointing to the right so pre the begin pointing to the right so pre whatever we have whatever we have collected that we are going to call it collected that we are going to call it as begin as begin right so that means what so we have right so that means what so we have passed passed through k value i mean k nodes right through k value i mean k nodes right we have passed through k nodes and we have passed through k nodes and in this particular point the count is in this particular point the count is getting initialized to k getting initialized to k because we have passed through k values because we have passed through k values or k nodes already or k nodes already and then reassign the previous pointer and then reassign the previous pointer to head to head we don't use previous pointer here we don't use previous pointer here itself in this next itself in this next next value what we will be doing next so next value what we will be doing next so now now our temp head is pointing to the kth our temp head is pointing to the kth node right so k nodes we have passed so k k plus one i would say k plus one throughout we have passed and now while temp head is still not null we are going to move further so why are we doing this so basically in the second parcel two pass algorithm right while we calculate the kth from the beginning we are also trying to calculate the n so in this case i am calling this n as count here that's it so count is initialized to k because we have passed through k values and then we are going through the end of the linked list to find out what is the real number of nodes in that particular linked list so once we get through that right so we are reassigning the temp head to the head and as remember the count how many nodes we need to essentially pass so if you go back and understand right this is the number of nodes minus k plus 1. so that many number of nodes we need to pass through to get the kth from end right so that is what we are doing essentially count minus k plus 1 right so while count is greater than 0 we are going through that many nodes from the starting so that we can get the kth node from the end so once we have the kth node from end we are going to put that in the end right so begin is begin is having the kth node from the start and end will have the kth node from the end after that all you have to do is just swap so once you swap right on the head that's it so essentially these two while loops are going through them going through the linked list as once if you closely observe right because we are going through the through k nodes here and count minus k nodes here so that means these two while loops combinedly going one pass the first pass and this one is second pass that's it so this is a two pass algorithm so the complexity the time complexity would be order of n still so the first time it will be order of n plus second time is also order of n in the worst case right so the total complexity will be order of two n but since constants will be ignored in the bigger notation it will be order of 2n so now let's go back and understand a okay so it will be very very similar okay so it will be very very similar right so in this particular case again right so in this particular case again temp is uh case uh ascendant to temp and temp is uh case uh ascendant to temp and head is assigned to temp head head is assigned to temp head previous is also tempered while temp is previous is also tempered while temp is greater than zero greater than zero we are going to go through the k notes we are going to go through the k notes first first in this particular while we are going to in this particular while we are going to go through the k notes go through the k notes so after going through the k notes k so after going through the k notes k notes right so we have notes right so we have the kth note from the beginning so that the kth note from the beginning so that we are putting into we are putting into begin right good so begin right good so kth node from the back right that we are kth node from the back right that we are assigning it to the assigning it to the whatever the pre value we have just whatever the pre value we have just call we are calling it as kth node from call we are calling it as kth node from the back what we said the back what we said we are going to advance k note from the we are going to advance k note from the back so that back so that when the we have exhausted the linked when the we have exhausted the linked list right list right the kth node from the back will have the the kth node from the back will have the kth node from the back kth node from the back in reality right so we will be advancing in reality right so we will be advancing the k-th note on the back the k-th note on the back and we will be advancing the temp head and we will be advancing the temp head also so here also so here we went through the k right k notes we went through the k right k notes and in this particular way while loop we and in this particular way while loop we are going through n minus k n are going through n minus k n so entirely if you combine them right so entirely if you combine them right two while loops two while loops k notes plus n minus k nodes totally we k notes plus n minus k nodes totally we are going through are going through n nodes that two while loops combiningly n nodes that two while loops combiningly we are going through the entire linked we are going through the entire linked list only once list only once and this is just a swapping code right i and this is just a swapping code right i i made it i made it like little little bit verbose so that like little little bit verbose so that you can understand and then finally you can understand and then finally you can written the head of the linked you can written the head of the linked list so list so the time complexity will still remain the time complexity will still remain same right in here same right in here so order of n so in the previous case is so order of n so in the previous case is also order of n also order of n and the current case also is order of and the current case also is order of one so in fact one so in fact in all three approaches approaches one in all three approaches approaches one two and three two and three the time complexity the big goal the time complexity the big goal notation time complexity will be notation time complexity will be order of n still the only difference is order of n still the only difference is this is this is a process the one pass approach two is a process the one pass approach two is two pass approach one is three pass two pass approach one is three pass that is the only difference altogether that is the only difference altogether right so that's how we are able to solve right so that's how we are able to solve this problem with order of n time this problem with order of n time complexity complexity overall so if you have any further overall so if you have any further questions please post them in the questions please post them in the comment section below this video comment section below this video and also i have posted the code to the and also i have posted the code to the github repository github repository you can find the link in the description you can find the link in the description below this video below this video if you haven't subscribed to my channel if you haven't subscribed to my channel please go ahead and subscribe please go ahead and subscribe and share among your friends please and share among your friends please click on the bell icon so that you will click on the bell icon so that you will be notified about be notified about my future videos thank you for watching my future videos thank you for watching i will be back with another problem soon i will be back with another problem soon till then stay safe and goodbye till then stay safe and goodbye thank you
2024-03-20 17:21:49
1,721
https://i.ytimg.com/vi/d…axresdefault.jpg
Swapping Nodes in a Linked List (Leetcode 1721)
FcadUHcFseA
Hello everyone so today we will be discussing question number question number 15908 code which is make sum divisible by p 15908 code which is make sum divisible by p so in this question what is told to us so in this question what is told to us that c have you remove sach date d sum of remaining element is divisible by p means we have to make a Hey, if we have to remove as little as is possible Hey, if we have to remove as little as is possible Hey, if we have to remove as little as is possible from this ray, from this ray, then we will get the remaining ray from it, all its then we will get the remaining ray from it, all its elements, all the child elements, all the child elements, we are drinking at this elements, we are drinking at this time [music] Do you understand And And what can happen if there are all the what can happen if there are all the elements of the whole, which is the time of all this [Music] question is then all the concepts will be clear to you and I thing, because thing, because thing, because I have discussed everything about this playlist in the previous questions, so I will do it a little quickly I will do it a little quickly because if you have seen the previous questions of because if you have seen the previous questions of this playlist, then you this playlist, then you will understand it very easily, very easily and will understand it very easily, very easily and its prefix its prefix its prefix very easy to understand. Okay, so let's discuss its approach. Okay, so what we did is we are discussing in the questions like in the previous one, we are taking one hey and one prefix sub my. Hey our n1n2n3n4 is just we have zero before n1 n1 + N2 n1 + N2 + n3 doing it like this this is our pi and i is for element and this is our pk okay back till here time As I have discussed below, there is an equation in Minus Pi, the whole is playing with this, we will give us a continuous, it is fine like every time made the deduction. made the deduction. What is asked in this question, what is asked in this question will What is asked in this question, what is asked in this question will come out from this equation, your question will be solved, come out from this equation, your question will be solved, here that thing is very simple, here that thing is very simple, here what has been told to us that what is left is here what has been told to us that what is left is this is the total time, this is the total time, what I want is the what I want is the total number of I have found I have found zero, I have found the zero, I have found the equation, you have to see the thing which can cause you further problems, see the thing which can cause you further problems, I will also discuss it, but your I will also discuss it, but your core question is not your concept core question is not your concept right here. right here. right here. P, meaning its mode should be zero. P, meaning its mode should be zero. Okay, Okay, whatever I said, let's discuss what we have to pay attention to. whatever I said, let's discuss what we have to pay attention to. What is that? I have What is that? I have written down the question in advance, I will be total sums written down the question in advance, I will be total sums mines [ Sangeet] If I open the Plus Minus bracket, then it will be the mode of Total Sam, open the Plus Minus bracket, then it will be the mode of Total Sam, so what is the important point that I should very big you, I will come out of Total Sam only then keep it on mode. you, I will come out of Total Sam only then keep it on mode. you, I will come out of Total Sam only then keep it on mode. I take it then whatever my final total will be, it will be the total. Understand that when I look for and then a small number will come in every loop, I will keep doing every mode, I will keep doing mods. mods. Okay, so this is an important point. Okay, so this is an important point. Okay, so this is an important point. will do the same with J. I am not even talking about P in J. I never play with P backwards. As I have discussed in the previous question, when I move J forward, when I move forward with us, this is what I move forward with us, this is what I move forward with us, this is what I do, I move ahead with you only by taking the mode, I do, I move ahead with you only by taking the mode, as you must have seen, I have as you must have seen, I have completely understood now, now let's open this equation, let's open this equation. Okay, so we this equation. Okay, so we open this equation. open this equation. open this equation. director, so I have two things, now I will take these two things completely to the right side and both of them will be stored in the map right in my map and I will I will take it and find it in the map. I will take it and find it in the map. I will take it and find it in the map. I have I have discussed it in the previous question, so what do I do? I have discussed it in the previous question, so what do I do? I have taken it Music] Music] [ Open Open, everything is fine, now this thing Open Open, everything is fine, now this thing Open Open, everything is fine, now this thing and this is the number, I will modify it by P, and this is the number, I will modify it by P, I will get a number N, is it I will get a number N, is it from both, I have to check in the map, it is from both, I have to check in the map, it is total, there is total, there is just a small problem there, which was the previous question which I asked Question has been raised, there Question has been raised, there Question has been raised, there you know that behind this lace, it is moving forward, which is moving forward like this, always when you are in any element. always when you are in any element. Will you stay, Will you stay, this thing which is behind is becoming a mode behind, isn't the this thing which is behind is becoming a mode behind, isn't the thing which I had discussed important thing which I had discussed important here ok How will be the resulting number, this thing which I had discussed here, is n't it, we are in every loop in the early stage. In every hydration in the loop, we will keep doing grind mode, we will keep doing mode, we will keep doing mode, then the total which we will be resulting in, will also be given PC lace, okay okay [music] here is five, okay now I am here Total So the difference between these two which is negative, the less than P. This is it, I told you that it has become negative here, so what if it is negative, then it will also be less than P. do is J mines total [music] it will always be positive, whatever this it will always be positive, whatever this you period in it, so it will you period in it, so it will become a positive anti, become a positive anti, okay, that's why I did period. Now let's find the okay, that's why I did period. Now let's find the solution for this. Why do we in the for loop? Now let's see its solution. People have not explained this. You will have to understand it yourself but here I have explained to you why this is happening. Why am I doing this? I am doing just this Don't have to do it now, let's Don't have to do it now, let's Don't have to do it now, let's do it directly, do it directly, okay, then let's start, I am not explaining the complete example in this, now you can do it yourself by taking the example, if now you can do it yourself by taking the example, if you do not understand then let me know in the you do not understand then let me know in the comment. comment. comment. what I have initialized here in the map do in it, what will I do in it, I will check the expression that I told. You have it, I will check it and the value will be my date, it will be my index, why the index, because what I have here, the size of all, I mean, kept it by saying here, so that is mine. kept it by saying here, so that is mine. kept it by saying here, so that is mine. so I am storing the index in the value, so my prefsum, which is the initial element, has zero behind it, meaning there is nothing in the elements behind it, there are no elements, so again we call it zero. So, its location is mines van mines van and I what to do is my total out and that zero went to mode Meaning, the whole of the error is divisible by p, Meaning, the whole of the error is divisible by p, so the minimum size is all, what will be the zero? There is so the minimum size is all, what will be the zero? There is no one, we do not have to remove anything, we have to no one, we do not have to remove anything, we have to give this equal, you give zero, return zero is fine, we give this equal, you give zero, return zero is fine, we This is a This is a This is a famous problem. Consider this prefix as a famous problem. Consider this prefix as a topic. It is asked a lot. topic. It is asked a lot. Okay, now what do I have to check in the map? I call it 'check' in the name of the variable. here? here? What is my J here? that's my perfect and like full and time plus b which I said that I will bed because this piece was added because if this whole becomes negative look at the total here look at this total But what do we have to do, we have come out here, now I have to check, here I know here I know that this can be negative and this can be negative which will be a negative number so I have also added plus to my if this is found, if this is found, now if this is found, now if this is found, if this is found, then if this is found, then this is what I have got, this is my current location, if this is this is what I have got, this is my current location, if this is found, MP of check, then there must be some index found, MP of check, then there must be some index found, otherwise this index will be stored in MP of check, so found, otherwise this index will be stored in MP of check, so from there from there from there then it should be smallest so the answer is equal you minimum of answer earned I - MP of check and here I will update MP of prefix us above I and not after every item if it Whatever is there, we have to update it. I have to Whatever is there, we have to update it. I have to Whatever is there, we have to update it. I have to Okay, Okay, okay, I submitted. You must have submitted. You must have understood it. If not, then
2024-03-21 14:48:03
1,590
https://i.ytimg.com/vi/F…axresdefault.jpg
Leetcode 1590: Make sum divisible by P | Intuition and Approach