id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,649 |
hey there everyone welcome back to lead coding in this video we'll be solving the question number four of lead code weekly contest 214 name of the problem is create sorted array through instructions the problem statement is given an integer array instructions you are asked to create a sorted array from the elements in the instruction you start with an empty container nums for each element from left to right in the instruction insert it into nums the cost of insertion is the minimum of the following the number of elements currently in terms that are strictly less than instruction i or the number of elements currently in nums that are strictly greater than instruction for example if inserting element 3 into nums 1 3 2 and 5 the cost of insertion is minimum of 2 comma 1 because 2 elements are strictly smaller than 3 and one element which is 5 is strictly greater than 3. now return the total cost of inserting all the elements into nums and since the answer could be large we have to take the modulo with the given number all right now let's see how we can approach this problem using an example so this is the instruction set which have been given to us the first number is one and when we are inserting one our container is empty so no number is smaller than one and hence no number is larger than one so the cost will be zero one will be inserted into the container then the next number is five now there is no number which is greater than five so again the cost is going to be zero there's a number which is smaller than five but we have to take the minimum so that is why we are going for the larger number and there is no larger number than 5 so the cost is 0 in this case the next number is 6. again there is no number which is larger than 6 so it is 0. then it comes 2. there is one number which is smaller than two and there are two numbers which are larger than two so we are going to go with the smaller side here there's only one number so the cost is going to be one and we are done creating our nums array all right so we have to return the cost and the cost in this case was one let us see another example here and let us see how we can approach this efficiently so let's say we are starting from here and first of all let me list those numbers which are present here so one two three and four initially the frequencies of these numbers are zero when the number one arrives the frequency of all the numbers are zero so we will see what all are the numbers which are smaller than one as one is the starting number so there is no number which is smaller than one in this case the answer will be zero and the frequency of one is going to be incremented and it will be one then the next number is 3 so for 3 we will see that how many numbers are there which are smaller than 3 so we will have to traverse through all the numbers which are smaller than 3. so we will see what is the frequency count of 1 what is the frequency count of 2 so in this case it is 1 plus 0 which is 1 so only one number is smaller than 3 and for larger number what we are going to do is we are going to see that how many numbers have already been inserted there is only one number which is inserted that is one so one minus is smaller and one number is already smaller so one minus one is zero so the count of larger number is zero now the frequency of three is going to be one then again three is going to come and frequency will increase again no cost then the frequency will again increase and again there won't be any cost because there is no number which is larger than three all right now the number 2 is arriving and we have to see that how many numbers are smaller than 2 so there is only one number which is smaller than 2 and that is 1 and there are three numbers which are larger than 2. so in this case the answer will be 1 and the frequency of 2 is going to be 1. now the number 4 arrives and for this the frequency will increase and the answer will be 0 because there is no number which is larger than 4 but still we will have to count how many numbers are smaller than 4. so for that we will have to traverse the entire sequence starting from 1 till 3 and we have to keep counting their frequencies so their frequencies are 5 and already 5 numbers are inserted so smaller numbers are 5 and larger numbers are already inserted numbers that is 5 minus smaller numbers that is 5 it is going to be 0. so now the number 2 arrives now the number 2 is going to see that how many numbers are smaller than 2 there's only one number so smaller numbers are 1 and for larger numbers already inserted numbers are 6 minus 1 minus the count of 2 itself so the count of 2 is 1 6 minus 2 which is equal to 4 so 4 numbers are larger and one number is smaller so for this we are going to add 1 to the answer now the number 1 is arriving and we will see that how many numbers are smaller than 1 there is no number which is smaller than one so for this the answer will be zero and the frequency will increase to two now the number two is arriving and for this we will see how many numbers are smaller again we are going to traverse now for each entry we are traversing the entire array till that number so as to count the total frequency of numbers which are smaller than this number so that is going to take big o of n for each of these numbers which are present inside this array so in total it will be big o of n square in terms of time now when we want to get the summation from the starting point till a certain point we can think it in terms of cumulative sum or the prefix sum so for that we can keep the prefix sum but there's something that we'll notice when we are keeping the prefix sum each time when a new number comes the entire sequence the prefix sum for the entire sequence have to be updated so again the updation is going to take big o of n when the number keeps arriving we have to deal with the updation in this case the updation is big o of n and in the previous case the calculation was big o of n so how can we get the best of both the worlds so we can use a structure called fanductories or bit trees if you don't know about the data structure you can go to the description and learn about fan victories and then come back and try solving the problem and for those who know about fan victory we can continue with this the fan victory stores the prefix sum in this case we will be storing the prefix sum of the frequencies of numbers which are smaller than the current number so let's directly go to the code and start solving the problem with the help of fan victories so let's quickly create a fan victory and the numbers that we can have is from the range 1 till 10 raised to the power 5 so for that we are going to create the bit tree of size 10 raised to the power 5 we will create two functions one is to get the sum the prefix sum till the index i so for that we will run a loop j is equal to i j is greater than 0 and j minus equal to j and minus j plus equal to bit of j return answer the next function is going to be update so it is going to be avoid update in starting from the index i we have to increment the frequencies so we'll run a for loop j is equal to i j is smaller than equal to so let us increment the size and j plus equal to j and minus j v i t of j plus equal to 1 so this is the update and this is the sum now we will go to each of these numbers one by one we can start with the first number i is equal to 0 i is smaller than let us keep the variable n as the size v dot size where v is the instruction set smaller than n i plus let us create the answer now we need to calculate the number of integers which are smaller than the current number so for that now to the answer we must add the minimum of the smaller numbers and the larger numbers so this sum is going to return us the cumulative frequencies of all the numbers which are smaller than or equal to i so for that we will call sum this will be our smaller numbers smaller number than any current number so for that we will have to send v of i minus 1 and to calculate the numbers which are larger than this we already have the total numbers so total numbers are i which are already inserted minus sum of numbers which are smaller than or equal to the current number so for that we will have to send v of i also after this we will have to update bit tree so update v of i and finally we can return the answer we are getting correct answer let us take the module as well hash define mod so here we are taking the modulo and let us try to submit this so we are getting correct answer now for each number the updation and the summation is going to take log n so the overall complexity of the solution is n log n where n is the number of elements so this is it for the video if you like it please subscribe to the channel and the solutions to other problems from the contest have already been uploaded thank you
|
Create Sorted Array through Instructions
|
maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
|
Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The number of elements currently in `nums` that are **strictly less than** `instructions[i]`.
* The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`.
For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.
Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`
**Example 1:**
**Input:** instructions = \[1,5,6,2\]
**Output:** 1
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 5 with cost min(1, 0) = 0, now nums = \[1,5\].
Insert 6 with cost min(2, 0) = 0, now nums = \[1,5,6\].
Insert 2 with cost min(1, 2) = 1, now nums = \[1,2,5,6\].
The total cost is 0 + 0 + 0 + 1 = 1.
**Example 2:**
**Input:** instructions = \[1,2,3,6,5,4\]
**Output:** 3
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 2 with cost min(1, 0) = 0, now nums = \[1,2\].
Insert 3 with cost min(2, 0) = 0, now nums = \[1,2,3\].
Insert 6 with cost min(3, 0) = 0, now nums = \[1,2,3,6\].
Insert 5 with cost min(3, 1) = 1, now nums = \[1,2,3,5,6\].
Insert 4 with cost min(3, 2) = 2, now nums = \[1,2,3,4,5,6\].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
**Example 3:**
**Input:** instructions = \[1,3,3,3,2,4,2,1,2\]
**Output:** 4
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3,3\].
Insert 2 with cost min(1, 3) = 1, now nums = \[1,2,3,3,3\].
Insert 4 with cost min(5, 0) = 0, now nums = \[1,2,3,3,3,4\].
Insert 2 with cost min(1, 4) = 1, now nums = \[1,2,2,3,3,3,4\].
Insert 1 with cost min(0, 6) = 0, now nums = \[1,1,2,2,3,3,3,4\].
Insert 2 with cost min(2, 4) = 2, now nums = \[1,1,2,2,2,3,3,3,4\].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
**Constraints:**
* `1 <= instructions.length <= 105`
* `1 <= instructions[i] <= 105`
|
Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal.
|
Array,Hash Table,Greedy,Prefix Sum
|
Medium
| null |
84 |
Half a minute Sarai's performance went restrictions, let's go ahead and see that the next one is the distraction histogram. Without tightening this question, don't go for the third tomorrow, friend Vikas, this tawa pulao is instant that you will not be able to understand what is going on in it and till now This is the best question to a great extent from Google Microsoft Actress Top Fancy, many sweet companies also refer this question, Ramesh is reportedly found in Vikas Hall till now, those who have not seen this type of play list since the beginning I would recommend that please watch from the beginning, if you want to learn this type well, then I am waiting from my end, the way I have done Singh Rashtriya very well, I will complain towards the complete side. Okay, if you have not watched the beginning, then please. See, now I will move ahead also, appeal old concepts will be used in this, definitely, all this is fine, so let's start, let's see what is the question and basically, what is it, okay, largest rectangle, we have to remind what will be its area, like this Your input is given, this note is given, the length of the outside is one, okay, so it does n't make sense, okay, and we will keep it quick like this, send it, which is so much, which is the test flight from its area, so if we Talking about this thing, if we talk about *, we Talking about this thing, if we talk about *, we Talking about this thing, if we talk about *, then the area of two is only that of you into one of two, we will then the area of two is only that of you into one of two, we will then the area of two is only that of you into one of two, we will make a system of guava, basically the area which is difficult to call, if we talk about the Mann Ki Baat program, this one is a serial, it is complete. This area becomes completely sharp. Okay, how much is this? If the height is one and the total bar is how much is 123456, then one is interested, total six heels. If you consider this toe, the dealership is saying that brother, how will you do it, we will cut the toe till the bottom here. If till is fine, then this entire area is formed. Okay, green one, if we had stirred it, then what would have happened, then keep its result, roll out how much of the court, 1234 Chahta Maya Nagari, share on Facebook, this area of ours is increasing from 235. The big one was this area of ours is increasing from 235. The big one was this area of ours is increasing from 235. The big one was 52210 and settled on the side. I understood the question that how to do Megha Saunf but doing this little coat is a good deed on yourself. Now the question of don't be afraid after seeing her heart attack, really the gesture is not that much right. But you will have to understand, I will install it till the end. Enter the video of the articles and you will understand very well what question has to be solved. Now come on, if I talk about this question, do not delay, talk about the middle of it will break further, tell me. Why would it return this file? Even if I had centered this one, we can even say right, then this one would have been an Area account. How thick is this two * for? Right, if I had How thick is this two * for? Right, if I had How thick is this two * for? Right, if I had made this lineage an account, right, if I had appointed this one. If it is of one neck, then it comes in one and a half account, how much does it cost, it is 1234, whereas directly, five Raees alone, then how much does it cost for this file, which you have put on the other side, this is also clear to you, if you have a question then you will be fine. But speed is the most basic and saffron, which I named American point, but why is it named Decris? Opposition, if you have understood this line now, this is the way to solve Consider Every Small, it is ok, you will be able to solve it, just a science fiction. Every time it is small, now you can also remember it is not a big deal, as after remembering, it takes some time for our normal thought process to connect fully to this line, hence I am telling you that you should understand this. What we do is we chant this mantra once and according to that outside and people set that if you consider this time as the recitation of the acute triangle which is the poorest then what it would be like Let's ask for Bittu, okay, after this is small and there is no subscribe for this, okay, so let's go here, we can go to the whole, why subscribe, all of them are okay, subscribe to this one, this The account is fine and Azhar Kitna account is 12345 umbrellas 65. There are five Kepler left side of it, is there any big limit, isn't it like that, all of them are small, so we have got this small limit, we will go home now, otherwise if we increase it till after last here, we got the intoxicating ticket. If we get it, we will lead the workers and give gifts to this dough. * How many times can we do it, * How many times can we do it, * How many times can we do it, then the tax is fine, now it is on this side of six, it is bigger than this, no, weekly, we are considering some tips as the minimum, then the rectangle that we will make. So will you share the like, the one on the side is bigger than that one and this one here is bigger than that one, increase it a little bit, there is nothing on this case, next explosion item is small, just settled here alone, six into one, same thing, 6 grams, its wanted to create a, so We need a bigger side here too, now it is just a little smaller, so we will grate it. If we talk about the right side of the site, then this one is also big, we will mix it and add more elements here, otherwise it is two * How much and add more elements here, otherwise it is two * How much and add more elements here, otherwise it is two * How much difference is there in the four sides of the house? Eight okay, now very quickly three don't increase it from 62, this is our basic concept for that and see which ones to dip and talk about that, very simple step okay this question A six is different from six pieces. Don't think that we had learned this from the left side of the village that when we say what song, when left side first then how do we put i, it is ok, this i = 0 is ok, how do we put i, it is ok, this i = 0 is ok, how do we put i, it is ok, this i = 0 is ok, then i is equal to z spoch, any element in the middle is this i, so Knowing what we will do, if we do it together then we will move on the left side till we get more elements from it. Okay Chhota Mirza Dabir, don't forget to do small points in development, we have to go to the big ones. It will remain in f5 that if I talk about this, okay now we can go here six pack and pipe can go for also but we will stop at this why it is small got the height if we diagram psychology of this how will it become this six this Two is this, then this affair and this award is fine, so that dear bittu is fine, if this is two then the rich can buy tickets here, can record here because here the challenge is also big, smooth and small, so reminding the time is a little good. Considering it as minimum, are you able to understand what I am trying to say, so what did we do - It happened we do - It happened we do - It happened in 1757 AD that the whole came from I to this zero and this end. Okay, let's send it Ajay - - zero and this end. Okay, let's send it Ajay - - zero and this end. Okay, let's send it Ajay - - Okay. And this FZ which we are going to, if it is big, what will we do with infidelity, will we add infidelity to the current data, why will we add it, brother, let's get to, okay, what are we going here, starting is okay, it means, what is our answer? Trick or development on save current, we have inputted it and diet, we have looted this one, now we can go to the next side, we have got one more, now we can go here, we have got one more, we can decorate, if we have got two more, then total we Adding two is fake, which is our basic minimum balance. We are making a rectangle of that size. If we can go to the side, then I have brought one more side and added it. Okay, and it will be found a little smaller. Will we do it? I do n't know after that, we are sure that after breaking this, we will start playing till the generation end plus the same, we will do the same here also, if the place where we are going is big, till then we will keep going and keep adding that height. On this side, we are running assuming this current. Look, we are running assuming this current. We will keep adding it till that extent and as soon as we get a small limit, we will just back it up. If the entire limit comes out, then the results will be the same. This is our final answer, you will see whether Andheria will do the new one or you will consider it as the current area. Ok, the current area is the current area, it is big, this trick is there in the Puranas, which is a big hospital. Let's update it, we will add red chillies. What is your work, dry run it, call me, if you want to learn with me, then you have only one option left, you will be able to learn health while working with me. When I saw this question for the first time in Italy, I filled two pages or Depend on two to three, do it on your own, now I will give you and yours the dominance driving phone, let's go, if not ask for advice or induction, okay, if you have done dryer, then on the possible side, give only higher education, okay, development, we walk here. Start here, you ca n't go here, there is opposition element here, if you can't go because of small limit, then you will update the result with some tips, then comes equal one pinch current will come, there is two take here, you can go next, [ __ ]. If you can go, the current has come to can go next, [ __ ]. If you can go, the current has come to can go next, [ __ ]. If you can go, the current has come to here, you can lie down next to the personality, Gattu and added it. From here, you can go right to the right. So we will grate the finished result, it is bigger than this, six remain equal tubes, so by moving the black, you got the ticket, by going here, you got the ticket, current will come from the other one, five, what will you not do to update the result, Vikas result is already maximized now On coming to the right floor, if you find a husband who is elder in religion, then take 4345. Now this one will loot, if you get one more, you can go here, then 4008 is gone. Okay, so do 8. The one who has the result is David, so there is no point in updating. If we fail then we can go till the whole minute so 151 was exile 300 this is the current one and this is another birthday 1234 examples can be given 12 so for plus 384 plus 7 ok so total seven just updated If cholera does not spread then you can go left but the light could have gone plus if it fails then we will update the trend and the root of which then come on six but it turned out to be small and going here means no threads are related to it, do not update. If we give then ultimately the result will be the answer, it is inside us, then it is simple, but what is the problem, C, this is going on, it is fine, and these people are on the side, end and overall, this is going on outside, 2030 time complexity is done, that is done. Square that is open so this is for us we can do this okay now what is our target like this we are taking out this thing to the people and how it works like this which I talk about okay This is the first time, I am talking about what we have to do is that we have to go into it and see that someone was hating on it, that is why it is definitely getting a big momentum, can we understand it like this? If we continue this time, how long will we continue? If we go, then we are getting bigger limits, it is okay if we get some smaller limits, okay, this one, in external comparison, can we say that it is previously smaller and because of this, we got this bigger, this one got bigger, okay and Like we have got something small, okay, can we do this, can we do the next smaller, okay, basically, come and appoint us the particular bar outside this one, if we appoint the previous Ismail and after fitting the next smaller, where is the small will behind it in the late time? Next where we are getting small midnight or big element let's point sure this is our target we are pointing big element that is what you are doing and it has a bar and like if we got big length element then add this bar. After that, I got a big element, so this time I have to fold it, if I get a little, then it stops, okay, basically who is mine, if I talk about this side, then what is the previous model of this type, is it solar from this wave, one is okay. If yes, then previous means it is talking about its intact. Updates, reviews, come here next, in which country it is fine, so this time, if I cannot say that this tiger is only fine, then ultimately which * * * which * * * which * * * * Ghritarashtra is here. From and can go here - One is fine - World Admins that you are this - One is fine - World Admins that you are this - One is fine - World Admins that you are this minus one, what has happened to you - 02-02-2014 If you rate the point and make it two * - 02-02-2014 If you rate the point and make it two * - 02-02-2014 If you rate the point and make it two * height my * then what will come two into five height my * then what will come two into five height my * then what will come two into five Step sighing will go away, now I understand what we were doing, here also we used to do big sign and third big sign, what point did we get, here is this model, where is the next smaller one and the next stop of this point here is the next smaller one. These two stops will be at this point. There will be pyramids here and there. What did we do that we closed the index at the last point? How did we know how many total numbers are outside? Accept that particular segment as a particular bar. While setting Mubarak, he will multiply it by a bar, here the range is the big element, we will keep one, we can form the commission by considering that particular as minimum, you must have understood, friend, one more does, listen as if we were talking about it, now its PS What will happen PS means zero 123 456 where is its previous model it is not what it is not this butt its wish can't go till here behind it okay so one now its previous curse front one it means whose Toilet is smaller, what is it is big, it is purely romantic, it is over, I had talked about it by connecting it to the tractor located in Amritsar in Intact - but ok, how much is the total bar, where is it, where is the - but ok, how much is the total bar, where is it, where is the - but ok, how much is the total bar, where is it, where is the total bar, how much came 6 - 6 - 6 - in 110 - first, how much Hua Force Purva in 110 - first, how much Hua Force Purva in 110 - first, how much Hua Force Purva Aaya Si This four times we could consider were chilly considering were two major minimum bar ride if I talk about one okay then after one minimum who is you hum hai kya play his zooming is over then PS If we talk about 'Done' - Wall - then it PS If we talk about 'Done' - Wall - then it PS If we talk about 'Done' - Wall - then it is bad, six is bad, you are bad, three is bad, six is bad, you are bad, three is bad, six is bad, you are bad, three is bad, after that element is finished, then six, so its 6 - - Verb - One, so what six, so its 6 - - Verb - One, so what six, so its 6 - - Verb - One, so what is ok, you can see that total 6 times. Okay, in this way, two one, whose height is here, what is the height of four elements for entries, we are strict on the broken ones, can I understand piece or eight, what am I trying to say, it is very simple, happy shades. - - 110 * Height happy shades. - - 110 * Height happy shades. - - 110 * Height In this formula, we converted the less butter, how we folded the number and the bar and considered each bar as the minimum and estimated that we can make a triangle like this and multiply it and I paste it for you then if a little video is going long then big is necessary for you. Okay, which app will feel better for you to understand this. It means that what is our work which is that the result of our sun has been decided from zero. Let's go. Very good, I have appointed a previous small and I have appointed Maxis Mall, very good, now how will we calculate the area of each element, very good, now how will we calculate the area of each element, if we consider minimum one height of I, then the address of its area is I - PSI minus one * address of its area is I - PSI minus one * address of its area is I - PSI minus one * height. It will quote the text and its result. Our work has become easy. Okay, basically what will it be giving? Total number of bars. Okay, Total number of bars so that we are making the rectangle completely and will update it every time if I get it. Will add it in the last, now we are fully subscribed and now we will cut it. Advanced battle was seen in the last, in the same way, there are some similar questions, if you have not subscribed then please small ones are fine and this is what we have done. Given - 110 and subscribe to it that if the people following this index put some small element in the lines - on the left side of the flat surface, put some small element in the lines - on the left side of the flat surface, put some small element in the lines - on the left side of the flat surface, not found in some hotels at night, all the big ones will be found, then the beneficiaries will bear the burden of these taxes. Why are you doing this? C, I had talked about this, if I talk about this as an example, then who is small in the back side, two in the sky appears, there is no element in the right side, there is a test in it, this is the total element. How fast did it happen? 6 - 4 this is the total element. How fast did it happen? 6 - 4 this is the total element. How fast did it happen? 6 - 4 - It is the first which is as usual. - It is the first which is as usual. - It is the first which is as usual. To solve it quickly, we have assumed that if any element is not found on the left side - we will take 110 extra and if the item is - we will take 110 extra and if the item is - we will take 110 extra and if the item is not found, we will put 726 here, hence end. I have given you the total number of how much rain is that light, we will minute it, now you are clear till now, let's talk now, hit the code that says appoint the previous Ismail, write its code, if we have written the code for this that the previous matters. What would be the code of the question? It will be very easy, there is nothing left for us. Please do this first request. It may take you 10 minutes, 15 minutes, 20 to 25 minutes, but solve it, which is the duty of the PS. I have given you a career. Will remain, which is a bar stigma, it is better than the world number, now also we have to install the same Silly in this piece, every single recording like what we have here, what we have created the index here, we have installed it here, now you can check this. Is it correct or not and you should match it like this, if not then please do it once by taking this inductor as we have found it previously. If we talk about this particular part of this mantra, then wear one smaller than that, which is the minor index and which is bigger. Is and further smallness is getting two is getting so one and I If we talk about this then the smallest is getting one Bigg Boss-2 torrent is getting so one is one Bigg Boss-2 torrent is getting so one is one Bigg Boss-2 torrent is getting so one is next I is getting the smallest is getting one whose What is the index for? Okay, so I hope you call this and this is where we will come to the front and please code this, if you do, the day people code this, understand that you have subscribed till now. So you have to think, I told you, but why should this be asked of you and till now we have asked such questions, see the reviews, previous questions, this question should be asked of you in Stock Palace, okay, let's try this pattern. This is very important for me, especially that all of them are your real learning, its code is very simple, we started cutting it and saw that it is text-20, if the saw that it is text-20, if the saw that it is text-20, if the step is correct then it is simple, it means that you do not have any previous left, if there is no previous left then - We will start the play like this, if left then - We will start the play like this, if left then - We will start the play like this, if such a cast identity comes - we such a cast identity comes - we such a cast identity comes - we will minister and if the late supports strike is not MP, then is the top element big, if it is big then what will we do, will we pause it, why development us We need a small element, this is very important, I have kept it in mind here, we are currently removing the previous smaller element, that text is basically removing the index of the previous Ismail element, please focus, it is okay, then our missions fast smaller element index is okay, so basically look. Now stir it will be a just stop Kajol data when is the stock ok? If it comes big then what will we do we will pause it ok and while doing pop when if element if is completely empty statements that you have not saved the element for all All of them are big, in the house where people are getting big, they are going to cup the alarm, where the small one will be saved, that will be our answer, the answer will be on the tasty hotspot of time, okay, now I will joint it, okay that the time is At this time it is okay so basically an answer is our answer which will return to I can do rallies of add LPS okay princess standard so at this time to get started minus one the answer came - but will make more tips happy the answer came - but will make more tips happy the answer came - but will make more tips happy in this also that further For the elements coming in front of your belt, it may be fixed that they were small and right about, do the right thing, I taught you the next element by explaining it, because if we talk about it, even at this time, you cannot enter inside, Ajay is the top element, basically this Friends, zero will be fair, okay, that's why we are installing, if the top element is 282, okay then what is the top element, at this time six is basically how it is fitting, time six is basically how it is fitting, time six is basically how it is fitting, hey after std top up 6 is big, it means that we If people want a smaller limit then they will pause it and top it, now it's 2017 - but look at the Butt Office from Bigg Boss 2, 2017 - but look at the Butt Office from Bigg Boss 2, 2017 - but look at the Butt Office from Bigg Boss 2, behind the data, we have some element null which is this small in space - but now Coming to the face, is this small in space - but now Coming to the face, is this small in space - but now Coming to the face, when we talk about five, at this time, sorry, now when that was to remind one, it is an adjective. Maybe you can understand that for our upcoming element, two which is small and then things are fine on five when There are five so it was that not aunty but beautiful will enter and the top element that it will increase is small is the element of laptop. Hey, now you can compare like this if you are getting confused. Relief when you talk element is the air increasing or equal? Is it coming? Hey after two, here is that two presence killed 25, it is not like that, we will go out, if we go out, it is not at this time, then the add top which is in it will be the answer, has been added whose forest is everywhere, now only and But but now what will we do, set the tune that Bigg Boss can be there, for the further development, the small limit of five will be found, and when four is alienation, it is not there at this time and what is the top ten limit, at this time there is fiber. The fiber which is there, if it gets bigger then we will pause it. Now let's come to one UP talk element. If there is a to-do, then we will do it, then the small man will come to-do, then we will do it, then the small man will come to-do, then we will do it, then the small man will come out of the four and will be visible for this. We will set these to 143, okay. Now let's come to one, okay, if we are on such youth, then now the top element is the element of top, for you doctor limit 3D panel means that for which is bigger, then we will top, then come 151 tax has been imposed, it has increased from 201, we will top. Under this time teams, we will add minus one everywhere and inches to this point. Okay, now let's go to 5, so type Yeddyurappa element, the one which is small, so you smile from and do not enter inside it, the network will go here, the answer to this will go for. Now basically six come like six come top element what is the elephant of five laptops 5ghz it means that fiber friends simple means small 6 so after doing nothing now it will come out and its bread will go get the answer ok we guys This is the PS one, hey, we are ready, okay, when the back, hey, it is ready, add, then you guys know what to do, then we are going to find the area by simple, Dad I - PSI minus I - PSI minus I - PSI minus one * height, this By hitting this key, this is this and one * height, this By hitting this key, this is this and one * height, this By hitting this key, this is this and every time it is compared, this is more than this. So you have seen the previous one and understood it. Please friend, after testing this, please do the next flight and tell me. The code of neck system and key is very simple. There will be some changes in this same chord. And it will come out of all of yours, please do it friend, please do this model, you will get a lot of happiness, the commission must have done a lot, there was nothing to be done in this, friend, what did we do, this suspension was observed, crossed it and where - Play Store was and where - Play Store was and where - Play Store was installing, Vikas is installing by default. We are assuming that the index is next here, the song is seven again, it skips one and uninstalls it after that, if we are fine, then simple against. Aunty, at this time, the tips are quite fine and we will insert this tax. Maybe in the future, the mother that the six for this later coming element should turn out to be big, fix it and deal with it a little. We at 125 The Meaning of Element Data No matter how big elements are found, they will be popped. If they appear on the face, then six is that big. appear on the face, then six is that big. appear on the face, then six is that big. Sorry, it was not installed here today. Induction fix is a big joke. If you pop it, you will pop it and fix is a big joke. If you pop it, you will pop it and fix is a big joke. If you pop it, you will pop it and nothing will be left. So the answer to this is a complete development attack. If the step of installation is fine then move aside and feed five very well, if you go to one then what is the limit of Amla, five which is big, what they want is small, if your loved ones have fiber then they will top it, 100 is simple and the answer will come. Will go whole and we will set four, now give us this tree, then what is the limit, ₹ 1 is small, when the forest is small, how to run on ₹ 1 is small, when the forest is small, how to run on ₹ 1 is small, when the forest is small, how to run on this index, what is its index point, what is smaller than 124, but we will come out. Start our answer will go to this cancer will go for android in will set this time three okay now come here so if the element is small like 55 is small or smaller than 575 simple style Upendra Singh Dhindsa will go to the element its second place is this time Vacancy topic is three, then C has come and if you push, then it is very simple. Now let's come to this when you are tight, what is the top card limit for inter college students, incident five which is big, two will shift, then come 3D flashlight is on that you who That we will make the top from the big two, like this, fold the world school, but we will take it out from the smaller form and eat the top on an empty stomach, at this time the answer for four points will come and we will cut it, this one is fine, so let's make it simple. There is 66 stock limit, that electronics one means that if two which is found small then we will take it out from the bills and the top element is from the animal, this is the answer by drinking clean, it has gone out, a when the PM and we come to know, then when That last can be the mixture, you can give it a good news, Aishwarya, you will like it very much, okay, through this, you will reach the target, it will understand that you will like it doesn't even seem like it, brother, you will like it, please try it, you will really like it, gradually your height will increase. The thought process of doing gram code is okay to get the bills like this, Swapna Dosha does this code, what is ours that if you attack the previous one, then the co digger of the previous valve is okay, I have not done anything, the code is written there, same customer here. So that time can be saved and you can also do this, okay, next, whose one is to be written, next is the rate of the model, then this is the next9 previous code of the codeword, we have written the code, okay, so simple, our target is saved, now let's call this function, meaning that If we are given height then what can we do Next Solar PV Solar can be removed then int result 021 backed up torch light ps previous marks how will it come out previous call Ismail two bypassing height right end vector of address will come out this boxing fight In the simple for 108 sexual plus marked that it should be known took out now rest is the current equal height of i that will be multiplied by what now cooked this 20 minutes this i - sai - world this is our cooked this 20 minutes this i - sai - world this is our cooked this 20 minutes this i - sai - world this is our total number of come out Now our work is to update the maximum result 10th result a splash of midnight place one more button to solve this question matter okay in that you will not have to spend so much and this paste okay and I am telling you this because you should do so much guesting first, it will be a big thing for you. Okay, find development and once you start using it, you will become fit. But till now, mostly many people have understood this much. It came to me that we took the question in a basic manner, had basic facts, how did we start the approach and how did we solve the text till the end. If you liked the video, please do comment and share it with your friends. I was in my college group that this I am motivated, many people are supporting me, new episode soon, till then Bye Charlotte
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
1,762 |
all right so let's talk about the building with the ocean view so discussion is supposed to be easy so um I'm going to just follow that one so imagine this is a building ball this is building two this is building three and this is building one in the same definitely in the center for example so I'm gonna just use another color so you can only view to the right so building four you can view building through you can view and also building one so when you want to return the index is going to be zero two and three right so this is like return audio for index all right so this is going to be pretty much the idea right so if you're starting from the beginning like whenever you uh you want to go all over the rest of the album in the array you have to know like uh will my future building oh like will my neighbor building blockline I'll block my view right so the most easy uh the most easy solution is you store it from the end and then you can basically set the height to the uh to the local Max so I know nobody can block me right so if I travel to the left if this building is lower than me then I don't have to take care of it right if this building is equal to my height I don't have to take care of it right because I block The View right so um so you're still going to return this Index right and then whenever you go uh whenever you go to the left right then you probably will I mean you probably just have to check the height right so you will say height the maximum height by the maximum height it's going to be equal to what uh it's definitely going to be a new height for sure right if this one if this high is cooler than the local Max right and if this is smaller then we don't take care of it right and then this one is definitely greater than we update our local maps and then we also need to we also need another index to store the value for the index right so and don't just store the last Index right so the last thing that is going to be three and then comma and this one should be two comma zero right for the array for the return of the index is still going to be what a beautiful sorting and then increasing order so you want to basically you want to return 0 2 and 3 instead right so you want to reverse the array at the end and I'll talk about this later but if you know this idea like you're starting from the last building and to the first building and you'll be able to solve the question really easy so I'm gonna just here's a real list to store my index this is because we don't know how many elements you need to allocate your space right so I will have a map and I'll I'm going to servers so in height when it comes right and this is it right but I need immense so maybe uh and I also need to cover from the last right so I go to high school max minus one I create 0 I minus 25 so uh if my Max is what uh if my Max is greater or equal to the kernel one right then we don't want we don't take care of this element so we continue if this is more than if this element in this building is more than the maximum I'm going to update to what to the current height right and I need to what at the index into my release and then now I know how many buildings I have so in this case is three where the array inside the arraylist right is three two zero right you have to reverse and we also need to say return the values for in Array now already right so I'm going to say result let's go to new games business size and in order to return the results and then I need the fibers to the end and then result I equal to what this target this dot get and I need to starting from the last one so uh for the list it was three two zero and then I need to starting from the first one right choose the last one so uh how do you actually do this um you won't do what you want to use the list of size minus one and then okay sorry so this is this right uh let me draw the diagram again so this is this so how do we attend to the uh to the arraylist so this is only one so this is zombie three and two and zero right and this is in the ring right so the inner ratio returns 0 to 3 right so we need to say we want to append uh the list into the inner array reversely right so uh if somebody is a list of size minus one so it's starting from the last one and then you dig from it right or based on the right so this is not hard but it's a little bit uh thinking so let's talk about the time in space this is going to be a space and an access space in the real space all of them by and represent the length of the Heights and then this is all of them for the time for sure and this is all of and for the worst case but the timing space all the same so uh this is a solution and I will talk to you later bye
|
Buildings With an Ocean View
|
furthest-building-you-can-reach
|
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line.
The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height.
Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order.
**Example 1:**
**Input:** heights = \[4,2,3,1\]
**Output:** \[0,2,3\]
**Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
**Example 2:**
**Input:** heights = \[4,3,2,1\]
**Output:** \[0,1,2,3\]
**Explanation:** All the buildings have an ocean view.
**Example 3:**
**Input:** heights = \[1,3,2,4\]
**Output:** \[3\]
**Explanation:** Only building 3 has an ocean view.
**Constraints:**
* `1 <= heights.length <= 105`
* `1 <= heights[i] <= 109`
|
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
|
Array,Greedy,Heap (Priority Queue)
|
Medium
| null |
274 |
today i'm going to talk about the need code problem 274 h index this problem is rated as a medium but i believe like many people when they first look at the problem it's not very straightforward to understand uh let's us reading the description it says a scientist has index h if h of his or her end papers have at least each citation each as the other n minus h papers have no more than each citation each so here the ish like appears many times so it's not very easy to understand so i transfer this description to a way maybe uh sounds more familiar to engineers so this is a new description given a long negative integer array let us try to find a largest decay so we have like a uh k elements a lot smaller than line k so here uh let's check example so we have this array one six one five six so uh the final answer is like a six five six uh because we have like a uh the key is equal to three uh let's check why the case is three so um uh how about we choose snake two uh you can see here if we choose two uh we will have like a three elements larger than two so because we want to find the largest case so two is another the final answer uh how about we choose four uh you can see we don't have like a uh enough number uh like four number larger than four we only have like three numbers larger than four so four couldn't be the answer um i think if we uh if the array uh is not sorted uh it's not easy to find the what is the uh target key so here i think to solve this problem we need to like first sort by sort the array by its values so here you can see uh if i sort the array to be 1 5 six so i think now maybe it's easier to resolve the problem we can just go over from uh from the uh right side uh two to left so uh and check one by one so here uh i go to uh six and now i have one number uh it's itself six itself um so like uh six is nigel uh then one so uh but we are trying to find the uh largest decay so one is not the uh maybe not the largest one so we'll we will try in two fan and here uh k is equal to and six is still larger than two so two maybe a candidate and we go to the next part so we now in increment the key to b3 uh 5 is still larger than 3 so 3 is still a granted candidate but after we move to this one allow case increment to uh to four so one is not equal or larger than four so four cannot be a candidate so we find the uh the final answer which k is equal to two three so here i think the first solution is just trying to use a program to simulate the uh the process so here you can see i have this code already written down uh we have input it has a array first we sort this uh this array uh in uh increasing order uh this uh complexity is like a and log n and uh we define uh one k uh and the one uh reload so as i said before we just go over uh the array uh from the uh right side to the left side and we have okay to count like a how many numbers we have uh we already processed so uh so for example if we process this six uh case increment to one so and we evaluate uh if this uh its value is like a larger or equal to k and because we want to find the largest k so we in every rung if we find the vanity case we just compare if it's still the largest one and finally we retain this result so the algorithm is like fairly simple if we understand uh what is the problem is looking for okay we already solved the problem uh with a time complexity which is like a an organ so i think one follow-up question we made uh we one follow-up question we made uh we one follow-up question we made uh we might get from the uh interviewer is like can we do better than a noggin so here as we know uh the bottle lick of this problem is they could be sorting at the beginning so here we are going to uh trying to improve on the uh floating part so i think uh the second solution which is the uh follow-up solution uh maybe indeed uh follow-up solution uh maybe indeed uh follow-up solution uh maybe indeed some like a background knowledge uh first you have to know like a consort and our bucket sword before otherwise it's not very easy for you to come up this uh follow-up solutions follow-up solutions follow-up solutions so as i understand uh counting sword uh is a like a more strict uh variation of uh bucket sword uh for example what is bug story is like you can go over this uh this you can go over this uh list and you can uh put the elements uh which share the uh same uh attribute uh to one bucket uh so in this way you don't need to do a swap for all those elements so i think the time accounts complexity is just the o of n i'll go over this example to see how exactly this uh real solution uh works so first we have the same like array which is like a one six one five six so uh we need to define a new uh array to uh record the counts of each in each value so we define the new uh element new array as the size as the previous size plus one and we go over the original array uh and uh increment the uh jewelry or coordinate so first we go with this one so we increment the index one by one uh and we check this six um so there's one extra thing we need to take care of uh it's like because they uh the number the uh in the original array uh could be extremely large for example this is uh here the exam uh the number is six uh but it could still be like a 100 or 10k or something like that so uh here uh one tricky thing is like we don't want uh our uh the array to be uh extremely large so uh we need to do something is like if the original number the value is larger than the size of our new array we just increment the uh the number uh for the last index so here uh we saw six so we just increment the uh value for index five and we process one we increment the index one we process five we increment the index five and six increment the index uh five so the final then the counting for each venue is like this so the second state please like we need to trying to find the uh target key so to find the target key uh we are same we go over from the uh from the right side uh two to left side so and here we need to uh record a sum so this sum value will be the total number uh we have processed uh which is like a larger or equal to current index word value so here is like a we process this three and the sum is three so it means that we have like uh three numbers uh larger or uh equal to five uh but to the criteria of k we need to find like a maybe at least a five number larger or equal to five uh but we only have three so um so now uh there is no candidate and then we move to uh the left side that means like you know the sum is three it's mean snake we have like three numbers uh which is uh its value is larger or equal to four but it cannot still cannot meet the uh criteria so we move to lift now the sum is still three but we now we have like uh three elements uh larger or equal to three so this is already made our uh crit here so we find the final number which is like a three so here uh you can see i've written write down the code um so we just simply go over this code and see how it works so first as i said i create a little array to store the count for each value uh the size is like the original size plus one and we go over the original uh array and we need to check uh if this number is larger or equal to the uh the length of our new array we just increment today uh the last index so here i can change this to a larger format maybe it's easier for you to understand so here it is if it's not your actual equal to dens we just increment the index of last one else we just incremented the account for the value so and we have defined another negative sum and this means like until now how many elements we processed in total so here we just go over the jewelry from right side to the left side uh and uh right we inquire we sum up the uh sum menu and we check if they uh if the sum is like uh larger or equal to uh 2i uh if it's like a uh meet the criteria we just return the i which is the uh final answer so here i think it's now the problem two solutions
|
H-Index
|
h-index
|
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_.
According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times.
**Example 1:**
**Input:** citations = \[3,0,6,1,5\]
**Output:** 3
**Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
**Example 2:**
**Input:** citations = \[1,3,1\]
**Output:** 1
**Constraints:**
* `n == citations.length`
* `1 <= n <= 5000`
* `0 <= citations[i] <= 1000`
|
An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space.
|
Array,Sorting,Counting Sort
|
Medium
|
275
|
771 |
hey everyone today we'll be doing another lead code problem 771 joules and Stones this is an easy one you are given a string joules representing the type of stones that are Jews and Stones representing uh Stones you have each character in stone is a type of stone you have you want to know how many stones you have are joules so letters are case sensitive and if you have jewels and Stone here you can see that in joules I have two type of jewels a and a capital and now the stones I have are a two a capitals and Four B's so I will check that if this a is in the joules yes it is so I have one stone that is azure now I have again in the next you can say indexes or in the next pair I have a capital which is also a joule and if I add all of them up I am having total three joules these B's are also present in my stones but I do not have these bees in the jewel so I will not be adding them these are just not you can say the joules the stone I have but they are not the tools so here the capital z's I have are the stones but these Stones I have are not the jewels so the jewel is they were if they was in smaller case in the lower case then we are going to return true uh two here but we are going to return 0 because there are no stones that are used here I have three like I said before here I have three this Capital these two Capital A's and this one that are Stone so will be written that are joules will be returning the total output and that's it so making a total output we will be starting from zero obviously and for every stone I have so for stone in Stones I have if that stone is also present in Joule we are going to increment our total and then just return it that was this is very easy one so if the stone we have is in our joule we are going to increment our total by one and just return the total that's it
|
Jewels and Stones
|
encode-n-ary-tree-to-binary-tree
|
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`.
**Example 1:**
**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3
**Example 2:**
**Input:** jewels = "z", stones = "ZZ"
**Output:** 0
**Constraints:**
* `1 <= jewels.length, stones.length <= 50`
* `jewels` and `stones` consist of only English letters.
* All the characters of `jewels` are **unique**.
| null |
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
765
|
1,608 |
hey everybody this is larry this is me going over q1 of the recently called contest uh special away with x elements greater than or equal to x all right hit the like button hit the subscribe button join me on discord and let's get started so basically the thing to notice is that uh each element can go only up to a thousand so the answer is just proof force and because length is up to a hundred uh that's what i did you could probably do some sorting and sweep line as well uh but if you wanted to optimize it for speed but that's not what i did so uh so yeah so basically i just do a count and for each number i just count the number of things that are in the criteria that they tell you and then that's pretty much it um yeah let me know what you think uh this is going to be n times the max element but you know that's okay because n is only 100 right so yeah you can watch myself live now start it now let's go uh um uh that was kind of a wealth contest uh mostly on the q4 uh let me know what you think about me solving this problem and i will see you next contest bye-bye
|
Special Array With X Elements Greater Than or Equal X
|
calculate-salaries
|
You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`.
Notice that `x` **does not** have to be an element in `nums`.
Return `x` _if the array is **special**, otherwise, return_ `-1`. It can be proven that if `nums` is special, the value for `x` is **unique**.
**Example 1:**
**Input:** nums = \[3,5\]
**Output:** 2
**Explanation:** There are 2 values (3 and 5) that are greater than or equal to 2.
**Example 2:**
**Input:** nums = \[0,0\]
**Output:** -1
**Explanation:** No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.
**Example 3:**
**Input:** nums = \[0,4,3,0,4\]
**Output:** 3
**Explanation:** There are 3 values that are greater than or equal to 3.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000`
| null |
Database
|
Medium
| null |
1,021 |
10:21 we moved out of most parentheses a 10:21 we moved out of most parentheses a 10:21 we moved out of most parentheses a weather parentheses string is either empty I don't know said like left wind wiper in and then this moment in the middle a plus B where a and B are valid parenthesis strings and plus my percent string concatenation for example their example rounded parentheses strings about a parentheses string is primitive if it's not empty and there does not exist a way to split it into S Plus P okay that's interesting and a and B with a and B non-empty violet Tennessee a and B non-empty violet Tennessee a and B non-empty violet Tennessee strings I mean that makes sense given a rather pregnancy as consider this primitive decomposition return s out to be moving out of a parentheses of every primitive string in the primitive decomposition of s okay yeah I mean I think so I mean it's a easy and it's just a mouthful barrel thing made I feel like it's not very hard but maybe there's some edge case I haven't answer and there's a lot of downloads but that's a little bit of matter but I think yeah anytime you see these kind of parentheses stuff or I'm tremendously is probably the place where it comes up more but a lot of like balancing left and the right and stuff like this what I usually like my first impression is to it stacks right and that would kind of push and pop myself and in this case my quick dot is just push everything in the stack and well what is it out of most or yeah what isn't out of most parentheses in this case that means when you pop something off the stack and go some zero to one then you just don't point it and I think maybe that's good and then in all the other case when you pop you play with it yeah and then you could do some like Korean values and then just in the end do one more pass their ways to do it without the extra pass but I think for me it's just easier to understand just think about so I'm going to try to do it that way and let me know if y'all have questions as you follow along hopefully or as my friend said you pause this video and then come back to me somehow you know this is a live stream but uh and try it at home mmm cool okay so usually I just literally label myself stack and he's in Python it makes sense kind of I just couldn't operations I'm used to calling them operation because this is like for me it's kind of like parsing and that's kind of how you would pass it like this you centered like a language of some sort with some weird way but okay so you go to the left winced and we push it onto the stack oh I just say should use and then we put we need to index this once died otherwise so no other types actually so this is always a valid string yep okay one thing to note which I usually tried to put in this poem in this form because I feel like there's a stack frame there's a damages over N and O of n it's going to be fast enough just because that's how much time it would take for you to read in the data anyway but have a look at the constrain more sometimes in this case n is equal to 10,000 so that means like you can't even 10,000 so that means like you can't even 10,000 so that means like you can't even think about anything higher than of and I mean n log and maybe depending the thing that but that usually would just mean sorting or dividing concrete which in this case I guess you could kind of just call it that but it wouldn't be it would still be like n square type things so yeah that's why I shouldn't miss Q languages to elves and then we could just pop and then now we check because we don't want the outermost one so that we would check to see if name was if the stack is now empty then that was to all the most one so it's not zero actually whoops it's not empty that means it's one the inner ones then we should do you should let's just say I said - come on - should let's just say I said - come on - should let's just say I said - come on - true and also set the frame that we pop - true and now we just have to return - true and now we just have to return - true and now we just have to return the results and it's just a string and now we can you and should use that's like a terrible naming bit and we need to index on this one that's where awfully right and you can make some comments about string you can cat did I miss Regis no my expected is right so my output looks to be equal to the test case though maybe Nico's having some issues okay well this time to the coupon went away and I have good stuff so that's submitted cool okay I mean it's fast and moves like a pie frankly I didn't never know I mean I actually don't know how like what is the variance on decode I've heard is something like you could you see it goes up and down like 20 to 30 minutes I can usually for me that's why that a song like it's more binary and that sort surpassed within a reasonable time then it's good I don't really try to optimize that much well yeah I'm actually I explained my logic with this poem while I was going through it so yeah and I've definitely seen a lot of stack ish stack related problems my interviewing days so definitely pop up on it this would want to say yeah I would say this is okay I mean I wouldn't say it's straightforward it's just that it's expected so definitely yeah practice and yeah I mean I know obviously everything's off and in this space it's also over and because that's your you know that's going to be your results ice kind of so I can really do better than that and that's this is n square but that's another but that's just string concatenation stuff which by trapping in pipeline is not but no don't quote me on that one but yeah it's still easy so I think they expect you to know how I'm doing even if that so many downloads I mean it's not the best part maneuver it's not the worst form in the world I mean it seems interesting actually because it I think the key on this one is just figuring out that actually the line that I was on line 13 we're like how do you count like what's an outer most parentheses so I think in that sense is a good ish problem in that you know they take something that way basic and then ask you about properly on what it means to be using that stack without about being explicit like hey this is what you do because yeah and you have to kind of make that mental conversion between like what an outer parentheses is and what it means to be on this stack state so Ryoka
|
Remove Outermost Parentheses
|
distribute-coins-in-binary-tree
|
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings.
Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings.
Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`.
**Example 1:**
**Input:** s = "(()())(()) "
**Output:** "()()() "
**Explanation:**
The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ".
After removing outer parentheses of each part, this is "()() " + "() " = "()()() ".
**Example 2:**
**Input:** s = "(()())(())(()(())) "
**Output:** "()()()()(()) "
**Explanation:**
The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ".
After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ".
**Example 3:**
**Input:** s = "()() "
**Output:** " "
**Explanation:**
The input string is "()() ", with primitive decomposition "() " + "() ".
After removing outer parentheses of each part, this is " " + " " = " ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'('` or `')'`.
* `s` is a valid parentheses string.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
863,1008
|
80 |
hey everybody this is larry this is day 11 of the leeco daily challenge uh hit the like button to subscribe and join me on discord let me know what you think about today's farm uh we moved duplicates from sorted away too uh so yeah so i usually solve this live and especially with the explanation as well so feel free to watch in 2x or skip ahead if you like uh okay so basically we move duplicates okay so it appears so okay so basically we move more than two copies is that right so you have at least most you have at most two copies of each number but they're sorted so um i actually don't know what remove duplicates from sort of wave one is but i think it is still the same idea which is that you know you just have pointers and you have to keep track of uh you have to keep track of numbers to make sure that it doesn't appear more than two times right and you could do that in a number of ways uh and maybe if you want to generalize it that's okay too um the way that i'm going to do it is uh the way that i'm going to do it is just doing a couple of if statements but i'm just looking at it because it looks a little odd um i'm trying to figure out what the in well the input is symbol i suppose but the output and the number okay so i um i think i have an idea what this is saying this is asking for because you want to modify it in place um you want to return the number of elements in the final array and you could just return it away but i suppose they only care about the first seven items in this case uh yeah so basically the idea behind this algorithm is just your two pointers right one for the beginning of the array that you're looking at and then one for the end of the way that you're processing the one in the front will be your the one that you write to and then the one in the back will be the one that you read from uh so in this way um you're trying to do take care of the um you're trying to basically figure out what the variant is for each of these loop and the invariant here is that the back pointer will always be behind the front pointer because you're always going to at most remove um because you're at least going to remove items but if you don't remove any items then they'll just be moving in lockstep okay so let's do that i suppose um how do i want to implement this so let's say for index and range of n i always like to set n is equal to length of the nums um i think this is okay but maybe i want to do n minus 1 so that we don't do more than that or maybe even n minus 2 and you'll see why in a second which is that because i want to do something like if index um uh yeah if index is equal to num sub index plus 1 is equal to num sub index plus two then i think that's right syntax i'm not sure actually i think that is right in python but i could be wrong so i just let me save and then the front pointer is equal to zero said that so if this is the case um well if this is the case then we don't want to write index plus two actually let me just rewrite this uh for a second let me start from two instead so that we our indexing makes a little bit more sense maybe and you go from indexes you go to minus one and minus two and then now i would say that you always write the first two elements because no matter what your um the no you cannot have three ways for the same number if you have you know the first two number cannot have three numbers being the same number right so you could skip the first two because effectively you write to the first two so actually let's start the form at two in that case and then now you have nums if this is so we want the inverse of this and if you remember your logic this is actually morris toten i believe or one of those things or the more maybe it's de morgan i always confuse them but in any case uh you could just invert the logic and feel free to leave in the comments what the name of that actual uh logical operational switch is uh but okay so then that means that if this is the case that means that you're able to get this from num sub index and then one increment by one right because in any other case well the only other case is that numbers of index is equal to numbers of index minus one and numbers of index is equal to numbers of index minus two and in that case that means that you have at least three numbers in a row so you don't want to write in that case um but so the opposite of that the inverse of that is that you want to write which is what i did here and that's pretty much it i think um because i think that's the number you want to return and because you do it in place i think that's all you need to do let's give it a spin let's give it row 12. um i seem to be having an off by one maybe i'm my logic may be a little bit off uh for the degree of a kind but because this is clearly off uh let me look for my logic again because if it is equal to both then you don't want to write right so okay maybe i messed this up um right in this case we don't want to write so let's do change a not to this does that change my answer that is interesting so we still have one we get the one we skipped and then oh i see because what happened here is that i messed up so the last two number is not the last two number in the adjacent array but the last two numbers you wrote right so this is actually front minus one and front minus two um okay whoops okay there we go uh let's hit the submit button so the tricky part about this problem is okay i was gonna say get it right because if i get a wrong answer but the tricky part of this problem is getting it right but also just thinking about the invariance of this problem and thinking about your pointers in my case i confuse the pointers for half a second which is why the index and the front but as soon as i get that because basically the idea is that okay you have an index the current index in my code this is the candidate for whether we want to add this number right and we want to add this number if and only if the last two numbers that we added are not equal to this number because then in that case you have a third number that's the same um yeah cool i think that's why i have it with this problem um it's linear time i guess constant space because we manipulate the input um hmm yeah i mean i think i don't really have much more to say i mean it's a little weird it's a little bit um you know constructed in a very forced way in the in placeness of it um usually you know usually you can you have to extra space or one extra space is not necessarily done and then maybe they'll ask for that but in place algorithms are always a little bit tricky with respect to why that is uh i don't know i want to say that this algorithm is not super interesting but this concept does come up in play a lot with respect to in place or not sorry with respect to two pointers algorithm so definitely practice your two pointers algorithm i think that would be my takeaway for this problem uh that's what i have let me know what you think i will see y'all tomorrow and have a great whatever bye-bye
|
Remove Duplicates from Sorted Array II
|
remove-duplicates-from-sorted-array-ii
|
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`.
Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\]
**Output:** 5, nums = \[1,1,2,2,3,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,1,2,3,3\]
**Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\]
**Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
| null |
Array,Two Pointers
|
Medium
|
26
|
79 |
in this video we're going to take a look at a legal problem called word search so given am times in grid right and a word find if the word exists in the grid so when we do word search we can do horizontally right we have to uh construct the letters sequentially adjacent cells and we can do this horizontally or vertically neighboring right so in this case the same letter cell might not be used more than once so we can use the same letter but we cannot use the same cell right and then here you can see we have the grid and then we have a b c e d we can go first find the letter right in this case a and then we're going to search all four directions to see if the next letter is consist in this case we can we found b right which is on the right then we know that there's we got to continue to search and we search all four directions for c now c is right there search all four directions to c and c is right there search all four direction for e now e is right there and then search all four direction for d now d is right here right so we know that oh well there's there is a path and then at the end we're just going to return true right so if there's no path we're just gonna after we search all four directions if none of those path is equal to fall uh is equal to true then we're just gonna return false right so but that's one case and the other case is that we have to thinking about how to like memoize the result right like how can we store the visitor node and how can we keep track of the unvisited node what we're going to do is we're going to use a boolean 2d array and store the unvisited cell on as false and visit a cell as true so let's say we have an example like this a b c e right and the re the result is false and the reason why we have result is false here as you can see it's because we don't have a b c b and you might be thinking well there's a b c and b right there but we cannot use the same cell we cannot use same cell right so if we cannot use the same cell that means we have to have a way to like memoize we have to how to have a way to keep track of which cell has visited which cell has not visited so let's say we found this character the first character which is equal to the first character in the word then we do a definite search for all four directions then we find if this is visited if this is not visited then we're going to continue to see if this character is equal to the second character that is equal to the word now if it is equal to the word okay cool then we're gonna search on the all four directions and we know that this is visited so we don't we're not gonna bother we know that this is not visited but this is out of bound we know that this is not visited but this character right here you can see is um is basically not the third character and we know that this is the third character okay then what we're going to figure out is we're also going to search all four directions but we notice that this is visited even though this is b but this is visited so we're going to return false for this path this is out of bound this is not a character and this is not the character either so in this case this path will visit it but we're going to return false and we're going to use backtracking to go back and say this is false right and then we're going to continue to search nest a in this case a is right here search all four directions if there is no character that if there's no path now we're just gonna return false right so that's one case right that's one case for using the memoize um the caching the result right caching the visited and unvisited nodes uh visit and visit a cell but what if we have something like this right so first of all we know that it's true because we have a b c e s e f s right in this case what we can do is we can same thing apply the same principle we can find the current character right but up to here up to this character right we do in that first search and then up to this c we know that there's two e you realize that they're two one e if we go down this path this e right here we potentially end up in a wrong path which we will traverse s right there and then traverse e and then realize that this is a dead end right this is a that path right there's no more uh elements then it will return false but at the same time it will mark those places as visited so what we need to do is that if we realize that this place right here and this like this path this direction is false then what we have to do is we have to mark those positions to false or in other words make them unvisited like if this path that we go down to is uh is a wrong path is a is false then when we going when we're backtracking when we coming back we also have to make that position unvisited so that when we go to the different direction let's say if we were to go to a different direction on the right we know that this is unvisited so that we can explore all of their options and then figure out from there so now we know all those cases special cases let's try to do this in code so our first step will be to creating this global variable called um matrix we're gonna get matrix is equal to board okay and what we're gonna do is we're going to have a we're going to basically use a nested for loop to iterate each and every single element and the goal right now is to first find the character find the first character that is equal to the word dot character at zero so we're going to have letters is equal to word dot 2 character array integer row length is equal to board dot length column life is equal to board at 0.9 at 0.9 at 0.9 okay so then what we're going to do is we're going to we're just going to use a for loop to iterate so once that's done what we're going to do is we're going to perform our defer search if we found that the current character which is if matrix right if matrix at i at j is equal to letters at right letters at zero the first character right let's put here if that's the case then what we're going to do is we're going to perform our defer search so we're going to have a boolean result is equal to that first search we're going to pass thin the current result right sorry the current coordinate i and j as well as which character should we start in this case we're going to have a dfs method that takes the carbon coordinate i and j right the current row in the current column then we're going to also take the uh the current the fir uh the first character right the index of the word the letters array in this case we're starting at the zeros index and what we're going to do is that if the result is true right we found a path using dfs then we're going to return true otherwise we're going to continue to find the next character that is equal to the letters at zero and then if we find it we're going to return true if we don't find it after we traverse the entire grid which is going to return false now let's create this dfs method current row and the current column and then the current index okay so what we're going to do is we're going to first define our base cases right our base cases and then once we define our base cases what we're going to then do is we're going to see if um current letter is equal to um the word letter right if it's not then we're going to return uh false but this is kind of like included in our base case so we're going to do is we're going to do a depth or search for all four directions the directions okay once we do that for search for all directions and if one direction is true then this is a valid path if no direction is true right if we found that okay well there's no direction is true then what we're going to do is we're just going to return false okay so in this case what we're going to do is we're going to basically return the result right so return the result at the end but first we're going to have a boolean array visited that stores the visited result and for each iteration we're going to have a brand new visited okay so that we're refreshing the results so we have a brand new grid to work with okay and we're going to have a size of row length and we have a size of column length now we're going to do is for the base case right in this case if current row less than zero where current row is bigger than or equal to array.length bigger than or equal to array.length bigger than or equal to array.length not a radar life a matrix that length then we can return false and if we have a situation where the current column is less than zero or if the current column is bigger than or equal to matrix at zero the life okay and then what we had to do before that is we have to make sure that the current index is actually within the range because we if we have a situation where the current word like we already successfully traversed all the words when we found a path we found the word right and then in this case for the next word if we the current index is out of bound then we're just going to return true so then what we're going to do is we're going to focus on validating so in this case it visited current row at current column if the current position is visited already then we're going to return false because we already visit that place we don't want to visit that again right then we're going to do is we're going to have the check to see if the current character is equal to the uh current row current column is equal to array at current index right if it does not equal to current index then we can just return false otherwise we're going to continue to do our job now we know that this is equal to then what we had to do is that we have to mark that as visit so visit it at current row at current column is now equal to true because we visited that place already now we're going to do our dapper search this case we're going to have boolean top is equal to that for search current row minus 1 and current column index plus 1. we're moving on to the next index left is going to be current column minus one right is going to be plus one and then basically what's going to happen is we're just after it's done after we're done like getting this element right in this case what we're going to do is that if the current so we have a boolean answer is equal to top or down so if one of them is true then that's going to be our answer right if none of them is true then basically our answer is going to be false so in this case if we found that there is a path if answer is equal to false if there is no path then we're going to set the current element so visit visited we're going to mark the current element unvisited right and in this case if we visit if we have a situation where we have the answer is equal to true we found the path then we can do is we can just return true right in this case sorry not true sorry then what we're going to do at the end which is going to return answer right so now let's try to run the code okay so we should have a integer j cannot find this so 22 we have array so instead of array we should have letters my bad so it's going to be letters right in this case we have array somewhere but anyways so let's try to write the code another array 26 which is right here so it should be letters that current index and let's try with this result right here this example right here okay so let's try to submit okay so here you can see we have our success so basically this is how we solve this problem using that first search backtracking
|
Word Search
|
word-search
|
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
**Example 1:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED "
**Output:** true
**Example 2:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE "
**Output:** true
**Example 3:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB "
**Output:** false
**Constraints:**
* `m == board.length`
* `n = board[i].length`
* `1 <= m, n <= 6`
* `1 <= word.length <= 15`
* `board` and `word` consists of only lowercase and uppercase English letters.
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
| null |
Array,Backtracking,Matrix
|
Medium
|
212
|
259 |
hey what's up guys this is john here so uh today uh let's take a look at this very old or classic problem the number 259 three some smaller even though it's like very old problem but i think it's i find that's kind of interesting you know okay so you're given like an array of integers right and it could be a either negative zero or positive and it asks you to find that like the three distinct like numbers the basically which consists of triplets uh who's like the sum of those three numbers is smaller than the target and yeah that's the question right and the follow-up is like follow-up is like follow-up is like can you solve it in the o and square time so um so today we're going to focus on this one because if we don't care about the runtime here i mean we can simply use a brutal fourth way right basically just to have like uh a three nested for loops right to loop through all the number out three numbers and then with for each combinations we just compare and then we just increase okay that's it so i think the a better way we can do it a better way of doing this is that i mean we can utilize the uh the hash tables to store the previously uh two numbers results okay and for the for those for the two number pairs who has the same uh sums we can simply store all those the number into one key which will be increasing that the numbers the count for that two pairs i mean so that i mean we can because you know so that we can improve our runtime uh a little bit but i mean the first for that uh solution the worst case scenario is still uh o and cube but since we have like a range here right and we have a bunch of like uh random numbers here i mean it's very likely that i mean a few numbers can end up a few pairs can end up have having the same sum so which can help us reduce some of the runtime here and cool so let me try to implement that one first okay so sorry about my chinese input here so the first one is going to be the numbers right like i said you know and uh we're gonna have like a few you know like uh the sanity check like let's say for example if the uh for the basically if the n is smaller than three okay and then we simply return zero because there's no way to get a triplet in that case second i'm gonna have like uh basically gonna be two sums okay two sums dictionary and i'm gonna use the default dictionary like uh like int okay and then uh basically i'm gonna start as the uh from the third element okay because that's the first one that we might have we might get the uh the three triplets sorry we might get the three numbers which uh is that the triplets okay and then basically the two thumb dictionaries stores all the i mean other two pair sums uh we have seen so far okay and since we're starting from the third one let's add the first two to the two some dictionaries first okay so it's going to be numbs zero okay plus nums one okay equal plot and then plus one we increase it by one okay so basically the way i'm doing it for the current one the card number uh basically if the for any two sum okay for any two sum in the two sums okay if the two it's if the two plus nums plus card number okay it's smaller than the target okay and i just uh increase the answer i just uh accumulates increased answer by what by the answer plus whatever how many appearances how many counts we have for the current sum here okay which means let's say for the two sum let's say the current one is like the current num the current number is two here and let's say the target is like uh is five and let's say for the previously the two pairs right let's see for free two pairs we have a sum equals to one which count is equal to three okay that means uh it means that we have three pairs that uh whose sum is three that's why with those three pairs we can just simply uh consist you can simply form like three new triplets that's why we do a answer here okay so that's that and then later on we just need to uh basically update our two sums is the card number okay basically for all the numbers uh in range of uh of i okay uh two sums okay num i plus nums j okay plus one okay that's how i update the uh the two sounds because two sums because it's the current with a new number num i here we will have like this many new two pairs two some pairs okay here in the end we simply return the answer okay i think this should just work okay cool submit all right so it works okay i mean as you guys can see here right the time complexity for this one actually the worst case scenario is also it's still like two square i'm sorry still an n cube because you know for the outer loop with n here okay and here this part is n right but this part is also is as always and but for this part the worst case scenario is that like every time we're adding like a n new element into the uh into these two sums dictionary so the worst case scenarios will have like a n square here that's why the worst case scenario for this one is still an n cube but like i said since we will have like a most likely will have like many pairs whose who have the same sum values that's why this part i think it's between the n to the n square okay cool so that's the first approach okay it's a it's not a strict like n square solutions and let's take a look at a better solution which is a strictly n square okay so which is sorting you know every time when you guys see like anything any problem that asks you to find any triplets okay or any pairs triplets or anything that's like uh satisfy a condition right the first things pop out of your mind is always sorting okay and i think the easier version for this one is find us to some smaller okay basically find that the two sum like the pairs whose number is smaller than this one so for that one we always would we always uh we also do the sortings and basically for that one we do the sortings and then we just have a left and the right pointers and then basically if the sum for those numbers is greater than the target right and then we shrink the uh we showing that the target we start we should shrink the we shrink the right pointer to the left because we know we need a smaller number otherwise we move the left pointer to the right side okay because the number is they're already sorted so same idea for this one but the only difference is here now we have three numbers okay so with these three numbers we can still utilizing the same utilize the same concept but we just need to do a little bit extra work here so like i said uh let's do a sort let's sort this number first okay now we have assorted numbers and we have n here length equals to the uh nums here okay so and since i already told you guys how can we find a small a two some smaller numbers by utilizing the left and right pointers and actually we just need to uh i mean treat that one as a sub problem and instead we just need to have fixed one number first and then we just use that problem you use that solution to solve the uh the rest two to some smaller problems because that like two pointer is like oh and owen uh runtime right so basically this is what i mean here so we have a n here okay we have a range like n minus 2 here because that's going to be our starting point basically uh with the current number here with current number i here to the n to the end number here we want to see since the current number i is fixed okay and we just want to know like uh how many two pairs how many pairs that i mean how many pairs that between the current i here between this one and this one that satisfy the uh at the target right so how can we do that we just simply do uh you know since we already fixed this one here so the left will be what will be i plus one okay and the right is always the n minus one okay and let's do a pointer while left equals to right uh left smaller than right okay and now we have our three numbers here if the nums i plus nums left plus nums right okay it's smaller than to target okay uh okay then what do we have okay so i mean if the current one if the current on the left and the right uh satisfy the current condition what does it mean it means that i mean since remember the number is sorted now right so it means that from here from the left plus one to the right for all those kind of uh right elements they're all satisfying the they're all satisfied and they start there this condition here because currently the right one is the biggest one the biggest number is since the biggest number it's also satisfying this one so anything that's smaller than the current right is also like satisfying our conditions here so that we don't have to worry about anything between those okay then how many uh options between those right we have like right minors left so that's the that's how many pairs that uh between the left and the right uh will satisfy this condition okay then so after this one it means that okay we have uh count all the pairs like right starting with uh which i have which have like i and l with different uh right uh different uh right here right that's why we can simply move the left forward and we just want to check okay this one with that one can we try on a bigger number of the left to see if this one's still satisfying that and then we know okay if that's still satisfying the condition then we know from here to from the here to the end we also we were gonna have like a few more valid pairs here okay otherwise right if this condition doesn't meet and then it means that the number is too high it's too big so we need to find a smaller number so this by so how can we find a smaller number we just move the right to the left okay that's how we try to find a smaller number okay yeah and here in the end we simply return the answer here so this should just work yeah let's see yeah as you guys can see this is a much faster because we have a on here we have owen on the an outer loop and here it's simply like another o n here so that's why this solution is o n square yeah so it's pretty smart right by using like sortings plus you know plus like of two pointers to solve this problem because you know since like i think i'm repeating myself but basically just to recap right we're using like us we store these numbers first and then we fix the first number first we fix the first number and then we try to find like for every for the for each of the fixed number here we're trying to find a place a number right like a two pairs that satisfy the current conditions since the numbers they are sorted right if we find a left and plus right that is satisfying our conditions which means that everything uh like left plus like uh anything that from l plus one to right okay to right there they're gonna satisfy the conditions as well because the right one is the smallest it's the biggest one okay yeah so that's how we uh can skip all this all these things because we know they are already sorted and then we just move the left forward we try to find if we have another uh valid starting point okay and then we keep doing it right and if there's no this doesn't satisfy them we try to lower the right pointer so that we can have like a smaller number in that case cool i think that's it for this problem yeah thank you so much uh for watching the videos guys stay tuned like always thank you bye
|
3Sum Smaller
|
3sum-smaller
|
Given an array of `n` integers `nums` and an integer `target`, find the number of index triplets `i`, `j`, `k` with `0 <= i < j < k < n` that satisfy the condition `nums[i] + nums[j] + nums[k] < target`.
**Example 1:**
**Input:** nums = \[-2,0,1,3\], target = 2
**Output:** 2
**Explanation:** Because there are two triplets which sums are less than 2:
\[-2,0,1\]
\[-2,0,3\]
**Example 2:**
**Input:** nums = \[\], target = 0
**Output:** 0
**Example 3:**
**Input:** nums = \[0\], target = 0
**Output:** 0
**Constraints:**
* `n == nums.length`
* `0 <= n <= 3500`
* `-100 <= nums[i] <= 100`
* `-100 <= target <= 100`
| null |
Array,Two Pointers,Binary Search,Sorting
|
Medium
|
15,16,611,1083
|
144 |
hello everyone in this video we'll do lead code 144 binary tree pre-order lead code 144 binary tree pre-order lead code 144 binary tree pre-order traversal this is today's daily challenge so basically we're just given a binary tree and we need to do a pre-order traversal on this tree so what pre-order traversal on this tree so what pre-order traversal on this tree so what is a pre-order traversal it's basically is a pre-order traversal it's basically is a pre-order traversal it's basically we go from the root we select the root and then we take the left subtrees pre-order traversal and the right pre-order traversal and the right pre-order traversal and the right subtrees pre-order traversal so it's subtrees pre-order traversal so it's subtrees pre-order traversal so it's pre-order because the root goes first so pre-order because the root goes first so pre-order because the root goes first so in this case it will be like 1 and then there's no lab subtree so then it'll be the pre-order of this so it will be 2 the pre-order of this so it will be 2 the pre-order of this so it will be 2 followed by the left which will be three so it's just one two three so with that let's get started so basically we'll just use a recursive approach where every time we visit a node We'll add it to our list and we'll start with the root and then recursively we'll call pre-order recursively we'll call pre-order recursively we'll call pre-order traversal on the left and right subtrees so let's go ahead and create our list first so I've gone ahead and created the list we're going to end up returning this list at the end then we'll call our recursive pre-ordered traversal function pre-ordered traversal function pre-ordered traversal function that will take in root and their list now let's write this pre-order recursive now let's write this pre-order recursive now let's write this pre-order recursive function so here's the signature we'll take in the root and the result list and what we'll do is if the root is not null we'll add to a result and recursively do the traversal of its left and right subtrees so here we have it if our root is null meaning if we reach like a bottom subtree we just return because we don't need to add that to our list then we add the roots value to the list and then recursively we'll Traverse the left and the right subtrees so here we have it we're recursively traversing left and right and so this should do it let's try to run it oops we need to pass in our result list as well when we do the recursive calls let's try to run it again accepted let's submit perfect thanks so much for watching I'll see you in the next video cheers
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
78 |
Buddha Problem Hindi Recording Series Suggestion Or Their Discuss Problem Sabse To In This Problem Will Be Given There Need To Find Out All Subjects Which Can Be Made From Midnight Should You Know Problem Ka Suggestion Liquid 1 Hafte Element Se Z Subscribe Different Subject Agreement To Give The Number subscribe and number of elements in the to this sub scan v2 v3 hundred 40 that daily 900 that 2012 daily ne 1512 and we can have fifteen alone 2001 and practical option 12321 half improved 8th subject which they can make this add the walking police Discuss All Three States This Fabric Problem Vyas's World Record Call And Have Small Work On Okay Gyan Sunao Motu Patlu All Need To Divide Me To Record Inform Anybody Can Be Divided Problem Into Smaller Problem Okay Full HD Hai To That Year That Bihar Ke Vadh 2fa 1000 test hai na jis din hai right and not vik and divided into two parts mein divide plant hai aina-e-ghazal bhi now it is back to hai aina-e-ghazal bhi now it is back to hai aina-e-ghazal bhi now it is back to points on vik in the next two for withdrawal in the morning divide the question was walking to na Lagti inclusion list sunni hai aur sunao ucd.inch pumpset vihar phase with us the withdrawal of in this is right 113 to possibility of 25th insan sabe zor and these subjects will not light a whatever aap bhi to make to record for great journey to Record Call Decoration Love You Can't 10 Subject And You Don't 10 And Subsidy Torch Light So Let's See How Two Is So Most In English 2950 1000 2000 For Rest Of The Amazing Two That Press On Electrolyte Deep Yet Leave End 12th Part 9999 Able First Most More than 20 Lights Unknown Person Possibilities for I and 98100 A Torch Light and in Various Ways Skill Naresh and The Amazing Hoenge Welcome I Tujhse Mila Lift They Also You Will Have Two Possibilities I Love You Can Take Revenge of the United So if you don't believe in your intuitive but then 212 subscribe 2108 and listen or pet wealth and will there girls for the rest of the river but now they are Vikram se zameen soon is the world largest fresh water every subject 90 a this morning when its Opposite Subset And Will Return Back To Twelfth Patna Possibility Of Twelve Team With Me To Table No 21 2012 To Area Which Will Withdraw From The Black 06 A Heavy Drinkers Of British Are Sure To Present Only Ones Again Also Picture Opposite Quota Subscribe To 0 Subscribe To Person Lord Buddha Possibilities Pet's Spirit And Wait For The Possibility Of Twelfth No Possibility Of Death Against Evil Returns Back With Good 20 2012 0000000000 Ki And Fifth Class Date Of The Area Specific Wealth Against Verification I Will Contest All 29 Oct 11 2012 Less Juice of That First Come Only Kill Twenty-20 Twelfth Night End Kill Twenty-20 Twelfth Night End Kill Twenty-20 Twelfth Night End Exam Is Passed Tomorrow Morning Contrary to Claim Jet 2 End Wealth Torch Light OK 9 We Go Back and Will Take Responsibility They Don't Act Will Suggest Nothing in Return Holi 2019 19020 Hai To Viparit Vidmate Kaise MP Are Passed And These Softwares Ki 22nd Print Twenty Years Back In Sabse Ye Front Four Subscribe All Possibilities That They Will Return To The Possibility Of 10000 To 15000 Possibility To 28th Nov 19 2012 Subscribe 0 Ki And Twelfth And Sunao 's various forms to possibilities for safety 's various forms to possibilities for safety 's various forms to possibilities for safety norms and identity effect in the to take 1615 intersect with have to right and will gather arrest amaze 12th 112 that to magan photo and will have to possibilities light speed a van and vitto test to isi 12% Vijay Ko Mutworks Front test to isi 12% Vijay Ko Mutworks Front test to isi 12% Vijay Ko Mutworks Front Part Ko Mute Wealth And Will Pass Antivirus Because Now Everything You Know More Element 812 1512 Printout Inside You Parents And Possibility Will Return And Go To Minutes 12-12-2012 Virat Go To Minutes 12-12-2012 Virat Go To Minutes 12-12-2012 Virat Kohli Chhutti Na Sabse Hai So Vidmate Ke Ampere End Shiftiness printed a we go back and when we explorer window note 1000 subjects and behave in a difficult wealth software or game is possibilities table spoon ticket is so effective twelfth subject is 2012 only and vintage's so you submit blueprint visit world in the way both orders Subscribe Now Only With Abe A Ka Rate Song MP3 Software Also Printed So 308 Possibilities Vihar Terminal Solidification So What Will Discuss The Source Code So Here Court For Bihar Vector Of Vector Media And Today There Because In The In Bihar returning all subjects right and shifted to make over two years in which will add the most worn meeting a subsidy vector and Times of India subset and they setting currency 100 friends 100 sub calling sub function and they were watching this is the country and the The Return Of Is FD Martin Way Is Case What We Do Is Ribbon To Equal Subsidiary Hydride Can Effective Midnight Tonight And Elements Of United 100 Was That Air Idont It Reverse Elements In The Land Of Blood And I Will Give U That And Over Year Id Bilari To All Subject In The Graduation In Which Will Power And Strength And Will Power Temple And Uplift Vihar Edit Element Inner Temple Sudhir Gautam Kaun Hai Loot 300 Meter Problem Endoid Vitamin E Don't Please Comment And Dar Prominent Court Ne Case In The Discussion And Please like share and subscribe from the video thank you by
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
1,557 |
Hello everyone, welcome to my channel, I am going to do video number 26 of my graph playlist and before continuing, I am reminding you that if you have not seen my graph concept playlist, then you can watch it if you want to understand graph. In a very easy way ok it will be very easy once you go through the playlist once ok today's question is of medium level but it is actually very easy if you understand it thali ok if you understand it well then you understand the tuition This question is very easy ok late code number 1457 the name of the question is minimum number of words disease tu rich jo notes ok Google it and by looking at its input and output understand what the question is ok so look the question I have given you is a directed Recyclable graph will give you the input which has total N vertices and you have been given an agent named Hey, where the value in each index is given from i2i, like see the example here, what does it mean that zero. From one is a yes, okay till here it is clear, this is representative from direct from I, you, I find this set of vertices from which is notes in D graphical, so it is saying that zero can be reached, let's see, it is so that No, if I look from zero, then where can I reach? I have reached from zero to one. You have also reached one. Okay, I am not going to tell the story, so what is the other answer brother? I have given three and it has become zero. Now I have given three, I have seen how far can one pass with three it is being said that you will reach 4, with four you will reach 5 and if you see, we have made all the notes, right, zero and three. It was in our set, from there one and you will reach 425. We have done all the notes, there is a minimum of zero and three, so that they can be billed, you can do whatever D. The notes of the graph are fine, but now the point is Now it comes to how to solve this. Okay, so see, to understand this, no, I lay down the graph from here, okay, I lay down the graph from and from there, I understand. Okay, so look, forget all the words which just take these two. Right now, let's agree, let's just talk about this. Okay, let's just talk about this right now, because it's happening, forget the rest, what I have seen. What can we do with these two, tell me one thing, brother, if I tell you that there is one more in your answer. B is to be kept in both, it is okay, then you think for yourself whether this is right, what is the reason, why am I am having a problem with this, because look, why did you add B, brother, if you had written only this, then from A you would have reached B. If yes, then B is not necessary. Correct, if you are going to reach B from A, then just write this. Why is it necessary to write B? Then B has become redundant because you can reach B from A, so there is no need to write B. It is not necessary that we can reach the minimum number. Okay, so the point is that it can be reached from any note. So, what does this mean? Also, if why are you doing incoming ad on this, then reach to B. It is possible that there is some load from where the incoming would be taking it, hence we will not include B. Okay, so one point of mine, have we learned here that brother and yes on some mode which comes forward? What is that called? Remember, I teach topological sorting, that's why I am saying that. If you watch my graph concept playlist, you will learn many things about graphs and you will know that the ara that comes on a note has to be called in these degrees, okay? If we talk about these degrees, then what I am saying here is that no one will include these degrees on Note G. You must have seen this in my answer. Why am I repeating again that Science is on B here? If we can reach from A then why would I include B from these degrees, if A is there even on any note then it is ours, I will definitely not include it in my answer. Okay, it is clear till now, so brother, this is a very important point. I came to know that brother, if any person has these degrees, that is, if he has any degree, then I will not keep him in my answer sheet and I have told you here the reason why I will not keep him, come on, I have seen such a note. Now let's look at the same notes on G. There is no A on G but there is no example. Okay, that means this poor guy, if I don't include it in this set then it will be reachable because no one has reached it. If I don't include it in this set, then this poor guy will never get this note in my result because no one is coming forward on this, so no person will be able to get an on this, nor from any person, from any note, from any person. Also from vertex I will not be able to reach on this vertex and also on this vertex here because there is no incoming ahead, what does it mean that their in degree is zero, okay meaning what I have to note here is six that brother if in degree If there is zero, it is okay, these degrees, if there is zero, we will have to input them in our answer, even if it is clear, it is okay, we will have to add it behind it because poor people, we cannot reach these two even from the story that has reached now. Because these degrees are zero then both these points are valid but what is the meaning of this then what is the most important question that today if we give only 1° zero then my mine will be reduced. give only 1° zero then my mine will be reduced. Otherwise the question would have been A. Mother, let's see whether this will be possible or not. Okay, so look, let's try to understand it. What did I say that brother, I will definitely give credit to those with degree zero in my result. Even this is clear, but I am asking. Yes, our answer will be A, so let's see, like the example is fine, whose degree is not zero, okay, but we have to check that brother, can that also be in the answer, like mother is late, okay, so see, the input is not happening. Right, if no one has been talking about this further, then our answer will definitely be 'A'. then our answer will definitely be 'A'. then our answer will definitely be 'A'. Okay, this will definitely be true. Now you are asking me, brother, is there any other vertex which we can insert or any other vertex? What is it that you are thinking that you should put it, but take example C, okay let's check, then it means that this C is not degree zero, it is going on this, so now say brother, why can't it be done? What is it, tell me one thing, if this degree is not zero, then surely someone must have been ahead of him, then I will not add this C, I will go to the person from where he is getting this, or I will ask him to add you brother. If I don't have to do it then I will come to B. It is clear that I will not add this one because there is already an A ahead on C, so instead of adding C ahead, I will go to C from where A is ahead. I will go and ask whether you guys want to get Ed or not, otherwise come to P. Then I saw, okay, you have these degrees on B too, so what will I do, in between, I will see from where I am going to B, then after excluding B, those people I will include it because from there only A can be on B, otherwise I will leave B also, I came on A, okay, I came on Dal Dog, here, your head graph will become S because it has integers other than zero. Which children do you have whose integration is not zero? And if his integration is not there, then to whom will I go for an example, from where he is getting the fear? Just a little while ago, I told you that neither is this one nor this one. Brother of A and B, if you have given A and B in the answer, then I saw that it is good that only B can be written from A, so what is the need of B, brother, if you write only A, then B will not go like this, I am saying the same. I mean, if someone A is going to C, then I will not include C, from where A is coming, I will not go to P, then look, well, someone is going to B also, then why would I include B, where A is from? When I go to him, I will go here. I came to know that okay, one can go from A to B and one can go from B to C. Okay, it is clear till now, so this is the principle of it, so ultimately what do you need to know? Brother, ultimately whose individual is only that is your answer, thoughts will be done by doing it, you will be gone and what is one more brother, where can you go from three, 4, 2 and 5 because poor people, their degree is zero, they have access to it. Therefore, at least visit these two, we have included zero and three, these are the minimum vertices which we have to include, so our code has not become very simple, we just have to do what we have. We have given agency in the input, we have given 01, we have given zero, we have given 34, we have given 42 and 25, we have given it in the input, till now it is clear, now see what we have to do, that will be our answer, so how good. From zero to one, you are three, four, five, let's do it, we have zero to you, so you are also to the degree, okay, I have marked true, you are integral to five, see the same, my answer is, consider zero as three. I came to know the most important thing was what were these two points because you should know this point right and this is the part which I have explained, okay this is very important, only if you explain this then the interviewer will be impressed by you otherwise he will understand that by remembering you for sure. You have come to the solution, you do n't have to memorize it, try to understand it is right, let it be a simple code, then all we have to do is travel this edge and populate one degree, whatever value is there, that will be my answer. So let's do this code but it is so simple right so let's start it, what I said is that I have made the vector of boolean in degree, I am okay now what do we do with ours okay and this I know, we have to make the vector of and result and Only those with these degrees were getting zero i < degree but there were no further incidents, they got i broke but no one was coming ahead, so include them, very simple solution to the result.
|
Minimum Number of Vertices to Reach All Nodes
|
check-if-a-string-contains-all-binary-codes-of-size-k
|
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct.
|
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
|
Hash Table,String,Bit Manipulation,Rolling Hash,Hash Function
|
Medium
| null |
3 |
uh hey everybody this is larry this is day seven of the january leeco dairy challenge uh yeah first week ending let me know how it goes hit the like button to subscribe and draw me discord um i usually attempt to solve and explain these problems lives so um let me know what you think about the format and if it's too slow for you feel free to fast forward i tend to go over my thought process and that's what i like to do okay today's problem is longest substring without repeating characters given the string now let's find the length of the okay um yeah so this is going to be a sliding window thing um which is in a way a sort of greedy and trying to figure out um an invariant that is true and the reason why this is that um uh given any substring with the without uh yeah any substring without repeating character you could greedily add one to the left or to the right if it does not make um yeah it does not repeat any characters right that's basically the idea and then now we just have to kind of have two pointers two fingers and go okay let's say now we want to add in this character to the right um what happens to the things on the left um well now you have to remove until you know it's good to add this character um so that's the idea uh and many variation of this problem is on lead code and different competitions so definitely practice this and even up solving it and doing in linear time i didn't even look at the length but you know because i know that's going to be linear time it should be okay um yeah and when i say about invariant um we'll go over the loop and variance as well so let's kind of get started on implementation um cool so what i like to how i like to write and there's a few other ways to write it just i like to set left for zero to zero sometimes i use a while loop sometimes i use a for loop it just depends on what makes sense and how the pointers get moved in this case we want to move the right point every time and then just make sure that the left pointer um holds in variant where nothing between the bounds inclusive um contains uh repeatable characters right so now let's say you know um let's have just um inset maybe i don't know that's a good name for it but it's just to keep track of characters that are in the set so then now it becomes if or wow uh as the right is in inset that means that what does this mean right this means that uh the cur we want to add this character but it already exists in the balance that we keep track of um so now we have to kind of move it um we have to make it so that it doesn't um and that's how we get the longest um longest substring that ends at this current character of the right bound so that's kind of the way that i would think about it um and that you know uh let's see inset we move s dot oops s sub left increment by one so and in this case there's also a few invariants to it which is that uh you know normally otherwise um you may see errors right like for example this removal well we know that the precondition is that because left is going to be on the left side of the right makes sense um we should this can only be true if we added it before so this will never give us an error about not found and in this case left we incremented until um until left is less than right um like you know maybe you can write something like that but it's not necessary because of the invariant that um once left is equal to right then s of right should never be an inset right so that's why you know the way that we write it um yeah and then at the very end we add a sub right that's fine and we want to keep track of what i call the best that which is the longest and in that case we just set it to the max of the best or if the current length which is right minus left um plus one because there's inclusive bounds to be the current length and this is the longest length of a substring that satisfy non-repeating characters non-repeating characters non-repeating characters that ends um that ends at the current character right uh at the right bound and that's pretty much it really this is a very fundamental um very basic relatively um uh two pointers algorithm so definitely get to familiar with this one because it only gets harder to be frank uh with different variations and as long as you're able to kind of figure out in varian and the loops then they should be uh pretty you know it gets harder but you know you can build on what we have here right um so yeah and there are a couple of key things to this one is knowing that this is a set um because then now this is an o of one operation and this is a one operation as you can imagine that you've just partnered naively for example list then you could get n squared because you're doing a search every time right and that's too slow um and this time you know speaking of that complexity is only going to be linear because for every item that's an s we add it once and most ones and we remove it at most once so that means that we only add and remove once per element which means that this is all one number of element or all of one time per element so it's going to be o n um number of total elements or time for total right in terms of space of course we do keep track of a set so it's going to be linear space and the worst time um cool uh that's all i have for this problem as you can see we got it accepted um yeah again this is relatively basic um and i don't mean that to say that it you know you should feel not good for not getting it but i just mean like no you're you don't feel like you're able to solve this very comfortably um definitely practice it because it comes up all the time um in various different ways so yeah and the condition here is relatively simple we just don't want anything repeating so we use the set but definitely the conditions gets harder and trickier to kind of make sure that um we're holding it right but still the idea would still be the same um cool that's all i have for this problem let me know what you think i'll see you tomorrow and stay safe bye
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
141 |
Hello everyone Chirag this side and in today's video we will do our lead code problem number 141 which is link list cycle is a very easy question let's see what it says given head d head of English determine if d link list has a cycle in it It is said that we will be given a head of the penis lace. What do we have to do in advance to tell whether there is a cycle in it or not, that is, whether there is a loop or not? For example, this is our link list, you are three four and in this we will be given a head, what is a head? Head is our first load. This is our English. So we will be given head and we have to tell whether there is any cycle or any loop in it. What is a loop? Loop is when our oil is not pointed at the tap and is not flowing in any first place. It points to the note of, in English we call it cycle or loop, like our four in this, it is our last load, if it were oil, but it is pointing to tu, which has been loaded before, hence it has cycle. We will return true if any English is pointing to null i.e. there is pointing to null i.e. there is pointing to null i.e. there is no cycle in it then we will return false in it like they have also given an example. Our last mode in this link list is that of null. The place is pointing back to 2, it is pointing to the old note, so there is a cycle in it, so we will turn the rule, we can hit their input as Indore because we will be given only head and we have to solve these questions from that, so let's go. Now if we look at its approach, we will basically be given the head of English and we have to find out whether there is a cycle in this linked list, otherwise we will do it with 2.2 approach. We will create two reference we will do it with 2.2 approach. We will create two reference we will do it with 2.2 approach. We will create two reference variables, the first one will be made slow and the second one will be made fast slow. We will run this for the van step and we will run the fast for two steps. Initially we will stitch both of them from the head, here we will keep our slow and here we will keep our fast, then what will happen in the first step, move the slow from here. Here it will come and our fast result will move forward then a point will come where both our slow and fast are pointing to the same note i.e. both become equal, i.e. both become equal, i.e. both become equal, if such a point comes then we can say that in our English If there is a bicycle then this is our condition. If slow = fast then you can our condition. If slow = fast then you can our condition. If slow = fast then you can return. We can also understand this in another way. For example, if there are two persons and one is running at 2X speed on a track, then if both those persons meet. So we can say that our track was circular, but if those two people who were running never met, it means that our track was not circular and there was no bicycle in it, then if a case comes like van tu three. And if our last note is pointing to the tap, then in this case our slow and fast pointer will never meet, slow extra will move ahead first and fast, our friend you will move ahead, then slow will move one step ahead and fast. So our link will go out of the list, then slower fast will never be found. Okay, so keeping this approach in mind, we do our code. First of all, we make our head equal to null i.e. there is no note in it and if Our i.e. there is no note in it and if Our i.e. there is no note in it and if Our head is national, that is, there is only one note in it, so we will return false. After this, what we did was that we created two reference variables, one slow and one fast, so let's make slow which we will point to the head and By the way, we will make fast which we will make head point, after this we will create a value, first write the content inside it, then let's see what is the condition, what will come inside, we have to move our slow extra because I know that when slow If we get fast then it means our cycle in English, so we will go out of the form and return false i.e. we did not get any cycle, so i.e. we did not get any cycle, so i.e. we did not get any cycle, so now let us see what condition we will put in the wild loop. We know which is our fast point. If he completes the link list quickly, then according to the condition of Wiley, he will be fast, so we will put our fast dot net is not equal to n. Along with this, we will put another one which is our fast dot next, this is also equal to null. This condition should not happen. We have put a cute condition that in this case, which is our fast point, it has reached the last note of our penis, then what will happen to it will be next to the next i.e. it will be next to the our penis, then what will happen to it will be next to the next i.e. it will be next to the our penis, then what will happen to it will be next to the next i.e. it will be next to the null point, which is the null point. If it gives an exception, then avoid it. Now let's run it once and see that it is run. Let's see by submitting it once for all the three cases. And this time also it is done, so its time complexity will be there, why is it off? Because if we travel each note one by one, it will become open and what will be the space we will call city, it will be off van because we have not created any extra data structure nor any extra space in it, so we do it with this. We end the video and hope that you have understood these questions. If you have any doubt regarding these then please ask in the comment section and if you liked the video then do like it. Now we will meet in our next video with a new question. Till then goodbye
|
Linked List Cycle
|
linked-list-cycle
|
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
142,202
|
1,577 |
hey what's up guys chung here again so today let's take a look at one of the uh a weekly contest problem uh number 1577 a number of ways where square of number is equal to product of two numbers i think it's a pretty good problem so basically you're given like a two arrays right array a nums one and a red number two and it asks you to find all the other triplets basically all the other triplets type one and the type two okay so for type one basically what is doing here is you pick one number from nums one and then you pick two numbers from nums two so see the number is the index is different where the uh the square of the number from number times one equals to the product of those two numbers from nums two the type two is just a in the opposite way basically from type two you pick one number from num2 and then uh do this to the square and you're looking for two a pair from nums one to find the equal the number where the product the same as the square yeah that's why so for the numbers one for the example one here right there's only one triplet basically a peak four from numbers one and then you pick uh two and eight from nums two okay and example two you have nine options the reason being is because you can pick one and then you have a one two three four uh basically all the combinations they're all equal right and if there's nothing if there's no what no way no such triplets you just simply return zero okay and the length right so the length is like the uh the 1000 okay the length of the two is one thousand so which means you have you can use you should use like um n square right if you use an uh n cube that will be two that would be too much okay so i mean a through the fourth way is what basically brutal fourth wave will be uh you simply pick uh one uh pick each number in numbers one okay and then from nums two right you just loop through all the uh you look through all the combinations right the all the pairs from numbs two which will be also like unsquared right and then you just find okay you've if i've ever find like a triplet right and then i increase the answer by one okay so basically you loop through all numbers and then you do a uh a nested for loop to find the pairs in number two and then you do it reversely and then you do the same thing you pick one number from numbs two and then you find all the pairs in nums one okay so that's going to be uh what so that time complexity is going to be uh to loop through each number in number one it's going to be n right to find all the pairs right for uh in num 2 is going to be a n square so in total it's going to be a n cube right that's going to be too much right so we have to find a better way better so we have to find a better way of doing this okay so a better way a improved algorithm will be uh we probably we can pre-process all the we can pre-process all the we can pre-process all the other results right since we can pre-process each of the numbers here pre-process each of the numbers here pre-process each of the numbers here nums right here we can find all the pairs right near the balance and since we have the pair we can get the product of those pairs right and then we can simply store the count for each pair let's say for example let's say we have a so from num from number two here let's say we have a count so basically the key in the dictionary will be the product and the value will be the number of pairs that have the same products so basically let's say if the product is like it's four the products uh is eight i said eight has like the value is like three counts okay so this means that in number two uh we have three pairs that have the products equals to eight okay you okay see so after we have built this like dictionary or hash map now when we have when we look through the num1 here we can simply use this number the square the net the square of the number and then trying to look for the counts right the counts from the nums to uh hash table then we can simply add these counts to our final answer right so in that way actually we reduce since we preprocess all the other pairs now it's going to be n square plus n right which will be the n square time complexity that will work cool so i think we can start coding here all right so like i said we need the answer here right and then uh n1 equals to uh nums one and n two equals to length nums two okay uh what else uh nums1 products okay uh default ticked int and nums2 product also default right so and now we need to pre-process those now we need to pre-process those now we need to pre-process those products basically where i'm going to have a loop here and one minus one okay this is how we uh loop through all the uh the pairs right since we uh we need another like a place for the next number that's why we stop at n one minus two okay for j in range uh i plus one and to l one okay and then we have nums one dot product okay the key will be what the key will be uh nums i times nums j right and the value will just basically increase okay so and same thing for the uh for the other array here basically n2 and 2 yeah okay so now we have the products for those numbers now we simply need to loop through the numbers right on each of the array here okay and then we have a target right the target is what nums num1 square right and then to answer plus we're going look going to look for the target from the nums to product dictionary okay target if there's if it's not there it's fine right because uh we have like a default dig equals to uh integer right we already set the default value here so even if the target is not in here this one will return us a zero okay same thing for the num two nums two but in this case we'll be looking for the target in uh in nums one product hash table okay yep and in the end we simply return the answer cool so yeah this should work let's try to run the code here oh sorry in oh one two okay all right cool so submit cool so accept it all right yeah so it's pretty uh pretty straightforward like uh what can you call this like a counting or like hash table problem right basically uh we just a little trick here we just need to pre-process trick here we just need to pre-process trick here we just need to pre-process pre-process all the products right and pre-process all the products right and pre-process all the products right and then store those products into a hash table with the key equals to product and the value is the number of the pairs for that product on each in each of the arrays and then later on we can simply use the preprocess results and then so that we can reduce our time complexity right from n cubed to n square uh yeah i think that's pretty much it is for this problem yeah thank you so much for watching the videos guys stay tuned see you guys soon bye
|
Number of Ways Where Square of Number Is Equal to Product of Two Numbers
|
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
|
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105`
|
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ?
|
Math,Dynamic Programming,Backtracking,Combinatorics,Probability and Statistics
|
Hard
| null |
502 |
hi everyone in this video we're gonna solve a new problem the problem name is IPO and the problem number is 502 so first of all we're going to clearly understand what this problem says after that we're going to move to the logic part and after that we're going to implement our logic in C plus by Java and Python programming language so now guys let's see what this problem says supposedly it could be start it's IPO soon in order to sell a good price of its share to venture capital netcode would like to work on sub project to increase its capital before the IPO all right since it has a limited resources it can only finish at most a distinct project before the IPO so guys this is a restriction of a project so lead code can only finish atmosphere project before the IPO it could design help leadco design the best way it's to maximize its capital after finishing at most K distinct project now guys our tax is to maximize the capital such that we can finish at Max Key project right before the ipu your given end project where I project has a pure profit profits of I and a minimum capital of I is needed to start it now guys in example when you can see that we are given two array profit shared Capital array and the first project I need a capital 0 to start and once we completed first project we are going to get the one profit right and similarly for second project we need a minimum Capital One to start and once we complete the second project we are collected anything but two profit right all right initially you have W Capital so we are again we're going with the w Captain easily when you finish a project you will obtain its pure profit and the profit will add it to your total Capital fine see you guys first if we completed the first project then we are going to get one profit right so this one profit is going to add in my develop once we completed this project right all right now guys pick a list at most K distinct project from a given project to maximize your final capital and return the final maximize Capital so now guys we have to pick at Max Key project right as liquid can only complete at Max K project now guys we have to fix us that we can get a maximum capital so this was problem I hope you understood this if you still have any kind of drop don't worry we are going to understand this problem with this example one now so I'm going to take example one here we have a profit is nothing but one two and three and capital is nothing but 0 1 and 1 right and we can complete we have a limit of two project right we can complete at Max 2 project and there is W which is initial Capital that is zero right so now guys we have a initial Capital that is zero that means I can only start those project which has a minimum capital or we can say which has kept as 0 or less than zero right so here guys we have only one project right now that has a zero Capital so I can start this project and the profit I am going to get one so I'm going to add in my w right so now guys my w is nothing but 0 plus 1 that I can say is nothing but one round now guys and but my cable decrement because I have done one project so now my K is going to be nothing good so now guys I can see that I have Capital One so I can only start those projects which has Capital One or less than zero as this has already been taken so this is not a part of project now so we will have free to project and I can take this one as well or this one as well because both has Capital One right so now guys tell me which project should I take this one or should I take this one you can see which has maximum profit this one has a maxi profitage so I'm gonna take this one and now my capital is gonna be nothing but 2 plus 1 plus 3 that is nothing but 4 right so my final capital is four and my K is nothing but 0 now right so I have taken all the project now my K is 0 so I am going to return one four right you can see in the output as well I have nothing but four now guys I hope this match is clear to you so I hope now you understood the problem now let's move to the logic part how we can solve this particular problem so in logic guys what we can do think about this so first of all if you know that we need to do a sort of capitals right why we are sorting a capital see guys if we sold then minimum approach that which need a minimum Capital will come first right as we given W so I can take at Max Pro project because I know that the minimum we can say the capital required for a project is going to be at the first so if I sort the first example if I take so there is nothing sorting these are already sorted so let's take another example I'm going to take one two and three and zero one to write so it is let's say in initi note in sorting order then if I say this then you can see that we have to Traverse this then we are going to say zero part then we are going to take it then we are going to come back from initial position then it gonna take big of n square right but if we sort it then this will gonna come like this 0 will come first then one will come first then two will come first but remember guys whenever you are sorting it this project also gonna be changed right because this project is defining the same index if we uh in example when you can see that if 0 index has zero value then respective project profits is going to be one if you sorted this one Capital then you will lose the order for profit right you're gonna add the profit for any particular project whose don't have that particular capital I hope now this is clearly that first of all we are going to sorting the capital once we sort the capital then also we have an error whatever we are going to have let me tell you so let's say k is nothing but one and you have an array let's say you see nothing but uh I am going to take a one let's say this is two this is four this is six right and this also Capital this is profit and this is capital nothing but one two and three and initial Capital you have nothing but three so now guys tell me which project you want to be you have sorted right so you can see capital in sorted router it is so terrible so you're gonna take you have one project so you're gonna take the first one you can see this is less than W right or equal to W so I'm going to take this project and you will say my profit total is 2 so you're gonna add 2 into this so it will become five and you will say that my I have taken the one project now I don't need to take any more problem but wait you can also take this one two color one as well right so you can ask it this one took a project as well and it has a profit nothing but six so you're gonna add six into your W and you can see I have maximum profit nine and I took this project because this also is less than or equal to w so now guys how would you come to that which project should I take even it is in sorted router so guys for that I can use a practical right so what I can say until and unless I don't have uh I have a value which is a capital value is less than W I can put in my priority so in particular I can see that one is less than double so okay I put in the two in plating by two because profit is going to taken right so now I can see these two values actually less than W so I'm going to take 4 as well in my period now I will move ahead 3 is less than WS it is less than or equal to W so I can say I'm gonna put six hours into F150 right and if there were more values and let's take some more values so I'm going to take little bit so I can say there is a 10 but it has a course nothing but 5 right and here is also 2 which has cos nothing 1 that's a 7. so now guys you can see that if there is more value but still it will not going to taken why because you know that 5 is not less than W so but still we have nothing but 246 in my Q right so the maximum value I'm going to use the maximum heat that means Max practicum so it's going to take me the it's going to give me the max value that nothing but 6. so I can say I have taken I need a one project so I take nothing but one we can say case I decrement where K is equal to Y minus 1 and I took the maximum value and add it in my w at 9. and let's say if there is a k is 2 if I need to take a two value then you can see that my case decremented y1 so now I will have one value because I have taken up approach 36 but now my w is 9. so I'm going to start from ahead because I have taken already all this element in Q so I'm going to start from here and I'm going to say now keep checking how many projects are there which are less than 9 right how many projects are there or we can see project which has a capital less than I so now you guys can see that nothing but 5 is as well as the 9 so I'm gonna I have taken 6 so I'm gonna put 10 the maximum profit into my so 9 plus 10 is nothing but 90. and K will look one two zero now it will decremented by one so it will become zero now guys you can see that biotic with the have with the using of practicum I could able to take a maximally 90 right I have first of all I need to sort it then I need to use a fretogue and how I am going to do it I am going to keep checking when uh until and unless my capital is less than W keep pushing in my practicing and once we are completed this travel so it means once I go to Value which is greater than or equal to W then greater than W then you are going to break it and you are going to take a max value from your practicum and now you are going to decrementally as okay and you are going to update also your capital I have this much Capital we are going to say first step is nothing but sorting second step is nothing but we can say use a practical right a third step is nothing but keep adding uh keep decrementing your key adding your max volume to W right so that is nothing but the logic part I hope now you understood this now guys let's move to the implementation part and let's see how we can implement this in Python C plus square and Java programming language right so first of all I'm going to do this with python so I'm going to say first of all but we only we need to find a length so I'm going to say length is nothing but length of profits and now guys I know that I have already also told you that profit and capitals are related to each other rights if zero index of profit is uh we can see the first we can say first project is nothing but having a profit zero index and capital which is at 0 Index right let me add Capital this is so I can't change it right so first what I need to do I need to make a 2d array which is going to take profit as well as capital inside of it right so I'm going to say nothing but my array is going to be list I can say G related zip and here I'm going to say profiles profits and capitals right once I done this thing I have a normal capital and profit inside my 2D array right now I can sort it I can say error.sort e is equal to Lambda in increasing mode right so I can see Lambda x of 1 so X of 1 is management Capital value so it's going to sort on the basis of capital value in increasing water once we sort it we are going to use our pride degree as well right so I can say practically is going to be maxi fine now guys I am going to say while my key is greater than zero I can say while K is greater than zero you keep taking the values from your array right so now what I can do say I can say I have to Define one more variable that is nothing but keep track of how many values we have already pushed in our queue right so it is going to be index 0 initially we haven't pushed any value so we are standing at zero index so I can say while index is greater than sorry it should be less than n while it is less than n and I can say my array of idx of 1 or we can say one as capital so it is it should be less than o w right I told you that until then unless my capital is less than W you have to keep pushing your practical rate so I can see you have to just put my array of index and you have to push the profit and inside python we don't have a Max effect we have only mean here so what I can say I can multiply it by one so I can say this right so once we push it into a priority I have to increment my index as well fine so now guys when we come out from this Loop we are going to say if I don't have anything if no there is no mean here if there is no mean here so you can see return W because there is no element which has a value less than or equal to W in my array right so if it is not the case then return W but if it is the case then what you have to do you have to pop the max element right so I can say the value is going to be Pope so I can say my w is going to be plus equal to minus 1 because I have pushed my data in inside my hip queue by multiplying minus one so I'm multiplying it with minus 1 so that I can get my original value right after that I can say hit Q so let me write Heap q and hippo and here I can pass my mini right and once I done this I popped up topmost value which is maximum value and added also in my w we can see your capital and after that I can say k minus equal that means I have taken one value and after that I can return my w so that was the problem now let's try to run this code and see whether we are getting a right output or not if we are having an error let's see that so you can see that both the test case are passed so now let's try to submit this code and also you can see that is successfully submitted right so that was the problem I hope you understood this now let's move to the another programming language that is nothing but let's see C plus right so now guys in C plus what uh what we are going to do so first of all we're going to find a length so that is nothing but we can say profits so let me add profits and the profit stored size array so this is going to give us a length now I'm going to create an array so I'm going to say vector this is going to be pair of incoming array and initially it has nothing so I'm going to Traverse over my profit since n 0 less than n let me write here 9 and I plus I'm going to say array dot push where and here what I can do I can say uh profits first of all I'm going to put a capital select net capitals and capital of I comma let me write a profit of highlights so once we have done this we have created a 2d array where we have a first index capital and second index Network profit right so once we are done with this we are going to sort it so we can say uh sort array dot begin so let me begin and here a to 10 right so this is going to sort my 2D array right so once we are done with this we are going to Traverse first of all let me Define a practical q and here this is going to be a data type in and this is the name I'm going to give this network people right so now I'm going to Define also index so let me Define index which is going to be nothing but 0 we are pointing to First Index right so we will say while my K is greater than zero keep moving right so you have to take our project right so before that we are going to push into our um as well so we are going to say while index is less than n we can see uh that error of idx of 0 is less than equal to W here we are using a arrow 5x of 0 because I have pushed initially Capital after that profit right so I'm going to check with the capital until it unless my capital is less than W you have to keep incrementing it uh idx as well and also you have to push that particular data into your practic unit so we can say PQ don't push error of idx1 that means the profit you have to post in here practical once we are done with this we are going to check it if writing is empty PQ dot empty then what we can do we can say that if it is empty then you can return the blue right so there is no more element which have less than or equal to uh w i so now guys once we are done with this if there is no at least one element then what we can do we can say guys uh take out the topmost element the greater element right so I can say W plus equal to the PQ Dot two right so once this is done we are going to say all right now once we are done with this also we are going to say k minus 1 we have taken the one project and after this while loop we are going to return WS right so now let's try to run this code so I got an error it says that while error of idex is zero so it's say that what kind of an allocation error all right so we have done something wrong so guys let me find out all right so we can't use this zero because this is a pair right so we can use the first and we can use a second right because you we are using a pair now pair we can't use induction right so now try to submit this code first of all you can see that all the disks are passed now let's try to submit this code and you guys need to add this one also submitted right now let's move to the last programming language that is nothing but Java right so let me take a Java and here first of all we are going to find a size so we can say in 10 is nothing but profit stored 10th right so this is going to give me a size total size now guys we are going to Define uh array right so we can say my error is going to be nothing but let's say enter I can see into my AR is going to be new in the lens once we are done with this we are going to Traverse over this Orient i 0 I less than n i plus we're going to say air out of I is going to be I of 0 is going to be Capital so I can say capital and error of I of 1 is going to be nothing but we can say profits right and profits of I is going to be this and capitals of I is going to be this so when we are done with this we are going to sort it right so we are going to say area arrays dot so we can say uh we can pass this particular thing ARR and we can see as a comparator here we can say this is going to be a minus V right once we are done with this let me first of all see without this because I can I think that it's gonna sort by default kept by Capital only right so now once we are done with this we are going to say entire day c0 and we are going to define a priority as well so I can say Q is going to be the name let's say p q right TQ right T Q fine and this practical is going to be of another data type that is nothing but a comma B let me Define my own comparator and here I can see we have to B minus a because I want it in a maxi order right by default is going to take mean order right so once we are done with this we are going to use a while loop while K is greater than 0 that means we have still to do some project and we are going to say while my idx is greater than is less than n and we can see error of idx of 0 is less than or equal to W then you can take that particular value inside of your practical right so we can say p q dot add this particular value so we can say we could dot at error of idx of 1 and you can increment your idx after that if there is no data inside of our practic use periodic is to uh PQ dot is empty so we can say you can return right so if it is empty then you can return develop but if it is that if there is at least single data then we are going to pop it right so we can say w is going to be plus equal to foreign so this was the I can say the code for Java let's try to run this code I guess it should work because I haven't used a Constructor here so you can see that it's giving an error okay so spelling mistake capital now let's say to run this code there's one more error that is nothing but we need to find a comparator here right so we can see comparative a comma B that is going to be nothing but a minus V all right so now let's send this code okay it's all right I have to do let me say a comma B is nothing but this so it says that binary operator okay so what I can do I can say is Go error Roots error let's see let me Define here one other thing that is nothing but a if a is smaller than b then fine well let's say it is a 2d array so I can say a of 0 minus P of 0 right so this is going to work right now let's see I hope it should work you can see that both the test case are passed right now let's try to submit this code and it also submitted I believe you guys you understood this problem if you have still any kind of doubt you can ask in the comment section I'm always there to help you and guys I believe you understood this problem you know why we use a practical why we sort a capital array all right so if you learn something new in this video don't forget to hit the like button and subscribe my channel meet you in the next video
|
IPO
|
ipo
|
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects.
You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it.
Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_.
The answer is guaranteed to fit in a 32-bit signed integer.
**Example 1:**
**Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\]
**Output:** 4
**Explanation:** Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
**Example 2:**
**Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\]
**Output:** 6
**Constraints:**
* `1 <= k <= 105`
* `0 <= w <= 109`
* `n == profits.length`
* `n == capital.length`
* `1 <= n <= 105`
* `0 <= profits[i] <= 104`
* `0 <= capital[i] <= 109`
| null |
Array,Greedy,Sorting,Heap (Priority Queue)
|
Hard
| null |
1,926 |
hello everyone let's serve today's lead code problem nearest exit from entrance in maze you are given an M by n Matrix maze with empty cells and worth the red one you are here at entrance point you can move one set up left down and right in the Border you can move along the empty stairs not worse your goal is to find the nearest exit from the entrance and exit is an empty cell and at the border of the maze you have to return the number of steps in the shortest path to the nearest exit count one if we have maze like this then there's no such path so we return -1 -1 -1 let me show you an example blue ones are worse and the black ones are empty cells and you are here if we use a q data structure then we can solve this problem easily you are here 0 comma two so we push the entrance point to the queue with step count to zero and Mark as it over and we pop it you can move one step downside only except out of orders and two words so you push the point one comma two with step count one to the Q and Mark it as a word and we pop this you can move to the left and right side because this is a word so we can move and we can't move to the visited War so you push the point on command one and one comma three with Stepside step count two and mark them as a word and then we pop this we can move left side only so you push the point one comma zero with step count three and Mark it as a word and we pop this finally you found exit now because it was empty cell and it is on the borderline so congratulations it has two steps count so the output is 2. okay let's cut it we Define a q variable using DQ and we add the initial information and trans row index and column index and initial steps we've moved so far it's zero the empty cell is uh DOT sign but a word cell is plus sign so we Mark the entrance is plus sine and for convenience we predefined directions the raft one is for a row and the right one is for column so one step move to the upside this one is downside and this one is left side and this one is right side and we're gonna do BFS search using Q during the queue has items non-empty queue means we can't move non-empty queue means we can't move non-empty queue means we can't move anymore in this case we return -1 first we pop a cell from the queue and move to it if he stands at the first row or the last row or the first column or the last column we return steps how many steps we've moved so far except the case we are on the entrance cell we are going to find the cell to move in the four directions if our new candidate two movies in the Maze border and it is an empty cell we opened it to the queue new row and the new column and the step count plus one to visit next time the last but not least we must change the cell to war using plus character to never visit a cell twice if not we can get time limit exit okay we made it if we have M number of rows and number of columns then these Solutions time complexity is Big O of M by n and we use the Q for PFS its base complexity is Big O of M plus n I hope you enjoyed this video and it was helpful and I'll see you soon bye
|
Nearest Exit from Entrance in Maze
|
products-price-for-each-store
|
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell.
| null |
Database
|
Easy
|
1948
|
1,431 |
Work in this field Ajay Ko Ki A [ Ki A [ Ki A Hello Everyone Welcome to New Video Hindi Video Player Going to Discuss Any Problem He Problem Solved Video Friends' Video Friends' Video Friends' Root to the Problem Statement's Problem to Dates of Reddy Festival Number Aaf mid-day ne under-19 sir its candidates in waiting ne under-19 sir its candidates in waiting ne under-19 sir its candidates in waiting number of extra candidates you have written bullion are result 10th result aap isse must subscribe to hai aur cords advice ek kaam se problem hai kya hai humse problem hai it hai problem statement What is it saying to us, apart from this, there are multiple number of candidates and that is always the problem, what has to be done that we got this pimples acne pimples named 3515 and for that, we have subscribe problem if we appoint subscribe this subscribe Subscribe toe is next will have one and you have if we see subscribe its pipe and appointed the subscribe button means waking up for school now we will see that there is for war and subscribe that in the society we have one here and its Pass which number of candidates subscribe yes all this subscribe for school you have to subscribe here if subscribe is the result of turn then if we see the output of first class then what is it True False So let's see temple at what is it that this is our output through all true for shruti our now one more example appointed 2121 example subscribe and subscribe if subscribe village here the sum of call maintained it subscribe recognize were after guru all other call rate Our example is this look, by cutting this point, the appointed solution is a combination of broad and reach. For us, first of all, we will run equal for every child, which is Yudhishthir, where will he get it from? Subscribe, we will check here our number. Of candidates a which candidate comes plus which is our extra can extra if this grade is daily if this planet is our exam then what will we print then we will put it above here and if it is not so then what will we do means what do we Let's do it here if it's appointed time if it goes that if it's appointed soon then we will add here our form appointed like young will make this and after that we will beat this our if we here we Here we subscribe to the time that the time complexity will become ours. Soak off the inquiry because we have to run the loop twice. That press conference will go to us because the youth returns. Ravan Meghnad, we will make the name according to the appointment, but this is ours. Before that, for this, first of all we have to make happened in this village Next what we have to do is if we want to make it from this then what will we do Our list is made according to the equal two rules Now what we have to do is one within this we We will create this for loop, we will run it from here to here, we will bring it to 10 K eye lashes ban which will be the length of the candidates, inside this we will have to run another one inside this, from where will we run Equal Ajay 6060, now what do we have to do, now first of all we have to do this. Inside the group, we will press this means that whatever is ours means here we have to debit that now inside this if our in any case if any of our candidates a 110 dad I add plus which extra candidates can extend in this Will present if it gets laced with what does it get laced does it dry our glue Candidates and Candidates figure from Reddy So what we will do at this point moment is our test here we will call it and this We will do one right here, okay and like our flop will end up with this one, the inside one like our follow up will end up like this one, we will put whatever brilliant you have made in our my list, if our test is through. So if we put it, then we will put appointed, I have to put it, we will put calls in it, otherwise if it is from point, then we will put it, before that we had given its name, then we would have created the answer. Suppose, then what will we have to do, answer daughter advance raw, we What to do if this is our entry, set us, otherwise what should we do, tie us here, do it, okay, alarm in, like this border follow of ours will end, now what will we do inside this, we will make our return inside this, whatever we had created which is The accused are ARU, they should be accepted for the test, they submit and see their result, now this run is happening and this is our successful run, then if we see that it was faster than fifty percent of the people and it seems that it is Time subscribe now let's update it and now we will try to bring our solution in it so do it here subscribe village elements are done subscribe thank you and after pointing this maximum what will we do with the village and loot Once we read it, we can reach our solution, so if I follow you, we will be the first to get ours in 19. If we see this from here, come here, maximum limit, subscribe, now I will give it to the school, subscribe to our channel and Subscribe top whatever end express number to be off is more than two or tu then there we will see that if we call the daily passengers appointed for us here 100 here first of all we will do it in this way if we If you want to print it at some position somewhere, then this means number, our meaning, if we subscribe for that the rest of the cigarette is daily I will take the thing to confirm our that if see if this is 503 and already subscribe our maximum here we should be ours if subscribe Should not be - - - We mean if here we subscribe to our element and here we look at the property for it, then what will we do, here first of all we have to find the maximum limit, so to find the max, we use the for loop once. We will use this equal to zero to 1000 is fine and here we will calculate so here our com restart the previous song and what we have to do is just one condition like this if what we do we will write here. But if we subscribe, if our Do Subscribe My Channel Extra, if this is our channel is not subscribed, then this is yours in our list, then the list will start, otherwise our element will become voice there, then this is a simple roast with the help of which we solved the problem. Converted subscribe appointed which is our speed our which solve this problem on Bigg Boss simple sa this last subscribe and turn it on again so here we first of all we make a new appointment subscribe to come dot length it We will get the excise. Next what we have to do is that first of all we place Kwid inside it, after that we place the maximum which we make at the top. Now inside this, with the help of us, we will calculate how far will the point 204 go, this is ours, so copy and paste it. Let's update about it plus inside this we use this function and share this function and this is our increase and it will store it that as it ends this follow then we will get our maximum element then we What to do is a call option and we can run it like this which is our festival and this is our bread so here we appoint for this and inside this we if our we have to add to this if it is greater than equal to Ghaghra minor. Maximum - which is our extra candy, Maximum - which is our extra candy, Maximum - which is our extra candy, if it is greater than this, then give it to us, otherwise call us, this is our simple solution, after submitting, results are there, click on them and subscribe, get your result and subscribe, this is our channel subscribe. Do n't forget to subscribe our channel
|
Kids With the Greatest Number of Candies
|
all-ancestors-of-a-node-in-a-directed-acyclic-graph
|
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_.
Note that **multiple** kids can have the **greatest** number of candies.
**Example 1:**
**Input:** candies = \[2,3,5,1,3\], extraCandies = 3
**Output:** \[true,true,true,false,true\]
**Explanation:** If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
**Example 2:**
**Input:** candies = \[4,2,1,1,2\], extraCandies = 1
**Output:** \[true,false,false,false,false\]
**Explanation:** There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
**Example 3:**
**Input:** candies = \[12,1,12\], extraCandies = 10
**Output:** \[true,false,true\]
**Constraints:**
* `n == candies.length`
* `2 <= n <= 100`
* `1 <= candies[i] <= 100`
* `1 <= extraCandies <= 50`
|
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
1912
|
707 |
hello and welcome back to another Lee code problem today we're going to be doing problem number 707 design length list and it's not super tricky but you definitely are going to want to know how to like design a linked list and all these operations are going to be useful for other linked list problems you're going to have and so we're actually going to go through all of the things that are required and we're going to figure out how we're going to do these things so first of all to initialize the Mind linked list object so what you want to do with linked lists especially when you have you can have links with no nodes if you want to create dummy nodes either for the start or the start on the end if it's a we're going to create a doubly linked list here I think they have a choice of like you can do a singly or a doubly and so we're going to do the doubly linked list so we're actually going to do is we're going to have a head dummy note and a tail dummy node and they're going to point to themselves and so it's going to be like this and then we are also going to have the number of elements in the list so we can just call that num and just make that zero so what we're actually going to do is forget uh it's gonna be pretty straightforward so we're going to have the head remember and we'll have some elements we're gonna have the tail and so there's a few ways you could do this but we're just going to do a pretty straightforward approach where we are literally just going to Traverse the list so we're going to say like say this is you know we'll have some current node and then we are going to Traverse the list and we're just going to have a counter like how many nodes we traversed and then whenever we get a node we care about like this will be you know one two we would return that counter so that's how the get would work now add up the head let's take a look how that would work so let's say we have the head and we have the tail we have some nodes again I'm just going to draw two lines representing the pointers but they're really you know two pointers so what we're going to do to add the head is also pretty straightforward so we're going to be at the head we're going to have the element after the head and to add to the Head simply what you have to do is you have to put in a new element you have to have the point of this into this and then the other thing you have to do is you have to break up these two things and you have to just say for the two nodes that are on either side let's make them point to this node so that's how you would add to the Head add to the tail would be kind of similar except we just add here so we just take the tail in the previous node and there is an added index and so to add an index let's make this a little bigger and deleted index and we'll look at that so first of all um let's say we have a head again and we have a tail and we have some things and so you won't want to add an index what you do is you want to add before the element added index so let's just say this is index zero this is index one you know these aren't really like that but that's how it is that's gonna it's gonna be represented we're going to have some current node and so it's pretty straightforward so if we want to add index 0 we're going to start the head and whenever this current is like before the index we want to add we want to take the current node and the node after that it's the same kind of procedure so we break this up and we make a new node and then we make these connections so that's how you would add now let's take a look at a delete so we have a head some nodes again so we want to delete this node so what we are actually going to want to do is we're actually going to want to Traverse to the node before the node and the note yeah so we just need the node before the node which we actually have because we have the nice thing actually about the all these traversals is we have like the left and the right so we don't need to do so for most length list problems you're going to have singly linked lists and so you would actually have to Traverse here and then get that but the nice thing is since we have a doubly linked list we can delete a lot easier because we have the left and the right of the of whatever we're deleting so we're going to have a left we're gonna have a right pretty straightforward then we just so like I'm actually going to draw the arrows now so if we have this uh let's say this is here the nodes we need to delete are the nodes that are pointing to this node and we need to point them to each other so we need to delete or the not the node sorry we need to take the errors so these are the two errors that point to the node and it's okay that this node is still pointing to other nodes because the other nodes are now sorry this actually does not need to go there this needs to go over here and then I need to go over here and so even though this node technically does Still Point to other nodes because those other nodes never point to it and we're going to decrement the size and stuff it doesn't really matter right like if we have something like this and even though there is some node that points to these it doesn't really matter because we're never going to get to this node because nothing else points to it so that's totally fine leaving it like that so I think that's all the operations so yeah add an index delete it index and then we're also going to update like our you know our number of nums every time we add and delete an item we're going to add a 1 and 2 and so on there that way we could figure out quite easily uh you know how to delete things yeah so it says do not add the built-in yeah so it says do not add the built-in yeah so it says do not add the built-in linked list fine yeah and now another implementation of this could be you could use a hash map with the index being the key and then the actual node being the value but we can just Traverse I think that's fine like we can just Traverse whatever index we want there are benefits and you know downsides to each and this is only a thousand values so it's not that bad so we can use whatever we want here yeah but if you do want to like if you do get asked like okay how do I make this how do I make these insertions deletions faster and things then you're probably going to want to have a hash map where you store the index as a key the node as the value and then you yeah that would probably be like you know that would take more space but it would you'd be able to access nodes faster because you'd have you'd be able to access them in Big O one time or they're here we're gonna actually have to go through this whole thing okay but this is kind of like the traditional implementation of the link list that's what we're gonna do so start off we know we also do need to make so it's not given to us so we need to create a class for the nodes so let's do that it's pretty straightforward it only has an init Constructor itself um we're just gonna initialize everything to maybe like Val equals zero and then we're gonna say the next and the previous are none so previous there's none next I believe next might be something special here um let's just call it this yeah okay I'll just do this okay so then for the Constructor so it's going to be uh self. self dot previous equals none South Dot I guess this would technically be a previous but self dot next goes okay so that's gonna be the node so now for the initialize we need to remember we need to make a head and a tail we need to point them to each other it's going to be pretty straightforward so it's going to be self dot add equals node with the value of we can just we don't need to give it a value so then we say self.tail equals node then we just say a self.head then we just say a self.head then we just say a self.head dot next equals self the tail self dot tail dot previous equals self.head dot previous equals self.head dot previous equals self.head so we have them point to each other and then we need to also create a like a number of nodes so we can just call that a nodes here okay so next we need to get the value at an index okay well pretty straightforward so if the indexes is invalid let's check for that so if index is greater than num nodes minus one right so like if there's five nodes the last next is going to be index four I'll just make sure that yeah okay so this is a zero indexed so yeah this is the case then we are going to say that this is not possible uh otherwise pretty straightforward so we're gonna have our current node like I said it's going to be equal to the head and we're just going to Traverse down to the node we want so while index is greater than zero curve next so that's how we're going to get the next nodes actually what we want is we actually don't want self.head we want uh I think we actually want this because if it's zero we still want to go to the next node all right so if we have like a head and then another node and then a tail and we are asked for index zero it's going to start here so we do want one traversal to get to this node so while index is greater than or equal to zero let's move and then so if index is zero would do once if index is one it would go twice and so on and I think that's right okay now we just need to return so what are we returning we need the value so that's pretty straightforward so that's going to be occurred out valve Okay add up the head add a node before the first element in the linked list okay so remember when we added the head we need the head and we need like if there's some other values we need the head and then we need the values after the head and then we're going to change those pointers so we need the value that's after the head we already have access to the head so let's just say this is going to be uh maybe self.head or not self.head this is maybe self.head or not self.head this is maybe self.head or not self.head this is going to be like uh maybe we'll call that the first note or something right so just say first node equals self.head dot next equals self.head dot next equals self.head dot next okay there we go now we need to create a new node so we're gonna do that so new node Maybe equals node we're gonna give it a value so Val and then we are going to give it so it's next needs to be sorry it's previous needs to be the head and then it's next needs to be I do think actually this next right here might be a problem I think this is like a special thing let's actually use this instead of next oh no actually it's fine because we're just yeah no I think this is actually fine because even if it is a special function we're just redefining it so it's totally fine I think okay if we have any errors we'll fix it anyway so then we need to um what do we need to oh yeah put the next value of the new node to the next value in the new note is going to be the first node right so if we're at the head and we have some value here this is going to be the first node and we're putting in a value here the next value of the node we're putting in is going to be this and then the previous is going to be the head okay so this is going to be first node and then this is going to be head self.head.next and self DOT first node dot previous equals okay so we just made those pointers we're good when you also need to increment the num nodes uh nodes one uh nodes one uh nodes one we don't need to return anything so we're good there out of the tail pretty similar except now instead of the first node we last node so you know it is going to be self dot tail dot previous new node equals value so it's next is going to or it's previous it's going to be last node yeah so this previous is going to be the last note and it's next is going to be the tail so okay self dot uh tail dot previous then we have self Dot last node.next because new node okay node.next because new node okay node.next because new node okay so add at index add a node the value Val before the index okay if the index is greater this is kind of similar where if the index is greater than the length so if index is greater than self dot num nodes let's return let's just return okay so we need to add before and so when we add before so let's just re-draw some of this re-draw some of this re-draw some of this so we have a head tail we have some nodes okay and let's say this is noted zero index is node one index let's say we want to add it like index 0 or index one so what we're actually going to do is we're going to start here we're going to move up here and this is what we need so we need to actually access here we don't have this value directly because like I said we're not doing a dictionary implementation so we need the node right before this uh this node right here and then that way we can get yeah if we want to add before then it's been pretty straightforward because we're going to have these two nodes that we can just private point to this instead of to each other okay so let's do that so yeah so while index greater than zero we need to oh we need to have a curve so occur equals self.head occur equals self.head occur equals self.head and then this is going to be Cur equals or dot next okay so now we are at the node before like the node we want to add yes that is right so 0 would be yeah if then index equals the length of the linked list now would be appended to the n and that's what it'd be here I think so if the index is like one actually yeah so sorry the length of this list is two so if this was two it'd go here and then I would go here and then this would be and then it would be inserted right there which is what we want okay perfect okay so now we kind of do the same thing where we do maybe next node or something equals occurred up next and then so we have the curve.next now we make a new note the curve.next now we make a new note the curve.next now we make a new note again same story calls node with a vowel its previous is going to be Cur its next is going to be new node okay and then per dot next new uh next node dot previous equals node okay now delete I delete the X if the index is valid okay so if index is valid like let's say there's two nodes it'll be index zero or one so I think if index is greater than self dot num nodes minus one I believe right yeah because like if there's two nodes then the last index is one so this would be one yeah okay we also did forget to increment here okay did we have a deleted tail there is no deleted tail okay so there's add a tail there's a lead yeah okay so there's added index delete that index Okay so to delete at index we need to get once again the node before the index we're deleting so how would that look let's say once again we have a head zero one let's say we want to delete at index one here so we would start here so what we want to do same thing while index is greater than zero we want to move up one so now we're here so yeah we want the node before the node we're deleting and then it's pretty straightforward we just make this point to that and then that's deleted okay perfect so same thing while index is greater than zero equals curved up next okay now we want the node that's two nodes after current because that's the one after we're deleted so next node equals per dot next now we just do Cur dot next equals next dot previous occur decrement here okay um yeah let's see if this next actually gave us an error or not find out I might have to rename it something else um and yeah see what happens hopefully the best it's gonna be annoying to debug okay we hoped for something all right let's actually move this to the other side huh okay uh so let's just return if the index is invalid um self.first no Dot added head my link list object has no attribute first node ah this is a real painful one to debug for her hmm oh so we never actually decrement index probably didn't do that and some other stuff definitely for an actual interview I would definitely double check all this code but yeah you know um Cur man how many bugs can I make too many oh it never ends I was getting comical we're just making a bug everywhere we go please I think let's take a look sad okay so we added the head um so we have a linked list we added the head one maybe draw this out I am definitely good to look over but let's take a look so we have a head we have a tail okay I do think I want to actually change this value by the way um so let's do that okay it still has that error but it's okay um anyway let's see so out at the head we are trying to add one at the head okay so that would look like this all right and then now we're trying to add three at the tail okay no now we're trying to add that index to so adding an index 2 would actually be so let's actually so at index two I believe would be at the end so that would be over here so what are we actually adding add at index oh no sorry we're adding an index one okay so we're adding index one we're adding a two so I think let's go here okay now we need to get at index one so that should be a two we did get that okay deleted index uh we're deleting at index one so we want to delete this node and then we want to get at index 1 which would be the three and we're getting negative one so let's take a look at our implementation of delete Maybe okay well index equals zero Cur equals Cur dot next so if we want to delete let's say here at like index one so curve starts here okay occur equals where we got next yeah it's good to me okay now next node equals cur.next.next yep query.next equals next cur.next.next yep query.next equals next cur.next.next yep query.next equals next node X no dot previous equals curve that should be deleted but yeah we are returning negative one self-dundance nodes we did also do that I am curious uh okay so we didn't print it so how did we return minus one because it's a question did we return wait a minute oh no this is again so this is fine let's take a look at our get okay so our air is actually after missing it forever that's nice okay so let's talk about the time and space complexity this is definitely um like I said this is another great one for you to try out because lots of debugging lots of errors definitely would encourage you to put this up yourself and so here is time and space um so for let's think about it we can just do the time and we can talk about the timing space for every single function so of get will be oven oh of added head would be o of one add a tail o one added index is O of n because we have to Traverse to the index and so that's the downside of a linked list is you do have to actually get to the index add an index yes that's of one or oven and deleted and X is also event so like I said if you do want a faster data structure what you could do is you could make a dictionary I mean every time you add a node like let's say you have some nodes you would just figure out okay what index is this being added to kind of and then you can store that in the dictionary and that way these lookups can be of one so this deleted index can be o of one and things like that because like let's say you want to add it index zero if you know like what node is index zero you can just call that node directly from the dictionary and so on same thing for the gets so all these would be of one if you wanted to do that this is a small input so I didn't do that but so I'm kind of doing the standard linked list uh thing but if you want to do the more complicated one then definitely I'd encourage you to try using a dictionary for a space um let's think about it so I mean I think it's just pretty straightforward like it's just o of n where n is like the max nodes we're holding at a time or something like we just have one linked list we do have a head and a tail but those are just one thing so this is ovan where this is number of nodes and then these times are also and depending on how many nodes you have in your linked list at the current time okay so that's all for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Design Linked List
|
design-linked-list
|
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute `prev` to indicate the previous node in the linked list. Assume all nodes in the linked list are **0-indexed**.
Implement the `MyLinkedList` class:
* `MyLinkedList()` Initializes the `MyLinkedList` object.
* `int get(int index)` Get the value of the `indexth` node in the linked list. If the index is invalid, return `-1`.
* `void addAtHead(int val)` Add a node of value `val` before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
* `void addAtTail(int val)` Append a node of value `val` as the last element of the linked list.
* `void addAtIndex(int index, int val)` Add a node of value `val` before the `indexth` node in the linked list. If `index` equals the length of the linked list, the node will be appended to the end of the linked list. If `index` is greater than the length, the node **will not be inserted**.
* `void deleteAtIndex(int index)` Delete the `indexth` node in the linked list, if the index is valid.
**Example 1:**
**Input**
\[ "MyLinkedList ", "addAtHead ", "addAtTail ", "addAtIndex ", "get ", "deleteAtIndex ", "get "\]
\[\[\], \[1\], \[3\], \[1, 2\], \[1\], \[1\], \[1\]\]
**Output**
\[null, null, null, null, 2, null, 3\]
**Explanation**
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3
**Constraints:**
* `0 <= index, val <= 1000`
* Please do not use the built-in LinkedList library.
* At most `2000` calls will be made to `get`, `addAtHead`, `addAtTail`, `addAtIndex` and `deleteAtIndex`.
| null | null |
Medium
| null |
6 |
um hello so today we are going to do this problem which is a part of Fleet code daily challenge zigzag conversion so the problem says we get a string like PayPal is hiring um and then we is written in a zigzag pattern on a given number of rows right so in this form right so you can see PayPal is hiring like this um so basically some sort of pattern zigzag pattern like this okay um and you can read it so the way we want to read it is once we do the zigzag pattern we read each row okay so first this one that's what we have here and then this one and that's what we have all the way to here and then the last one here okay and the goal basically is to get this string in this zigzag format and we want to convert it to and then when we want to read it in a row by row um fashion right um so let's take a look at another example so for the first example which is this one PayPal is hiring right so we read the first row second row last row right so we get this one and then for the second example here it's PayPal right so the first four characters are in the First Column for the zigzag and then after that this one so yeah basically until PayPal is hiring is a drone and so we read it the first row is pin the second row is this one and so that's what we have here and then the third row you get the idea right uh for one letter just one right um and the constraint are not too big actually it's um 10 to the power of three to ten to the power of three so this tells you know something by the that is sort of a for loop on the characters of s and uh for Loop or rows should work fine right so sort of or when by a number of rows should work um okay so let's see how we can solve it um okay so let's see how we can solve this one so we have this um from this example the second example here so one thing you can notice is this we draw it in the zigzag pattern right so like this and then we move we do a zigzag like this and then we go down again and then we go up and then we go down right so it's sort of this pattern right and what does this pattern actually means like in theory it's just the original string by the way is just PayPal is hiring okay ring so if we take a look at this what is this actually this is just if we do it by column it's just doing PayPal so four first by the way the number of rows here are four right so it's just taking four right in the paper in the normal direction right uh from zero so let's say this is zero in the number of rows right so from 0 to n minus 1 the number of rows minus one so this would be zero this is R minus one let's call this r and then we go up which is from three all the way to um just before zero right yep so just before zero at one here we can consider the up ends here and then we start down from the zero okay so basically the pattern is actually just like this right so from 0 to R let me just correct this a little bit so from 0 to R minus one and then from R minus 1 to 1 and then from zero again so we include this 0 in the column down to R minus 1 again and then we keep going until there are no more letters so we stop here at one let's just make the super close so we stop at one and then we start from zero down we do that again to one we start from zero down until there are no more characters right and this is the exact pattern without doing and so we can actually just follow this except we will need what do we need for this um for each iteration basically we keep the index going until we fill the two basically each time in the iteration we fill the uh a pattern of up and a pattern of down so with this pattern here from 0 to 3 and then this pattern so for each iteration we fill this but the second iteration we fill this and we'll keep going like this okay so how would that work well let's run on an example let's not on this example actually um let's do it on stood on this here so what will happen is that we'll start an index at this position zero let's call it in our case here just I so I'll start I there and then we will need something to hold the values right and so let's call this just a string of rows right that will have each of the rows here so it will have each of these okay and so let's say so it would have 0 1 2 3 and we'll fill it okay so we start with at p and what we need to do is basically while um we start at a specific row right we start at row zero right and we want to fill each row from the column and so while that row is not has not reached the end which is smaller than R and of course we want to also make sure we don't exceed the number of letters right because for example in this case we don't want to proceed until R minus one we want to stop here because there are no more letters so we're going to make sure that the I we are doing here is smaller than n which is the length of the string okay so for that what do we want to do well for each one letter we want to add to the proper row just like we are doing in the zigzag here so we counter P it needs to be in row zero so we add p and then we increment um we need to increment both our row to go to the next one in the column and the index right so here what we need to do is just say the rows what we did here is the rows at row R we added s at I right and then we're going to increment R to go to the next one and we want to decrement the we're going to increment the I here so I moves to the next letter and now we are at Row one so now R is equal to one let's just hold that so I equal to 1 r equal to one right and so we add a here we move again where R is equal to 2 and so we add y here and then we advance I and now our R is three and our I is 2 0 1 2 3 sorry our R is I is 3 and so we add P so we can see this actually matches exactly this right and then we now we reach it three right which is the end of this so we stop here and we need to go to the neck at the other direction so that's the other loop so the other loop needs to start because we already filled this position the other loop needs to start here what is this is just R minus 2. so it needs the r is the number of rows so we need to start at R minus two and we need to keep going until we reach this position which is one because this position is part of the next row going with the indices going up and so we'll have to do while R is bigger than 0 right we want to stop at one so we just do bigger than zero and of course we always want to make sure we don't exceed the number of characters available right um so that's important so here and I is smaller than n um we want to do the same thing we are doing here except so exactly copy put here except what needs what does need to change we because we are going down in terms of like the indices of the rows we need to decrement this here okay we need to document R okay and so now let's continue so we move our I to a here what's the value of R is R minus 2 we said which is which needs to be R is uh four so minus 2 is 2 so our row is 2 and our I is 4 now right because we Advanced it here and so we place our value a in row 2. and then we move to um so here we just concaten it so you can think of this as just having uh like this and you already see this is starting to be like this is starting to match what we have here right um and so we if we continue Here We decrement R to three we uh sorry I made a mistake here this is I becomes 5 and this here becomes three uh B minus one sorry becomes one okay so the next letter is Al and so L where do we place it in row one right so Row one we place l and now you can see still this matches what's in row one right so we continue again we move I here we are at I we need to place it in row one uh we need to place it in row zero right but since we reach a zero we exit here and so we go back to this one we go back to the loop again so this would be for while index is smaller than n and so we go back here uh we need to add place it to row zero and so we add it here this is I so we'll place it here okay and then we need to increment row so row becomes one and six and so I moves here so we are at s which is this one and so we want to place it in row one and so we place it in row one and you can see this still matches what we have here and then we move um we move I so we move I here and we move R up so two and now we need to place a in row two it's a or H it's h sorry it's h from hiring so we place H here and then now we increment R so R is equal to 3 and I is equal to 7 and now you can see R is um 3 and so what we need to do is move I here to I and we need to place I in Pro 3 so we have I place it here so we add it okay and you can see this also matches this okay I think we can stop now feel free to run it on the entire example if you want but you get the idea it should work fine because we each time we just uh fill the rows going from 0 to R minus 1 and then we fill them again coming from R minus two to one and we keep doing that until we know we don't have any letters anymore right so pretty straightforward actually now let's implement it and make sure it passes out test cases um okay so let's implement this solution so what we need is um we said we need to have I that traverses s and so it and it needs to be the length of s and then we are first going to go from like zero to R minus one right so this is basically you can think of it as up um and then after that we go from R minus 2. to um to one right because zero is already done by this so this is down so we start here and we want to keep going until R minus 1 so smaller than R and we always don't want I to exceed the string and then here we want to go from R we said r equal to n minus 2. and we want to keep going until one so we can just say bigger than zero right and so what do we need to do here we are going up and so first we need to put we need to initialize our rows list so this is going to be just a string for each row um range of the number of rows so just to match what we saw in the overview let's call that r um and then here we need the row we want to add the character at this Index right and then we want since we are going up we want to increment our rows and so since we um we want to go to the next character because we already use this one we want to increment I um and then here we of course want to also add the string but we this time since we are going down we want to decrement okay and then we want to of course increase the index always okay and then here we will get um a list of the strings for each row and since the problem once you read each row but you combine them right so we just want to combine the strings for each row so to do that for just use join for the rows and that should be it so from this um looks like there is uh we need yeah just to specify that we are not using the index there um yeah we didn't Define I thought about that and looks good let's submit and this passes test cases right for time complexity no matter what happens here even though you have multiple Loops we won't do the maximum number of iterations we will do is the length of the string right because um because each time we'll place a string and each time we limit by I smaller than n right so this is oven actually yeah um yeah I think that's pretty much it you can do this differently if you want to sort of use um Direction um and not have two while Loops so actually let's try that so what do you need for that is you just need to keep track of the direction because if you look at the two Loops the main difference is the direction of the where how we increment row if we incremented or decrement it right um and then we just want to switch that direction when we reach R minus one or when we reach 0 that's exactly what we are doing here so let's actually just um comment this and apply that so we need the direction to tell us if we are going up or down so let's start with going the um up right by incrementing by one so each time we know we want to do this and then we want R we want to do R is R plus one or IR minus 1 depending on the direction and that's just adding the direction and now when do we switch the direction you can see here we switch if we reach R minus 1 or if we reach 0 right so here we can just check if R is equal to 0 or R is equal to R minus 1 we want to switch the direction and switching is just if it's one um so basically minus 1 If the previous direction is equal to one otherwise it's if it was equal to minus one we do one and this is just multiplying by minus one right because if it was minus one we multiply by minus 1 we get one if two is one we multiply by minus one we get minus one right so that's changing the direction there um and so that should be it we want to return uh join rows like we did actually we still have it so let's just copy it over up here and you can see this is a lot simpler um and because of -1 what will happen um and because of -1 what will happen um and because of -1 what will happen for R minus 1 is that we will decrement by one and we will get R minus 2 anyway right the only thing is that let's try it we need to still increment I plus 1 here okay uh looks like let's get rid of this first and run it um okay let's see why is r not defined yeah I didn't Define this so let me just Define it here to zero okay um yeah so this is basically for the case where a string is equal to um let me remove this one first just so that you can see so it works for other cases except for the case where you have only let's say one row then this solution won't work properly because you don't have a next row to go to so for that solution so this is the only disadvantage of this short solution is that um if you have only one row you need to treat it especially and so for one row there is nothing to do just return the string right um and so we do that but you can see it's a lot shorter it's one Loop and actually we can even make it more simpler by saying we don't need this while loop we can just go through the string like this and remove the eye and remove the need for an eye here and at this point we don't need n either and so we just need R in Direction which starts out at one um yeah this is C if we submit this and this works right so pretty straightforward here once you get the first iteration you can improve it and make it look like this um yeah so that's pretty much it for today's problem please like And subscribe and see you on the next one bye
|
Zigzag Conversion
|
zigzag-conversion
|
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
**Example 1:**
**Input:** s = "PAYPALISHIRING ", numRows = 3
**Output:** "PAHNAPLSIIGYIR "
**Example 2:**
**Input:** s = "PAYPALISHIRING ", numRows = 4
**Output:** "PINALSIGYAHRPI "
**Explanation:**
P I N
A L S I G
Y A H R
P I
**Example 3:**
**Input:** s = "A ", numRows = 1
**Output:** "A "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000`
| null |
String
|
Medium
| null |
67 |
hello everyone welcome on welcome back to coding Champs in today's video we are going to be solving the problem at binary in this problem we are given with two binary strings A and B we have to return their sums as a binary string so let us take a look at the examples we have here equal to 1 and b equal to 1 so let me write them down 1 and 1 so if we add 1 and 1 we get 2. so how do we represent 2 in the binary 2 in boundaries um one zero so we write 0 over here and 1 over here again 1 plus 1 2 so again we write 0 and 1 goes to carry since we don't have anything we write the carry here so the result is 1 0 and we return it in the second example we are given with 1 0 and 1 0 1 so 0 plus 1 is 1 plus 1 is 2 so we write 0 and 1 will go to carry and we have 1 0 1 plus 0 is 1 and again 1 plus 1 is 2 so 0 and 1. this is the result and we return the result string so how can we solve this problem like how we have done now we have used the approach that we have learned in our primary class so we have added the last week we started iterating over the last and we have added the last characters and we get some and we take the if our sum is like 2 in this case if it's almost 2 then we take class character the last character in our two over here and then the next character in the two as a carry okay we added this character to the result and this character the second character to the carry um so that's it if we have in binary so in binary it's not like we can write 2 if we have to then we have to consider 0 and 1 as carry if we have 3 then we have to consider one and carry as also one because 3 is represented as 1 and 1 is represented as 0 1 and we don't have to take 0 as the can because addition of 0 doesn't change any value right so how to get these values the sum and carry what we can do is if we have 2 we can do 2 mod 2 if we do mod 2 then we get this reason 2 mod 2 is 0 and 3 mod 2 is 1 so this way we can obtain the values that we add to our result and then for carry what we can do is or we can divide the result by 2 so 2 by 2 is 1 and 3 by 2 is again 1 and if in one case uh 1 by 2 is 0.5 which will be 0.5 which will be 0.5 which will be 0. right so the carry will be 0 and the result will be 1 what 1 2 1 mod 2 is 1 so the result will be 1 and the carry will be 0. so in this way we can solve the problem um the approach will get more clear when we code it up so let us see so we start iterating from the backwards right let me take two pointers which point to the last characters so let's take in I equal to a DOT size 9 a DOT size minus one and be equal to B dot size minus 1 and we should have a sum variable and a carry variable and also we should have a result stream where we add our result so let us take the rest and let's start iterating so we iterate let's say we have um we have a string one zero and we have another string one okay in this case what we do we add 0 1 we add 1 which will be is 2 so 0 1 and here one we don't stop when one string ends we keep continuing till uh either of the one exists right here we do one zero and this will be one and one so this will be the result we do not stop when one string ends will continue either till either one string exist okay so that the condition that we write over here so if e if I is greater than or equal to 0 or J is greater than or equal to 0 we keep looping and here we have to check which string exists and which string doesn't so if both string exists we add both to the sum if only one exists we add that only to the sum if I is greater than or equal to 0 then so here initially from equal to we do sum equal to carrying because we have to overwrite the sum each time um so let's say that an example so in this case if we have a 1 and 0 1 in this case um 1 and 1 we have so that will be to 0 1 and now um when we come over here we overwrite the sum with the carry we take some as carry we don't consider the previous sum we take some of the carry and then we add these two characters to our sum then we get the sum of this column okay so that's what we are doing here we are overriding the previous sum with the gal and adding the new values to our sum the values in both of the strings at that position okay some plus equal to a of I these are in character set we have to convert them into string so I'll do minus 0. and no we have added so we have all after that we have to decrement right so I'll do it here only and similarly for J if J is greater than or equal to 0 some plus equal one tool B of J minus let's see now we have added that now what we have to do we have to find the next what we have to add to our result and what we have to take as a carry so to our result we add some more 2 and this is an integer so to convert into string we do use a two string function and now what we have to do we have to find the carry what will be the carry some divided by 2 and finally here in this case we have carry as 1 so we have added carry at the last so we have to check the transition as well if carrying is not equal to 0 then the art carry to our result equal to root string of um charge interesting we have added we have Traverse in the reverse order we have travels in the reverse order and we have appended to our result right so the result will be in reverse order so we have to reverse the river reverse the result in order to get it in correct order let's do that reverse result dot begin Dot and anybody got resulting so let us run the code okay this should PJ right is it the same column passed all the sample disk cases later submit it seems like it passed all the test cases so what will be the time complexity of this approach will be o of n was maximum of n comma n if we take the length of the string as n and the length of the string as M so we iterate over this both the strings so we go through the we are treat how many number of times the number of characters the maximum number of characters present in the both strings so we'll take that as the time complexity and what is the space complexity is OS um maximum of English and comma M as well because we have this result string right so we use the result string will be its result it's the length will be maximum of n command so the space complexity will be maximum of n comma as well so Raman space complexity is of maximum of n command so I hope you have understood today's problem if you did make sure you hit that like button and subscribe to coding jumps for more daily videos keep practicing take care bye
|
Add Binary
|
add-binary
|
Given two binary strings `a` and `b`, return _their sum as a binary string_.
**Example 1:**
**Input:** a = "11", b = "1"
**Output:** "100"
**Example 2:**
**Input:** a = "1010", b = "1011"
**Output:** "10101"
**Constraints:**
* `1 <= a.length, b.length <= 104`
* `a` and `b` consist only of `'0'` or `'1'` characters.
* Each string does not contain leading zeros except for the zero itself.
| null |
Math,String,Bit Manipulation,Simulation
|
Easy
|
2,43,66,1031
|
1,041 |
hi i am ayushi rawat and welcome to my channel today we will discuss the september lead code challenge day 17 problem robot bounded in circle now let's have a look at the problem statement on an infinite plane a robot initially stands at coordinates 0 and faces north the robot can receive one of the three instructions g go straight one unit l turn 90 degree to the left r turn 90 degrees to the right the robot performs the instructions given in order and repeats them forever return true if and only if there exists a circle in the plane such that the robot never leaves the circle okay now let's have a look at the examples example one g llgg output is true the explanation reads the robot moves from 0 to 0 2 turns 180 degree and then returns to 0 when repeating these instructions the robot remains in the circle of radius 2 centered at the origin the next example reads input is gd the output is false why because in this case the robot will move to the north indefinitely next example the last one input is gl output stands true why because the robot moves from 0 to 0 1 to minus 1 0 and again back to 0 that is the robot has returned to the origin that's why we returned true now let's read the note 1 is less than equals to instruction dot length is less than equals to 100 the second instruction reads instruction of i is in g lnr now let's look at the hints hint 1 reads calculate the final vector of how the robot travels after executing all instruction ones it consists of a change in position plus a change in direction hint 2 reads the robot stays in circle if and only if looking at the final vector it changes direction that is does not stay pointing north or it moves zero there are only two scenarios where the robot can come back to its original location one being the robot is already back to his origin by the end of the string traversal and the robot is away from the origin but heading to a different direction from its initial direction let's say suppose the robot is facing left by the end of the first string's traversal after that three other traversals of left to left it brings back to the origin a second example would be robot is facing down by the end of the first string traversal in that case it takes another traversal for it to get back to the origin we can actually keep a list of all possible directions what would that be the coordinates 0 1 minus 1 0 minus 1 and 1 0 we can swap d x and d y and add a negative sign to one of it to rotate the direction by 90 degrees right the proof is the dot product of d x d y and d x and d y minus d x is zero what does that mean that these two vectors are perpendicular to each other it should become more clearer to you once we code so let's quickly head over to the coding section first i will define the direction as coordinate 0 1 and i'll declare x and y as 0. now i will run a loop over instructions now i will check if instruction is equals to g in that case i will append x plus d i of 0 to x and i'll substitute y of d i 1 to y otherwise i will check if the instructions is equals to j in that case i will set coordinates d i as minus of d i 1 and d i of 0. is i will substitute d i as d i of one and minus d i of zero at the end i will return true either if x or y equals to zero or direction is not equals to zero comma one coordinates now let's try running the code now let's try submitting it and it's done you can join my discord server and telegram channel for regular updates you can find the code at my github repository link is available in the description box below if you wish to connect with me on other social platforms the link is mentioned in the description box below if you have any queries or suggestions please feel free to ask if you like the video hit the like button and subscribe my channel thank you for watching
|
Robot Bounded In Circle
|
available-captures-for-rook
|
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction** is the negative direction of the x-axis.
The robot can receive one of three instructions:
* `"G "`: go straight 1 unit.
* `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction).
* `"R "`: turn 90 degrees to the right (i.e., clockwise direction).
The robot performs the `instructions` given in order, and repeats them forever.
Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle.
**Example 1:**
**Input:** instructions = "GGLLGG "
**Output:** true
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"G ": move one step. Position: (0, 2). Direction: North.
"L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.
"L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.
"G ": move one step. Position: (0, 1). Direction: South.
"G ": move one step. Position: (0, 0). Direction: South.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).
Based on that, we return true.
**Example 2:**
**Input:** instructions = "GG "
**Output:** false
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"G ": move one step. Position: (0, 2). Direction: North.
Repeating the instructions, keeps advancing in the north direction and does not go into cycles.
Based on that, we return false.
**Example 3:**
**Input:** instructions = "GL "
**Output:** true
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.
"G ": move one step. Position: (-1, 1). Direction: West.
"L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.
"G ": move one step. Position: (-1, 0). Direction: South.
"L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.
"G ": move one step. Position: (0, 0). Direction: East.
"L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).
Based on that, we return true.
**Constraints:**
* `1 <= instructions.length <= 100`
* `instructions[i]` is `'G'`, `'L'` or, `'R'`.
| null |
Array,Matrix,Simulation
|
Easy
| null |
135 |
hey what's up guys this is sean here again so today's daily challenge problem writes number 135 candy so there are like young children standing in the line each child is assigned the reading and then you're giving like candies to these children subject to the following requirements each child must have at least one candy and children with a higher rating get more candies than their neighbors and we need to return the minimum number of candies you need to have to distribute the candies to the children and for example we have this reading we have three children the reading has one zero and two so the answer is five because it's one it's reading one zero and two right so like i said you know the neighbors right i mean the child who has the higher rating must have more candies than his neighbors at the beginning everything is one right but in this case okay so one is greater than zero which means that you know this one needs to have two right and 2 is greater than 0 this one also needs to have 2. that's why we have 5 in this case and this one second one so this one is like 1 2 and 2 right so we have one at the beginning right and then two is greater than one so this one has to be at least two right but this one you know two is not greater than this one that's why we can keep this one as one that's why we have four here right and then yeah so some common constraints 10 to the power of 5. so for this one you know the minimum you know uh we can either use binary search or like or the dp or even the greedy right so for this one i mean the binary search uh let's say given like a fixed number of candies right can we allocate it to all the uh to all the child okay can we do that let me think can we use that as like as a solution um probably not because you know we if we try to use a given like fixed number of candies if you're trying to allocate to the people to the child we still have to somehow use a greedy approach right to allocate the candies to the children right so which means we don't have to do that and the dp i don't see any state transition here right from current one to the previous one yeah because we have to cover uh consider the neighbors both the left and right you know since we'll be using the greedy in the binary search you know if we can use the greedy directly then we don't have to do the binary search at all right and actually the answer for this one is the grady solution because for the first for the brutal force so what's the brutal force way so the brutal first way is the we have to basically scan uh trying to assign the readings trying to assign the candies end times right and then basically which for each readings we try to scan the entire array right and we try to assign them from the smallest to the biggest and then we do it end times but that's going to be going to tle right so with a greedy approach so what we're doing here is i don't know we try to satisfy the neighbors right one by one like i said i think i already showed you guys because you know so if we have some uh children let's say we have you know the base case is like this so if we have this is a reading okay one two three five right so that's the base case so i think i already showed you guys what how i got the answer at the beginning everything's one right and then from left to right yeah because you know so first we since we need to satisfy both the left neighbor and the right neighbor that's a strong hint that basically we have to scan the uh the array twice basically one from left and one from right because we have since we need to satisfy both neighbors right so for this one let's say from left to right so at the beginning everything everyone has one candies but two is greater than one which means that you know this one has to be two right and the three is greater than two which means this one has to be three right so the same thing for five so this one has to be four so that's how we satisfy the left side but how about the right side right so let's say the on the right side we have this four three two one zero right so how about this one you know at the beginning everything is one right like i said but when we uh scan from left to right you know this uh this four the remaining well uh the remaining children will have will remain uh we have still have one candies right because this one they are smaller than the previous one right that's why we from left to right we don't check that then we have to scan again from right to left because we have to satisfy both sides right at the first scan we're satisfying we're making sure the left neighbor uh the left neighbor will always basically the current one the current children will always have like uh more candidates than his left neighbor if he has the higher rating than the left neighbor right then for the second pass we have to scan from the right to left to make sure the right neighbor also satisfy the condition right so in this case let's say we have this one we have this two right so now this one is two this one is three this one's four right this one is five okay now and here we have a conflict here right because here we are we already have four but here we only have four started here we only have we already have five but here we have the five only has four so which means we need to update this one from four to six basically we'll need to use whichever is greater either this number itself or the previous one plus one because now let's say you if this one has like only two right if this one it's like this is another scenario right so this one we have one but in this case you know four uh two is enough for four right but so that's why we add five here we don't have to change anything because four is greater than first greater than three uh then two plus one that's why four is okay um yeah i think that's it right so we simply just need to scan the rate twice either from left to right to satisfy the left neighbor and then from right to left to set to satisfy the right neighbor and that's it uh let's do it right so then it's gonna be the length of radiums okay so the answer at the beginning every everyone has one candy right so from for left to right one to n gonna be if the rating right i is greater if the current one is greater than the then the left neighbor right i minus 1 then we do our answer dot i equals to the answer dot i minus 1 plus 1. so this one for the first loop here we don't have to do that comparison because we simply just need to increase that one by one whenever the current one is greater than the lag number we simply increase the left number by one and the assigned to the current one right and then for the second loop from the n minus two from left to right from right to left right minus manners so this time we have to uh make sure because we have already have some numbers set for some index right that's why you know for this time you know we have this one i is greater than the ratings i plus one right if this happens you know the answer i now equals to the max of the answer i right of the answer dot i plus one right so this one means that you know since we already have answers set from like from the left neighbors we have to make sure this answer is at least this big and then meanwhile we're gonna also check if this number can satisfy its right neighbor right if it can't then we keep this one if not we have to bump this uh this real number based on the right neighbor okay and then in the end we simply just summarize all the final answer right i think that's it right so accept it yeah there you go right so this is like a greedy approach basically we start from the very small and then we only increase it when it is absolutely necessary right for example this one that's all the necessary step and here is it says as well right so we only increase when the right neighbor is greater than the current one right or equal than the current one then we increase otherwise we can keep the current one to satisfy both the left and right neighbor and yeah i think that's it right i mean it's very classic greedy problem and the time complexity right often okay and yeah cool i think that's it thank you for watching this video guys and stay tuned see you guys soon bye
|
Candy
|
candy
|
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.
You are giving candies to these children subjected to the following requirements:
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
Return _the minimum number of candies you need to have to distribute the candies to the children_.
**Example 1:**
**Input:** ratings = \[1,0,2\]
**Output:** 5
**Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
**Example 2:**
**Input:** ratings = \[1,2,2\]
**Output:** 4
**Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
**Constraints:**
* `n == ratings.length`
* `1 <= n <= 2 * 104`
* `0 <= ratings[i] <= 2 * 104`
| null |
Array,Greedy
|
Hard
| null |
345 |
I friends, how are you all, today we are going to talk about reverse vowels of a string, so what is this question saying and what do we have to do with the vowels, we just have to reverse them and return them, so let's see through the example like in this If it is Hello, then the vowels in it have been reversed and this becomes If you see it on your white board, you will understand it better and there can be capital letters too, there can be other small letters too, okay, so it is as if you have given Hello. If it was then what will happen in hello that the consonants will remain at the same place in the return string and the answer will also remain in the same place in the string, meaning if you look at it in your own way like man lo amit then what will be its reverse. If you go to the team, what does it mean, if you look carefully, I am telling you that this is a normal case, only the reverse swipes got swiped together and the MRI which is swiped together, then A and T I T and I and this. I am getting it's okay, so I just mean, what do you have to do? Wherever in this question, keep looking from the front, where is the vowel, okay, I saw from the front, Google's howl is not there, if you move ahead, I am here, it is okay. Here we have come here, started looking from behind, who is our Google, that is our vowel, now what have we become, OLLI, then after that keep repeating the same process until I and K which are each other. Don't cross. Okay, ay and k cross each other, meaning your string is finished. This is the lead code in this case. So see in this, whatever consonants are there, they will remain at the same position. In the answer string too, only the vowels which are there are in front. It will go from and it will find the vowel. Okay and we have to take a gel. It will break from the back like in this case here a aya a pe a gaya okay and apan di is a consonant. If you go and your question is finished, then look at the code, this is a very easy question and there are many unknown dislikes in it, I have also given the dislikes here because it might have seemed easy to the children, so let's look at the code easily. Apna ko has a string S's van, Apna took out its size and found the vowel starting from end and i and gave the value of k as n - and found the vowel starting from end and i and gave the value of k as n - and found the vowel starting from end and i and gave the value of k as n - 1. It will go from n till our i < 1. It will go from n till our i < 1. It will go from n till our i < till both cross. We will run our loop and what we will do is first tell I that you will see where you are getting Google from now onwards, as long as you have put I < note then you have understood the meaning, as long as you are getting the consonant, you have to keep increasing I, okay. Na, in a way, as long as we are getting the consonant, let's keep moving forward. What is this vowel function doing? There are many people in upper case, 'Upper' many people in upper case, 'Upper' many people in upper case, 'Upper' is fine and you, I have given the team. Now if any of these if characters are equal to So it means that this one is fine, it will do the root and proof, so we have traveled in this string and this is not a constant operation because the length of the string is correct, it is only 10 sizes, so it is constant. The operation is done, it's okay, and if it goes anywhere equal to 'f', then make a it goes anywhere equal to 'f', then make a it goes anywhere equal to 'f', then make a return that 'Han Bhai, return that 'Han Bhai, return that 'Han Bhai, whatever 'f' is there, make that one false, okay, if I whatever 'f' is there, make that one false, okay, if I whatever 'f' is there, make that one false, okay, if I come here, I found my own like this. Then I placed my Se on K and here I have sent Ace of K. This time I have not sent and K is mined. Both of them will be at both ends. If there is still I < S, if it has If there is still I < S, if it has If there is still I < S, if it has not been crossed then open it. What to do, I swiped and moved both of them forward, I pressed + and its mines pressed + and its mines pressed + and its mines were just this little code and in the return I made the answer string 'S' I hope you will made the answer string 'S' I hope you will made the answer string 'S' I hope you will like the video and also watch the playlist of 'Oops', it's like the video and also watch the playlist of 'Oops', it's like the video and also watch the playlist of 'Oops', it's very good. Thanks for watching, see you next time
|
Reverse Vowels of a String
|
reverse-vowels-of-a-string
|
Given a string `s`, reverse only all the vowels in the string and return it.
The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once.
**Example 1:**
**Input:** s = "hello"
**Output:** "holle"
**Example 2:**
**Input:** s = "leetcode"
**Output:** "leotcede"
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consist of **printable ASCII** characters.
| null |
Two Pointers,String
|
Easy
|
344,1089
|
114 |
ok welcome back to my channel today we will talk make two real best video guys today radheshyam suggestion or hour solve question great 0ffline ab to landless and different videos subscribe my channel like this subscribe must subscribe reversal list of servi subscribe two three four One two three four turn on slider rights of trees and 156 is the meaning of this up and MD Gautam ok so another example this line through this only one hour channel subscribe hour number more than 90 - - - 121 add extra oil to solution subscribe and subscribe the Channel Saudi Now this traversal and stored in notes in these new tree to avoid all new notes use this cream and finally on science the original route to new road to the results newly created not only but this jar solution edition office Let Everyone Know The Furious All The Notes In The Space Complexity Will Be Mode Of In Definitely Veiled It's Not Official Notification Approach And Tours In Which Will Make No Extra Subscribe To The Page Treatment For Software To Discuss About This Is The Little Bit Of Pictorial Representation After which give example the same tree in Noida and see how to solve this problem Subscribe Jaipur root is a what we can do you want you to check this root note is next 9 newsroom se left right a lot follicles right month And what the want to here to take this loop not got destroyed 90 to take this root not right three tier right leg is to pregnant shoulder to android tree that and were going to make this right again the right mode of the right most mode of ours Left Mode of the Ru100 Beau Fruit Veto Available from Left to Right 09-09-09 Right to the Right Short Note On 234 Now You See The Get Of Writing Is Made Destroyed Incorrectly Lakshmi Mystery Correctly On To Basically A Positive Way Not Written For This 99506 Subscribe One Two Three Four Aadat Se Please 12345 Shy 961 Add Ki Election Hi Comparing With The Picture Of Gyan Yoga Incident For 500 Rs Take Now Connected To The Right Please Mukesh 350 Shy Please WhatsApp To Is Just This Hole On The Other Side Voice mail this left re the right of rural water tank in the history and the right free of cost to identify left right now the day null that and a piece of mind the left nod to the right mode of rural students york1 this point This Computer Now Behavior Roots to Remove The Story of My Life 9999999999 Ride Subscribe 999 Shab Soilder Same Thing If You Didn't Have the Rights of Free Water Will Do I'll Take the Directory Cutter Animated The Right Left Mode Switch Off Nominate Leo Last Day of August Reason Printer Nominate Notification What is the Next Native Which Date for Truth No Doubt to Make Its Loot Channel and Contented Life in Video Right Three Does the Same The Amazing Content IS Right and Left for The left side is 209 mode on right element of is avni second subject element of minerals and left element of two years channel and the right element of two 9 324 506 compare this with its side to withdraw 123 456 right position not good night Oak Final Year Result Not For You To Explain The That And Looted And Ride After Var U Not To Divorce In Tamil Nadu Traversal Right Most Node Of Left No Attempt To Right Node Set A Reminder To The Right Month Not Travel That Is The Faith A Tree Of Root North Edison Dry Tree And Make Glue Node Of Root Not Help Channel And Finally Swift Root Node To Resurrect In The Treatment Of The Match 2018 So Let's Move To Recording Partner And See How They Can Implement This Will Give You Don't user is approach from servant blouse benefits of wine rude note a professional under root is question a that this someone who first of all create to prepare right me request loot right and green node left pimples that daughter for doing now subscribe right or left or right most dot right this question on the right notification right nine stock prices are engaged that finally no right most valuable expression right nodal sonth you can do you can simply on this ireland right node to right the right mode of road dot right vikram request you know and not left side me left right left no do that if voices of this computer 110 012 sign roots right wali zaroor bhi guava dot right so they can start a beating the retreat which has no regret at its elements select Radhe Receive This Works And Accepted For This Subscribe Now Talk Time And Subscribe Kariye Time Complexity And Every Element With U Hi Honge And Acclaimed Yaar Pure Video subscribe The Channel for More Video Subscribe My Channel Subscribe And Will Continue To Thank You For watching my video by
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
520 |
all right welcome to this video we're gonna be doing miko problem 520 detect capital so return it return a true or false value right a boolean value if all letters in the word are capitals all letters in the word are not capitals like this or just the first letter of the worst capital and the rest is lowercase so there's I've seen a lot of different ways to solve this like regular expressions etc but I'll give you a solution that made the most sense to me to understand so we're gonna do is get a count of how many capitals are in the input string so I'll say let capital count be equal to 0 and let's increase it in courting accordingly if there are capitals so I'll say for let I is equal to 0 we're gonna input we're gonna iterate over every character in the input string or letter where do you want to call it so for let I is equal to 0 eyes less than word length I plus to make my code easier to read I'll just say const char is equal to word at index i you could also call it letter constant letter right I'll call it char so we'll say if char is equal to itself uppercase right if the character is equal to itself uppercase then that means it was uppercase in the first place right if the character was uppercase in the first place it will be equal to itself uppercase again if the character was lower cased was lowercase in the first place it will not equal to itself upper case so again this if check is saying if the character we are on is uppercase then capital count plus equals 1 and that's it this for loop will iterate over every character input string and get an accurate capital account now let's go over the three conditions that we return true all letters in this word are capitals like USA so I can say return capital account is equal to word dot length right every single letter is the capital so that's our first check done or all letters in this word are not capitals likely code so I'll say here or capital count is equal to 0 and finally I'll say or I'll put some parentheses just the first characters uppercase and the rest is lowercase and to represent that I'll say word at index 0 the first character is uppercase so word 0 let me type this out first so again was I'm not finished yet so let me just reiterate over everything again so either everything's capitalized nothing's capitalized or our final condition the first character is capitalized and the rest is lower cased so I'll say Cal is equal to 1 maybe put parentheses here so it's easy to see what's going on right this means only the first character is capitalized the rest is lowercase so I'll save you know go ahead or delete code and let's make sure that the test pass and of course if you like this kind of content be sure to LIKE comment subscribe hit that notification Bell to be notified of new content let's press submit and we pass the codes tests so what does detect capital complexity analysis time complexity is o of n because we go over every character in the input string using that for loop right and space complexity so of 1 yes our capital count variable can increase but isn't it is a type of number and that's constant space all right that should be it for this video
|
Detect Capital
|
detect-capital
|
We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like `"USA "`.
* All letters in this word are not capitals, like `"leetcode "`.
* Only the first letter in this word is capital, like `"Google "`.
Given a string `word`, return `true` if the usage of capitals in it is right.
**Example 1:**
**Input:** word = "USA"
**Output:** true
**Example 2:**
**Input:** word = "FlaG"
**Output:** false
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase and uppercase English letters.
| null |
String
|
Easy
|
2235
|
120 |
hey what's up guys chung here uh today let's talk about not another uh at least called the problem uh 120 triangles so you're given like a triangle and you need to find the minimum path from top to bottom and each step you can only move to the adjacent rows below it so what does that what does the adjace adjacent numbers below on the row below what does that mean so let's say for example number five right it can only move to i and eight for three only six were six or five for four only i uh sorry for seven uh eight to three right so what does it mean it means that with current index uh i right it can only move to uh so the next level will be uh i and i plus one right the index on the other next on the next row so those are the only two options uh he can move to so in order to find the m the minimum path of this so how can we do it right and if we do it top down right if we do it top down so we have to keep track of basically each of the possible paths basically right we have to try all the possible possibilities right and then in the end we just return the uh we just return the minimum path right that's going to be a little bit trivial right we have because every time we have to try this all the other paths basically i think a better way of we a better way of doing it is we do it bottom up right that's a better way for bottom up right uh we're starting from the last now we're starting from the second and last of the from the bottom basically for each of the eye here we all we always pick the smaller uh from his from it from this like element adjacent numbers right and then we just keep going up until the first until we reach the uh the top one then the top one will be our final result so i think obviously it's going to be a dp problem right uh let's do this let's do let's define a height first are going to be a length of triangle right triangle not triangle and then for dp let's do a let's define a 2d dp for now right so the dp means the smaller uh so basically we define like each element right for each element we define like an a number right and for each row on each row in this dp will be the level on this triangle and the inside will also define like a number for each of the elements in that row so at the beginning everything is like zero right and then at this ice height right uh basically the length is gonna be the length of the row right and then for what for rho in triangle right that's how we define this 2d dp basically we just define like a simple array a 2d array with a position for each of the element of the in the triangle here right and then what and we start from bottom but we know from the bottom right the last dp minus 1 right the minus 1 is equal to what is the same as the triangle right it's the same as the triangle basically because for each of the elements for every element on the last levels the distance basically the path to this current value will be itself right because that's the first step and then we do a for i in range right what we do a height right height minus two minus one right basically we'll loop from this one from the last one from the bottom then for j right for j in range for each of the element of the current level right what's the lot the level that's going to be the length of dp we can either use dp or triangle it doesn't matter because dp and triangle they have the same structure i'm going to use the dp in this case a dp what a dpi right so that's the current element on current row and the dp i j right equals what equals to the uh the minimum right the minimum from the previous one right that's going to be dp what uh i minus 1 i plus 1 right that's the height to j and we get the lesser one from the pre from that previously previous iteration numbers right dp i plus one plus j into j plus one right and then which in the end which add the current triangle right that's the current number of that all right let's do it over in until the end which we simply return dp zero and zero right that's not going to be the that's a bit our result because at the first level there will be only one and this one will be our final result and that should do it yeah cool see it's pretty straightforward and i think one of the bonus point or follow-up follow-up follow-up question is that if you can use like o n here right because right now what is this the space complexity here that's all uh n log n right that's a total number in this where n is the total number of the rows of in the triangle uh i'm not sure if we can do this but one of the improvements we can do it here is instead of using a 2d array right we can only use like yeah i think that's the uh yeah we can do it with o and n is the height right how we can do it right because all we need to do is all we need is the last the space of the last row here right because once uh once this like this number is calculated we don't need this calculated we don't need the previous level uh numbers we can just keep using the same level over and over right so we simply we just simply do this right we just instead of defining a create a 2d array we simply initialize this array with the last it's the last row right and same thing and here so here we're going to have the triangle here right then dp high here so with that we just need the dpi that's the level and that's the triangle of the level so dpi yes dpi equals to a dpi plus i plus 1 j let's see so it's going to be dp yeah j right dpj dbj plus and dpj plus one basically we're just reusing the previous uh numbers and then in the end we just return dpi zero right i think that should also work dp oh yeah okay sorry so yeah so that's going to be dp of that yeah so this like so this will reduce the uh the time complexity from n i think what's the total number in the triangle here and log n to n because we're just simply using the same uh reuse the previous like dp result right with updating keep updating uh from the previous result and the current result the so before assigning this one this is the last level's result right and then we just for the current one we just reuse the previous levels result and then basic same structure but which you reuse the same uh dpo right here and in the end which same just return the first element that will give us the final result and yeah i think that's it for this problem yeah thank you so much for watching the video all right i'll be seeing you guys soon bye
|
Triangle
|
triangle
|
Given a `triangle` array, return _the minimum path sum from top to bottom_.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row.
**Example 1:**
**Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\]
**Output:** 11
**Explanation:** The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
**Example 2:**
**Input:** triangle = \[\[-10\]\]
**Output:** -10
**Constraints:**
* `1 <= triangle.length <= 200`
* `triangle[0].length == 1`
* `triangle[i].length == triangle[i - 1].length + 1`
* `-104 <= triangle[i][j] <= 104`
**Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
| null |
Array,Dynamic Programming
|
Medium
| null |
27 |
so let's see how to do this lead code problem 27 remove element so what they're asking us to do is we have an array in this case we have four elements in an array then we have a Val which is three what they're asking us to do is find all the instance of this well and remove that so in our case we have three so they want us to remove this three and that three and at the end you just count how many elements you got so let's see the solution so here we have a functional remove element which accepts nums and well we have a counter which starts at zero so first thing we're doing is looping over this array and what we're trying to find is the value that doesn't matches so over here we're trying to find the values it doesn't match and we are adding those values to our nums array and just incrementing the count and if I run our code we get to independent
|
Remove Element
|
remove-element
|
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`.
Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things:
* Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`.
* Return `k`.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int val = ...; // Value to remove
int\[\] expectedNums = \[...\]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[3,2,2,3\], val = 3
**Output:** 2, nums = \[2,2,\_,\_\]
**Explanation:** Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2
**Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `0 <= nums.length <= 100`
* `0 <= nums[i] <= 50`
* `0 <= val <= 100`
|
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
|
Array,Two Pointers
|
Easy
|
26,203,283
|
389 |
hello and welcome today we're doing a question from wheats co2 called find the difference it's an easy let's get started given two strings s and T which consists of only lowercase letters string T is generated by randomly shuffling string s and then adding one more letter at a random position find the letter that was added in T example given the input s equals ABCD and T equals ABCDE we output e since E was a letter that was added to T now one obvious way to solve this would be to store all the letters in T and as we read in s to remove them so the one letter that would be remaining would be the letter that was added but is there an efficient way to store all these letters well what do we know about s and T we know that besides the addition of that one letter in T S&T you addition of that one letter in T S&T you addition of that one letter in T S&T you hold the same letters and the same values so if we were to somehow sum up all the letters you would get the equivalent sums in both s and T say for that extra value and can we do this we actually can sum up all the letters we can get their number equivalent using the ASCII conversion and simply subtract the sum of s from the sum of T and return that number converted back to a letter so let's just go ahead and code this up so I'm gonna initialize T sum to 0 this is gonna tour the sum of all the letters in T so for I and T C sum plus equals ORD of I so every single letter in T converted to its numerical equivalent and for I NS t some minus equals or D of I and now what I want to do is just return that value in T some convert it back to a letter so return character of T some run code accepted submit and it is accepted so talking about time and space complexity this would be order o of n plus M for time it's just one pass through both SMT and we're using constant memory and space so that's over one space as always let me know if you have any questions otherwise I'll see you next time
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
334 |
all right what's up guys it's fox from code bros and we're going to talk going over top interview questions arrays and strings question number six and raising strings which is increasing triple a subsequence so given array of numbers return true if there's exist a triple of indices i j k where i is less than j is less than k and num's eyes are some numbers j is less than numbers k if no such indices exist return false so over here like you do one two three four five because yeah it's all increasing then over here everything's decreasing so nothing exists there um over here do you do zero four six or you could do yeah zero four six works but what you need to remember about this question which is especially important is that these uh indices i j and k don't have to be consecutive they could be like eyes over here j is over here k is all the way over here so that's what makes this problem specifically a medium problem and not just a easy problem and they want us to implement it in on time complexity and on space complexity so wait let me just uh that was from previous attempts so let me give you an example which i think is a really good example that really explains the complexity of this problem so first off it's pretty evident that we need a we need three indices which are let's call them int min medium and max and these are the indices that we're looking at um so over here int min would be 10 medium would be 12 and max would be 13. so the hard part about this problem is or the medium part about this problem is how we're updating these values into mid min and max so let's just set them all equal to negative one because they're all indices and we know that indices only range from zero to length minus one so negative one just means that okay we haven't seen a value for this yet so when do we update min we would update min when min is equal to negative one or the value we're looking at is less than min so if the current value is less than min okay that's great and what would when would we update medium well it's equal to negative one or the current value is greater than min but less than medium um and one more time we would update the min value this is actually the tricky part we update the mid value if we see a value when we have min and mid already initialized but min is less than the current min then we want to update it so let me just run through this example here we have the three cases we have let me just copy this all right so over here we can have min first that is 20. they're all unique characters so we'll just use the value instead of the indices um then we want to update medium which is 100 then we see 10 right so think about it if we see 10 and we see a number greater than 100 then we've already found the indices 20 100 and like let's say this was 120 okay and we didn't have the rest of this array so if we see this we want to keep 20 and 100 stored as the value we've already seen and when we see 120 we want to return true right but we also don't want to just ignore the fact that we found a number that is less than the min so over here to account for this case we have to update the min because the current value is less than min and this also holds the property because we've already have the medium set as this so that any value we've seen greater we still have the previous triplet uh in our minds and then we see the value 12. so 12 is greater than the current min value and less than the median value all right so why wouldn't we just update the median value because any value that is greater than 12 is also greater than the 100 because the current value is less than the medium so let's update that 12. then we see five same thing same idea here you want to update the min value but the medium keeps the reference to previous triplet and then uh then we see 13 and we can just update 13. these are our final values of mid medium and max and they're not even in order they're not like is less than js less than k we just because this uh a question is only asking for a boolean answer if it was asking for actual three values in the uh array it would be a little bit more complex but since it's only asking for a boolean answer we can just return true or false and use this property where mid keeps the previous triplets uh state which is we found two values and we need to find value greater than this one so now that we have that out of the way let's look at the time complexity oh we don't even need a max because once we found a value greater than the median value we found the max so we don't really need this and then we can just return true in that case um so max is like a theoretical value so if value if curve is greater than mid then you want to return true okay so let's look at time complexity obviously since we're following the follow-up we're going through the array follow-up we're going through the array follow-up we're going through the array of n uh numbers which is o of n and space is all run because we only need three pointers mid and medium and we don't even need max is just there for uh the sake of explaining because this is just really an if case if current is greater than mid return true all right so now let's start going to solution uh one thing to know is that they want strictly less than so not less than or equal to it has to be num's eyes less than nums j is less than numbers k uh with that let's start coding up the solution so first thing we want to do is set a min value uh initialize that negative one and a mid value also initialize that negative one that should be a comma and y is a negative one because we want to show that it's uninitialized index and negative one is not a valid index next thing we wanna do loop through all the values cool when we update min is when min is equal to negative one or we can just look right here uh or the current value is less than min so num's curve note we won't get a out of bounds error because we detect if min is equal to negative one in our first condition then over here we're going to update min all right so when do we want to update mid which is the middle value over here i don't know why i wrote med before but i fixed it all right we want to update min first off the value has to be greater than the minimum value so first condition is numskur has to be great strictly greater than all right next condition so if it's already greater than it then there's two cases one case is the middle values uninitialized or the second case is i'll show you in our example that we did before 20 100 uh update min 10 12 or nums cur is less than nums mid so just like over here to mid over here you want to update mid last case is we want to check if the value is greater than mid otherwise once we go through all the values and don't find anything we want to return false and i'm gonna just give you guys this as a disclaimer because it was an edge case that was messing me up before um what if we had some values which were the same so if we had one and then one over here we wouldn't update the middle value and we go to this third case and mid would equal to negative one so if we had one we'd update min then we couldn't update mid and we go to the next condition and num is negative one which is an invalid indices so we have so that causes out of bounds error right so we want to make sure not mid is not equal to negative one and arrays go from zero to the number of elements minus one that's how they work all right cool and this should be good all right so our expected test case passed our initial test case my bad it was accepted so thanks for watching big thanks to patrick because he helped me with my mic settings they were all messed up before like if you guys saw my old videos it was bad but i recorded these ones because it was extra bad like horrible but so big thanks for him thanks to him like the code is always in the description of the github link if you have any suggestions or questions or just suggestions on what videos i should do or what problems you have a lot of trouble with please let me know in the description and it's always appreciated feedback's always appreciated so thanks for watching i'll see you guys in the next video
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
7 |
uh ladies and gentlemen uh we're gonna look at another question in the lid code problems popular problem series this is question number seven how to reverse an integer uh again this is a very popular question so we're gonna look at a solution algorithm and the approach all right so let's get started uh so if you go to you will uh so if you go to you will uh so if you go to you will find this problem if you click on the problems you would find this question number seven reverse integer it's an easy question according to lit code you can see it here but remember whenever they say it's easy doesn't necessarily mean that it's easy that's because there are always some constraints and if you follow those constraints then it starts to become difficult so just be mindful of that okay so let's look at which companies are asking this question if i go here at the bottom and so i would see you know facebook amazon apple google uber all the good companies are asking this question and let's say if you're interviewing with one of those companies or a company that is not from this list usually they are looking for questions to ask and they're not going to just uh you know randomly create well some might but mostly they might pick one of the questions from top 50 lit code questions and you know sometimes they modify sometimes they ask as it is so if you get lucky and this question comes in so i would recommend you to go through this entire video to understand the problem given assigned 32 bit integer x so this is an important part to remember sine 32 sine means it could be a negative or positive a variable called x returns with its digits reversed so if i have 12 it becomes 21. if reversing x causes the value to go outside the signed 32 integer range which is again 32 bit is you know 2 raised to 31 and that returns zero okay so if it's going outside this range it returns zero assume that the environment does not allow you to store 64-bit integer allow you to store 64-bit integer allow you to store 64-bit integer signed or unsigned that is why we are limiting to 32 because we cannot store 64 bit integer right so you read this usually multiple times and try to grasp uh all the key information from here and usually i would not rely on lit code example or if you go for an interview they might just give you a sample example or they won't they may not even say this right they may just say okay this is the situation now deal with it right so it's your duty to ask this to the interviewer saying okay uh what if it's a negative yes because an integer it could be negative you preserve the sign and reverse integer so you get a minus 321 okay good what if the last digit is zero then you reverse it you ignore the zero because now zero in the front zero 21 doesn't make sense so you return 21. okay good and obviously if you have zero which you return zero and one other thing they haven't mentioned here reversing an integer it's pretty simple if you can convert into a string right and you just flip the string and there are built-in functions to do that there are built-in functions to do that there are built-in functions to do that but if you're not allowed to do that which is a restriction and i guarantee you that will be the restriction when they ask you this question then this question becomes a little difficult all right so let's get started one of the first thing you want to do if you get this question or any question in an interview you want to first write down all the possible test cases all the weird ones and normal ones and then you want to build the algorithm uh you know on a paper uh and using a pen if you have a computer like this you can do it right there just as comments and then follow the algorithm to write the code if you jump into the code from the beginning as a lot of people do what would happen is that you get lost in the code you get stuck and then you will panic and then you would say oh i don't know how did this happen right so let's follow the process so let's start with some test cases uh if you are given let's say 123 obviously you're gonna return to one three two one right if it's minus 123 then you would return minus three to one uh if you are given 120 21 given zero then you would return zero and then if you're given the biggest uh 32-bit number a positive one then you uh 32-bit number a positive one then you uh 32-bit number a positive one then you would return zero and also either it's positive or negative you will return zero right so this is your pretty much covers all the test cases uh let's think about the algorithm uh now these two are actually edge cases so you don't have to worry too much about it right now but you want to cover it first right and these are normal cases how do you deal with negative number if you notice that the difference between these two is just a sign first figure out if something is positive or negative remember the sign and then reverse the positive number and then put back the sign this one is just like the first case except you would get 0 2 1 and then you can convert into integer that give you 21. so that's pretty simple because it's a number how you reverse it right the first case in order to reverse it let's understand what this 123 is made of so if i split this you know in a mathematical sense then 123 is nothing but 1 multiplied by 100 plus 2 multiplied by 10 plus 3 multiply by 1. now all i have to do is if you want to reverse it reverse the number keep the multiplication as it is right so if i just take this and just reverse the number which means three two and one i would need to get each number and then uh do this format okay so how do i do that to get the length of uh a number uh you can use log 10. so math library inside javascript has a function called log 10 and this would give you the log of whichever number so let's say if it's a 123 then it would give you 2 which is 1 less than the length so all i have to do is if i just add 1 to it this would give me three the length obviously this would be two something so i would have to also convert into a an integer so i would say parse and then this and if i console log this i would get three so this is how i can get the length okay so that's get that's out of the way i'm gonna remember this uh the next thing i want to do is how do i get each digit from here let's say if i want to get one out of here right then what i have all i have to do is so if i take 123 divided by 10 i need just to need to divide by 100 and this would give me one something right so if i 100 is nothing but 10 raised to 2 this is um a cool syntax 10 squared 10 raised to 2. and if i console log this and run this i'll get one uh 23 and if i made a typo let me run it again okay i'll get one so this is how i can get it each digit uh one by one all right so let's get that going so my objective would be looping through each number by parsing this information removing that number and the remainder would be then 23 removing two then and removing three okay so let's get to the coding so i would need a function let's call this reverse which takes an argument s x as an argument and it returns the reverse number and if i let's say call this let's say 123 it would return me 321 okay so we're gonna implement all the logic inside here so first we can get that uh the corner cases this two cases out of the way let's say if the x is less than all right or x is greater than positive number uh 2 raised to 31 or it's zero in that case i'm gonna return zero to test this out if i just well they're supposed to be seven is supposed to be triple equal sign it's a comparison operator not an assignment all right so you get a zero which is correct so all three cases would get zero so let's not worry about that now so we're gonna look at now the normal case which is this okay so for that i would need let's figure out if it's negative or positive if it's a negative then i need to preserve that negative value right so i would say const is negative equal to i can find out by comparing to zero if x is less than zero then is negative is true else it's false simple right then i can take that number and then convert it to positive if it's negative if it's positive then it will stay positive but i can just do it anyway so i just say const let's call it p int math.absolute and i let's call it p int math.absolute and i let's call it p int math.absolute and i can just pass x here okay so this is now positive and if i pass minus 123 the p end would be positive 123 and we preserve the sign inside this is negative variable all right now let's get the length we already have this here so we can copy and paste here that which we figured out so const length equal to this so that is simple and then we need two variable the final one that would we will return so we need to initialize that so let's let final equal to zero and we also need a remainder because uh remember we're gonna take one number by number so in that case if i take remove the one then i would have remained at 23 and then i would take 2 and then remainder 3. so i would need a remainder so which would be initially same as the x so i can say remainder equal to which is nothing but the positive x i can start so all i have to do is loop through the number uh we're going to loop through from the reverse from the back right so 3 2 0 2 1 and 0 equal to the length so i'm going to say length minus 1 so that is 2 equal to 0 run till 2 1 and 0. subtract one from it so i minus so write console log and run this would give me two one and zero right two one and zero i'm getting undefined because i'm not returning here right now so that's fine don't worry about it i can call this digit equal to as i said i can take the remainder which will be initially the whole number divided by 10 raised to i so initially this would be 2 so i'm dividing by 100 and i have to do the parse int this would give me 1 right so digit is 1. now how do i get the remainder would be and i would do 10 so if i take the whole number and instead of just dividing if i try to find what it would be the remainder right so if i divide 123 by 100 i would get 23. so that would be my remainder so i'm splitting into two 1 and 23. so 1 would be the digit and 23 would be the remainder and then for the next loop the remainder would be 23 then i'll split out two and the remainder would be three and so forth and the next thing i need to do is a multiplier the multiplier would be equal to what we can do is 10 raised to we can take the length minus 1. so this is 2 minus i so for i equal to 2 this will be 0 so we multiply one uh with one two with ten and three with hundred you know equal to final plus uh we can take the digit and then multiplied by mult and then if i just console log this right now i would get 321 which is correct right however if i pass minus 123 this would not work right so i need to put that sign back so what i would do is return if it's negative in that case i wanna return minus final else i wanna just return final so now if i run this i would get 321. now let's try 120 and what do we get 21 so it also works now there is a little better way of doing it so in the next video which is a little different than this but i will show you the different method as well now let's look at the complexity of this algorithm what is the complexity of this algorithm well for three digit number we are basically going digit by digit so we are visiting each number only one time right so the algorithm so the complexity of this algorithm would be o of n where n is the length of the number so it's a linear algorithm and i don't think you can do better than that because you do have to visit every single number if you want to reverse it all right so that's it folks i hope you learned something new from this video and if you did please like subscribe and provide a nice comment and you can follow me i have a facebook group where you can ask questions uh which is on algorithm and data structure in javascript specifically you can follow my youtube channel other channel this is my actually interview nest is my second channel my primary channel is techsittube so you can follow that and if you need help uh in terms of you know getting trained if you're giving interview and you need help um i'm planning to have a small session like hourly session with very minor fees uh where i can you know teach a group of people algorithm and data structure in javascript uh you can join this discord group uh to get more information and just in case of this discord group uh is disabled let's say uh for a few years from now or something like that feel free to email me my email is in the channel and thank you for watching
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
1,026 |
okay so lead code practice time maximum difference between node and ancestor all right so again two goals the first one is to see how to solve this problem and then we are going to put some code here and the second one is how we should behave during real interview so let's get started so remember the first thing is to always try to understand the question itself what it is asking us to do and also at the same time think about some ash cases if you have anything that is unclear to you please bring up the question to the interior and ask the interior to clarify um yeah so let's try to read through this problem so given the root of the binary tree find the maximum value v for which there exists different nodes a and b where b is equal to a dot y minus b dot value and a is an ancestor of b all right so a node um a node a is the ancestor of b is if either any child of a is equal to b or any child of a is an ancestor of b okay yeah essentially like a and b is on the same path so let's take a look at this example we have this tree and we have like those two knows the shirt so three has the ancestor eight so the difference is five similarly three and seven and eight and one ten and uh thirteen well um yeah so the largest one is seven okay i think i pretty much understand what the question is about and uh let's see the constraints so the node value is so node is going to be non-active uh node is going to be non-active uh node is going to be non-active uh integers so the number of nodes in the tree is between two to five thousand so for sure not to be an empty tree and for sure um there is there are at least two nodes all right so the next step is about finding the solution so what will be the solution for this um so for this one i think we could use some dfs thing recursion and so what we pass into it is the current maximum value and the current minimum value uh on the pass so like so you remember like d for your dfs um we just go as deep as we can to one pass and then search the other pass so it's like when we search through this path we just try to at the same time we pass in two things one is the maximum value and the pass and the second one is the minimum value of the pass and then at the same time you just compute the absolute value between the maximum and the current node and the minimum on the current node so for sure it is going to get us the largest difference between the nodes on the path and the current node all right so um this one we are going to visit all the nodes so the runtime is going to be open and there is a number of the nodes within the tree so the next part is about coding so for coding uh speed and correctness and of course the readability all right so let's see for this one max ancestors and max and sister dave and tree known as root okay so let's see if i define a helper function let's call it the effect or is uh max and let's just overload it so if this is a trino root so this is a dfs function i talked about so let's define its ancestor the tree node this is the root and um max value and this is a min value all right so um for okay so this one is going to return into so first let's try to see what is the axis of it so if it is uh if um root.left is equal to none um root.left is equal to none um root.left is equal to none and root that's right is equal to none which means it is a leaf node then uh what we are going to do is we are going to um return um so return so you're going to return mass dot max root dot so mass dot abs uh okay so abs root dot value minus max value and the mass dot abs um dot value minus main value yeah so if it's a leaf node that's it and if it's not a leaf node what we are going to do is um so if it's not a leaf node um if it's not a leaf node we should first see the left and the right so it's left max is equal to max and sister dave um max left let's say it is equal to minus one so if um left max sorry uh if root down left is not equal to none so left max is equal to max ancestor uh this is root dot left and we are going to pass in the um max um the max value and the current root value it's going to be so yeah so it's gonna be a mass value and the root dot value and this is mass dot mean um main value and the root value yeah so we pass the max and the min on the path of it yes you go to the left and then yes that's correct and similarly we are going to have rent max as equal minus one so if uh right is not equal to a none pointer then right max is equal to max ancestor from earth right and yeah so similar things like this and the next thing is um so the next thing is we yes so the next thing is we are going to try to compute for the current node what's the difference between the max div between the current node the value with max value and the mean value so let's say um right is equal to okay so in car max car value is equal to mass dot max mass dot abs root dial value minus the max value and mass dot abs root value minus main value yes so that's the current thing so it's um all right so current let's say it's current max value so if car so car max value is equal to mass dot max current value was the left max and the red max and we finally returned the car max value all right so let's see so let's take a look at example for testing so remember after coding always test your code so first you need to go through a piece of example and explain how this gonna work at the same time do some sanity track checking the logic about different branches this is about communication testing and then after you feel confident and your interior feel good about this piece of code it's time for us to set up some different test cases to increase tax coverage so let's see for this one um like this tree we are going to say okay left so starting from eight we are going to call root and eight and uh because it's not the leaf node and then we are going to go to the left tree uh so currently max ancestor is equal to so we are going to call um the this the note passed into it and eight and uh we are going to so when we call it this uh so regardless like other things which are like get the left max on the right mics the thing i currently know the car we compute the car max as equal to uh eight minus three and eight minus three so it is going to be five here all right and similarly i would say this is just a like a replication on the left tree and the right tree like doing same operations so i think it should look good let's give it a try all right so it's good and all right so everything looks good so this is pretty much the pretty much about the question and the solution so if you have any questions about the solution itself please leave some comments below if you feel this video pretty helpful please give me a thumb up and help subscribe to this channel and i'll see you next time thanks for watching
|
Maximum Difference Between Node and Ancestor
|
string-without-aaa-or-bbb
|
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105`
| null |
String,Greedy
|
Medium
| null |
1,046 |
Hello everyone welcome back to me channel once again and here we are going to talk about the problem of daily challenge and today's problem is basically from the easy problem list so the name of the question is last stone weight so read the question what is the question It is saying that you have a stone, wait stone, and for that, where each eye element is, it is telling the weight of the eye stone, okay, a game is being played, now basically what do you do in a game, the rule of the game. It is something like this, whatever container you are, basically here we are talking about payer, then it is fine and whatever is the second largest right, then in this way you have to choose for that, now what is the problem that if After choosing, see what you have to do. After choosing, see that if Meaning, if you look at it in a way, the equivalent is coming to an end, so here if If you keep doing this then what will happen, in the end you will have Atmos One Stone. Okay, what is the meaning of eating Atmos One Stone, if there is more than one stone, then this process happens again with both of them and after the process is done, either Student savings are either not saving, so if you look carefully, first of all, what is happening is that if both the stones are getting destroyed, then the stone is not left behind you. Look into this, if one of the two stones is left back, weight is being taken, then weight is being taken. That if we do not talk about only the number stone, then here one stone is being lost and here both the stones are being lost, in the end you will either have one stone left or no stone left. Return D Weight of D Last. Remaining stone, if there is no saving, it is possible to return zero to your mother and son, then its weight has to be told to us, what happened, okay, so look here, now let us first think about the time stand and also look at it is quite small, so If you want then I think this map means I have done it for you here but if you want you can also do it with vector because the length of the string and the stone is enough so it will not make much difference but yes if this question is You do it a little bit, son, basically what is happening to us is that every time if you are a vector then what will happen, every time you will have to short the vector and from there short in decreasing order. Okay, so is there any logic in this? It is not possible for me to explain it separately. Okay, so basically the code that is your round has the complete logic of the round. Okay, so see, now when you did it in short decreasing order, you want the first largest, then your first largest is the second. Is the largest pick within the stand key or an element or not? Okay, now you will erase both of them, after that the minas of these two, if given greater is zero, then you will put it in it, again you will have to shorten it, then this thing. It will happen again and again. Okay, because the constant given here is touch, so again after removing it, that element will become the largest. I want this method, if because brother does not have a problem, but because the question. This completely matches the direction I see of choosing the largest element so it's better that you go with this because to capture the question you have to learn what the question is asking. There are alternative methods but If I tighten the content and do it, then your alternative method will fail, it will be less, if the hip will come less, it is okay, here you will get the steel seat, which I have started in the center of the video and what is the top, which is always the largest, basically you can see it in the video. See, it's okay, so this is what I need here, so what will I do, I will make a temporary hip container, it is ready, I inserted all the elements in it, I am okay mother, take this PK, I have given it a name, so what will be the size of the PK? Ok, whatever size PK will be, as long as it is greater, it will be one, because what he said is that what will be left in Atmos last will be one or less than one element, so I have to keep processing till there are two or more elements. You can also write it in this other way, give it a grater, it will be equal, till the time it will run on the file look, now what will happen if I do two best, then there will be more butter, see why here and sir, you can do it in this way. Put the pulse in it, let's go into the container, let's do the opposite, brother, one should be here and one should be here, right, so after both of them are here, this will have to be popped. Now if one note of the constant is equal in between these two, then A. If it is their difference, then if their difference is not there, mains note is able, then I have done this to you with the difference and as long as it continues, you will keep doing this entire process, then the last of 30 elements. What you will get finally is whether there is an element in the vector or not, if not then return zero. If yes then we are accessing the top. You cannot directly print it and return it. Why because it is not known from this. No, do we have the size in it or not, if MPT is there in the video, then in this video, these questions were like very easy ones, okay, and in the last two-three days, very good and in the last two-three days, very good and in the last two-three days, very good questions had come, you got a lot of DP questions. I was learning from him, okay, so let's see which question comes the next day and then we will discuss it, so in this video we keep only this much and all the related links are given to you, whether it is of steel seat or of the code of the question. I have given the link to the discord server in the description box below, ok, watch it and enjoy.
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
114 |
Hello friends, I am Sharad Dushman, the special convert binary to-do list that has illuminated the country at the national level. It is a very famous convert binary to-do list that has illuminated the country at the national level. It is a very famous convert binary to-do list that has illuminated the country at the national level. It is a very famous interview question, it comes much later, it is a generic question and within the meaning of tu karne ke andar jo tareetha hai and kimam tareetha jo hai it is necessary to understand the flight. This is your request that the youth is about to start, the portion price is for you guys, basically once you have to delete it, you guys are converting it and it is very easy, we will convert it, okay, how to convert it? If you tell me to do then first there is a single stand, you are correct that the one that will be out of yours should be your inorder traversal road. Okay, so this is the basic - if its Okay, so this is the basic - if its Okay, so this is the basic - if its Delhi is liquid bane, this will be the in order for this industry, right like if I told you. If it has then it will be an inverter. We have seen earlier that this is the Inventivo Depot site. We have seen the spring. If you people do not know that instead of inserting it there, after that you will go to some lotion. Okay, so you guys, basically there is a sticker option inside the lunch. So you guys do it right, I have an ignore in it and let's put the note in our list, okay but inside the question there is a cotton center, what is that, you guys can't use a space, okay you guys Already white vinegar, the notes which are life, only those notes have to be converted, inside a link from, okay, now non-increasing from, okay, now non-increasing from, okay, now non-increasing notes can be made, inside them are your points, previous pause, next, which is here, electrolyte, so he has said. Whichever point is on the last point, make it off, so whatever right conductor inside it, you can make it next, okay, so basically the points will remain the same, still here too, its left, this is its right, okay, so don't get confused. The penis has to be inside it, your previous position is next, but we are basically changing their names, I will be there, left and right leg, with this note, you will convert it into this thing, okay. Now basically if you make it flat then this letter no entry type becomes president then flat no entry then convert them into trouble in English. This is a question and there are multiple ways to do it. Today I am telling you a very effective method by which you can The knowledge of the requirement will increase and the physical improvement of Hrithik Roshan is a very good advantage, but he is a jeweler, he is giving some examples, then let us see the support. If you had such a body, pick it up here but it is there, then you will get it in this way. Line and traversal is family. If you people like this then when there is no left part then you would enjoy something like this. We know how the inverter works. I know the important aspects. This note goes to your friend. Android suicide note. Can you why keep here important aspect gone but there was nothing on the left side so we went to the note nodes are our alliance on the right we will pay attention we will further make changes for this then we will adopt the phenotype for this dead skin tightening feeling should be noted Instead of writing the loss, director, there is nothing, after inspection, one came here and it was against him, now we will print this note in the night and then we will press the night one too, okay, so the separation and traversal is happening in this way now. I write the family code for those who listen to the office and Shyam who understands Krishna's fund very well. Here I have quoted the dip, which looks like a very small product, a slightly different type of horse, but the meaning was that you will understand it. Before going to sleep, give a soldier shot to the developer, then we should remember the basic fund of the request, what is it, first send the basic, after that you have to make a relation between parents and students, generalize it with you and generate it. After this, you can fold that thing from the side, we are going to run it here also, we know that we have to convert it into inorder traversal Chandra is important Kavita, first you go left, do some work, you process the mode on the side. Just look at IS thousands of times, you do the same work in the same court and it is written here that you people first ruined the country and then left it, after that you processed the route, its crime is forgiven, ok, the product is very simple, now this is the problem. How are we working? Okay, so here we have some work to do on the left side of the player's end and after working in the lab to understand this, you guys like the previous note will be updated here. Okay, I have created the previous note in stages because Whenever you delinquent children hands, you people, it is important to know the address of Chittor, what do we do in height drinking, all friends, you that this was your two have noted, God and two and this is your professional, okay now the episode is for you. If you can get it, when you do n't have to enter any one, all of them have been put in the form here, then how can you sell it and it will become right, this is the current mode and then one of the best modes of the current affair, I will fold the previous one, this front is premature. Whatever you do and in reality you are the element of the same coin than the one who put it here otherwise I will tell you how to do the work, first of all you will go to the left and do some work, you will want to make the previous one your own, then it means This is that the ticket picked up on you guys will update these okay so this is going to come if drink before this there was tap that alum please subscribe jagriti mission and so you guys set them valley national so you are on that current Come, collect the route of the explosive, put the previous and the princess, the road will be cut towards her, if you start updating the previous, then definitely call her with a bicycle in your hands, okay, this is the only work, if you understand the pain properly, then did you guys start from here ? If you want to get angry, you don't want to get angry, ? If you want to get angry, you don't want to get angry, ? If you want to get angry, you don't want to get angry, then it's okay, then we used to come inside and do quad, so this is the left side of it, okay, we have done Africa again, what is the form inside, if you have a tap, then you don't want to get angry, okay, so let's open the left side, now here is the layer. If you want to select, then a call will be made. If Ruthna is well, then we will return it. Okay, then you will get it from this channel. Okay, then after that, it will go here. Okay, it will go inside. If you are an email, then we are professionals. We are pieces of clay. This is saliva, so everywhere it puts five of the backward people here, the sign of that person is to move towards criminal, this is yours actually, you have vitamin superintendent fruit in it, now fiber will come please Redmi 5a white and you have opened it for the website and its deadlocked. The tap will help reduce even during overnight hours. Okay, so from here this note has become its full member, now to whom will this note go because now he will do his profession for the oil left in it. Okay, if you are a professional then please channel. It is not okay, if you read the account of the root, then you have to get upset. Basically, it is okay, Firoz has become and is previous and given heavy, okay and this fruit is root 's Africa, it will come with 's Africa, it will come with 's Africa, it will come with serious problems, this is his mother. We will just update the bus, here the footprints of will come here, you must do this and together, if you have done this, then the society has done this work, it has done its own processing, it is okay for Amazon to work, so in this way, it will do it automatically. This will last for years here and father let me tell you the money is being ticketed, by the way, such a rich person, if you see that yes, so many of ours are running from here, if you also solve this properly, this and last year and there is more of that. After our base, it is getting started, this is one more thing, then all the rest automatically, there is no need to complete the vacation assistance again and again. Okay, time is also wasted, but once we do it, we are right for the nation. Who is here, he is the president, he is upset, if he doesn't get upset, then who will do Tilak terminal, then he will go here, then you see, he will be upset, he will go to the doctor, open it wastefully, open it and go here, he will come back for free, you, this person is fine, now I Here I have read it is fine and it is professional, then there is this drain, so if you drink Aishwarya's hot collection here, then the current is this, its passenger bus has this note separately, okay, so here basically this is the hero, but the one to the left of it is Please set this previous and P Expert and Mysterious. Please say it is ok then it will crush the inverter automatically. Here it is done. Now after that it will grind and it will do its dance then ok. Its very which is basically left and right. Right to Recall will be set here in the world, this will work from here, I will put the education, okay and the preview will go to the previous, after that it will front it will do Britain and then it will do its process and it will do that JP Mishra is Satish Nal, it is saved on the side. This route will be followed by its target so its will be this and its benefit will be this and then the previous one will return you starting from here and then it will return the point and after this happens the hair you will get will be your central Answer: hair you will get will be your central Answer: hair you will get will be your central Answer: Roti head anytime and hand crank honey in the beginning, it is right that we have started hunting, so in this way the previous one also becomes good and inside this, it is a request to you that the new thing resides in this. That basically if you want then keep updating some of the points which were passed out by your friends on the journey of the record schools, okay then you can add them globally outside, okay so like I have sacrificed the previous ones from here so that This change can happen inside every developed Paul. These changes are happening inside the undeveloped call. Previous events are getting changed everywhere, so in this way you guys can design outside also. If the reverse is ok then it is clear. That question and the question inside it is very good, why did you find the need for a hunter? After this, we will see the idea of some more advanced After this, we will see the idea of some more advanced After this, we will see the idea of some more advanced courses. Even if you like the video, then do like the channel. Now let's go to the nails, so I am that a
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
1,716 |
Hello One So In This Video Will Solve There Problems 1716 That's Calculate Manish Ko Time So Let's Go By The Problem Statement First House I Want To Say Money For His First Car Reports Money Dalit Vote Bank Everyday Star Spotting Aur Lavan Deputy Everyday From Today I will support and always one more 1034 on every subsequent Monday $15 mode one mode on the Monday $15 mode one mode on the Monday $15 mode one mode on the present in giving and returned the total amount of money will have in Dalit vote bank at the end of and stay in a statement in the houses of money to Buy His First And Every Day With Increasing In The Bank Money According To Destroy Every Day For Increasing At 10am Dollar Then On Monday Everything Fitting Dollar One And Every Day With Increasing The Amazing $1 Mode Show Light On Witnesses Posts 4,805 Witnesses Posts 4,805 Witnesses Posts 4,805 Saturday And Sunday Loot 700 Guido Lavan Mode On The Everyday From Do Half Hour Egg And Sorrow Of Example Number One Backstreet Boys Ka To 400g The First How Much Money Is Catering To Active 123 602 nh-24 Total Amount And Example nh-24 Total Amount And Example nh-24 Total Amount And Example 210 First Three Days From 6021 3330 70 237 Ab To Aadat Si Problem Statement In Which Will Have To Do The Total Amount Darcis Cutting Back Saw How Can Solve This You Should Decide What We Can Do It Will Keep Calculate The Value Of Do That Also to develop a 200 and will reduce to do the value of but and so they can be updated on em back 7 is so awat is advance alike for the first chief of his feelings after for the country for V0 451 Sql Tours 0.2 a Aa hai ya so ahat similarly develop a soon develop will be and model on 7 I soft positive idea interference for it's quite well into light on 6060 chain 7.10 7.10 7.10 statement do 200 values of condition and hai to shubhendu that this dress value do it is equal to 10 can do that behen de villiers equal to ka sex 200 wide its and is so in the case of the total value bone calculating seven more visible 10th 12th value a plus we are so applicable for any requests of wave 6600 divine grand Subscribe Now To Things That Is The Value Of For Water For All Us Wash Used Oil Will Do That Thing Will Return To Ooo Hai Ya Sona Let's Have A Dance Class That Aapne Friend Follow Us Is To Thanda The Liver Shrinks To Point Is Equal To One Style action equal to and half inch plus the week is 12345 on two Android 17 eggs busy to unmute election or aa try swift voice over time record orgasm suli is time I thing in the remote a sort of in the value Mr hours 0 and your This relinquished w2 sex that today water into new latest total valley on a treatment difficult to debut on me that and attend school return to tilt were that this show person 2018 se val value anand vimal total value bihar setting use calculating value for every i M 16 Pure Her and Also 182 and Effective Pure Capital and Effective Video then subscribe to the Page or Sweep Eight No Late Semester Subject for Quite a Specific or Research
|
Calculate Money in Leetcode Bank
|
maximum-non-negative-product-in-a-matrix
|
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**.
He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**.
Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._
**Example 1:**
**Input:** n = 4
**Output:** 10
**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
**Example 2:**
**Input:** n = 10
**Output:** 37
**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
**Example 3:**
**Input:** n = 20
**Output:** 96
**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
**Constraints:**
* `1 <= n <= 1000`
|
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
338 |
welcome back to I would just today's questions League code 338 counting bits so you're given an integer n return an array answer of length M plus one such that each I where I is greater than or equal to zero and less than or equal to n and so I is the number of ones in the binary representation of I so we have n equal to two the binary representation of each value 0 up to two is as such so we need an array as our output the ones in the binary representation of zero is equal to zero right there are no ones within this binary representation in one we only have one bit and in two we also have one so we're looking for the ones in the binary representation of the values from zero all the way up to and including n and we need to return an array as the output now what would happen in the case where we have n equal to eight let's have a look at that so here we have the binary representation of all values from 0 up 2 and including n and if we pay close attention to the two least significant bits we have zero one once we reach this point as you can see they repeat so we have zero one and then they would repeat again over and over so what is changing between each of these well we're updating the most significant bit so let's briefly discuss what the most significant bit is so we have a most significant bit here and here so what is changing between each of these values when the most significant bit is updated well it's changing by a factor of two and that makes sense right because a bit is a power of two essentially so if we start at zero right there are no ones within this section however when we move to one we have one bit so it's going to be one plus we could assume that's plus the previous answer which would suggest using DP right so if we make a DP array from zero up two and including eight this deeper rate is going to be the representation of all the ones within the binary representation of each value from 0 up to and including and we can initialize zero if index to zero because we know that there are no ones within the binary representation of zero and now we can try and work out our optimal substructure so if we do one plus DP of I minus one this will give us the correct answer for one so we can update our DP array at index of one however if we use this for the value of 2 we're going to get 2 right but we only have one so this cannot work so let's think about this the only thing that has changed is the position of this one so we've updated the most significant bit and we said when we update the most significant bit we Times by a factor of two so if we initially have a variable called most significant bit actually we'll call it offset if this is set to one when we change the most significant bit then or when we change this offset we need to update this value so if we times that by 2 to give us the new offset on the most significant bit then in order to get a bit of one using dynamic programming we need to add the value from DP of zero so one way of doing that would be to take the index that we're on which is two minus the offset which will give us one and like we said this optimal substructure is wrong so let's implement this so at position one if we do DP of the index we're on minus the offset of this position but like we said the offset was one to begin with I at this position is one it's going to be one plus DP of zero that works out so that's going to give us one let's see if it works out with three so it's going to be one plus DP of three minus the offset so that's going to be DP of one so one plus the DP of one is one plus one which is equal to two so now we're at the value of four so we're in the DP array we're at index four we can look at the binary representation what's happened here well we've updated the most significant bit and how can we check for this update well we said a bit is a power of two so if we get the current offset we times it by two if this is equal to the current index run then we've updated the most significant bit so we have to update the offset and the offset will equal the current index run so we can update that to full now by using this optimal substructure of DPI minus offset it'll be one plus dpf4 so the index minus the offset of four and this is going to give us the correct number of ones within this binary representation and then we can repeat the process and then for eight we make the check so we look to see whether 4 times 2 is equal to this index of 8 it is so we update this offset to equal the index and then we add it to the optimal substructure we created which is eight minus the offset which is going to be one add that in there and then we can return this DP array as our output and this is how we'd calculate the solution of counting bits in o n time complexity let's first create the DP array it's going to be n plus one and we need to fill it with zeros right because we initially need to set the index of zero to zero and the easiest way of doing that is to fill all values to zero we need the variable offset which is going to be the most significant bit then we need to create the loop so I is going to be equal to 1 because we set the base case for index of zero where it's equal to zero Y is less than or equal to n because we want to include the last value So within this the first thing we do is check to see whether we've updated the most significant bit so it's going to be offset it's two if that is equal to the current index we're on then the most significant bit has been updated so we need to update the offset to equal the index run then we can write out the optimal substructure so DPI is equal to one plus DPI minus offset and all we need to do is return DP and this should work submit it and there you go hope you found this useful don't forget to like comment subscribe and I'll see you in the next one
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
87 |
um hello so today we are going to do this problem which is part of Fleet code daily challenge scramble strings so what this problem says is we get a string s and we want to convert it so basically we want to check if we can scramble it to get T and the way we scramble is by a defined algorithm here which is first if the length of the string is one we should just stop and check um now if the length is bigger than one we want to spread the string into two non empty substring at any random Index right it doesn't matter and then we divide it into two parts using that index so X and Y such that s is equal to the combination of the two and then once we divide we randomly swap the two substring or we decide either to keep them in the same order or swap them and by swapping them meaning just taking the left part making it on the right side and taking the right side making it on the left side so either we keep them in the same place which is it would be equal to if the first part was X the second part was at y keeping them in the same place would be just concatenating both so getting the original string swapping them here would be to take the right part put it in the left and then the left part on the right so it would be y plus X okay and then we can recursively apply this into each of the two substrings right so we take X and then we apply it into it and when we do X we divide X we can apply it also to the two parts of X right so we do this we can do this recursively and given these two strings um that are of the same length One Direction true if we can scramble as one to get S2 with this definition of the scramble and return false if not so let's take a look at an example just to make sure we understand so let's say if we have S1 great and S2 is rge it like this so one possible way to get S1 to be equal to S2 is so first we divide let's say at index 0 1 2 at index two and so we get this is the first part this is it second part so let's say in this decision we make the decision to keep them the same to not swap the order okay so they are still the same now each part will also recursively get divided so gr get divided um and so into two parts right and then it we can choose random index so for example let's say we choose index um one in the substring and so we divide it like this so for this one um so then next let's say for the first uh for the first portion with side swap it so R becomes to the left and G to the right like this and remember when once you are down to one part like R here we are done because when length is one we just stop um okay so now we have this RT and then we have this one okay so let's say um let's say we make the decision here to swap um so we made the decision to swap now we go back here to these two parts now this one is one letter so we can swap it but these two we decide to divide them okay um and let's say we keep them in the same order right so now comparing to S2 now they are the same right these two are the same because we of this swap so we can compare R to this one and J to this one and then eat okay and so now they are the same the only thing we actually did was this swap and we were able to get this one to be equal to S2 so that's the roughly the idea here um now let's see how we can solve it um okay so how do we tackle this so um let's say for example if we take the first string great right and then the second string this is the first example is like this so what do we need to do so we can see what we do is first we divide right like this and then we take that division and then we divide more again so we divide like this these two and then we decide also to divide this one here right and then we can also go even further once we divide this like this then we can decide also to divide like this but the first thing you may think of is okay um how do I decide where to divide right and the thing is It's tricky to find out where and so whenever It's tricky to find that word let's just try all of them right so the first thing is try all i options to divide right okay so that's the first part now the second part is swapping or not swapping so remember each time when we divide we have two choices we have either to say s is equal to X Plus y or we have to say s equal to Y plus X okay that's the swapping part now the other thing we want to do remember the initial goal we need to keep in mind here is that we want to convert this S1 to S2 that's the initial goal is to see if we can using these scramble rules if we can from S1 get to S2 and so to do that every time we divide let's just keep in mind that our goal so for example when we recurse on GR ass pass RG because if we pass RG then if we do one both combinations we can compare right okay and now the other up so the first part I said is we will just try all eye options right now we have these two options which one we should do well each time let's just do both and see what we get right so do both okay so those so we know we'll all just try all the options it's really brute force a Brute Force solution now the second question becomes how do we so you can see for example here um we decide to divide here um on the side to divide here how do we pass that recursively well the thing is for example let's say for this eat what are the bounds for this it using the original um string so if we have here we have 0 1 2 3 4 what are the bounds well for it for example for if we divide at e what is the first portion for the second half well it's from one index um two right two if we have if we make this inclusive it's index two to two right and then if we make it also again for e t is from index 3 to index four and this one is from index 0 to index one so you can see for each string right we can't assume that the index the first index is always zero because some cases it's because we divided the first and then we divided again it may not be zero and so what you notice here is we actually need a left side and a right side each time so here what this means basically is that we need for the first string is one we need to know what is the left boundary and what is the right boundary each time okay so that's the first part here now since we are comparing against S2 remember whatever we do for GR we need to compare and see if we can get RG right so basically what we and we also know if we split we want to check if it's equal so what we can do is also just as we are passing the left boundaries to compare against for S1 we pass the boundaries to compare against for S2 so that would mean for example here the comparison is going to be from 0 1 between 0 1 and 0 1 here right and so we also pass S2 left and S2 right the boundaries for because also for let's say when we are comparing against e here right we need to pass 2 um like this when we're comparing this three four we need to pass three four this part here um okay so with this we know that our function will need to have these here as the parameters okay and so now the question becomes how do we recurse and keep dividing um we know the base case is when the string length is one we can just stop and check if they are equal but how do we what are the options well let's look at it so S1 let's say this is the block of the string S2 so we said we will try all eyes right all i options so the first case right is when we will keep them in the same place which is X Plus y so let's say I is somewhere maybe here right um so in that case right what's the what should we compare against well we should just compare this side right against this side of course after recursing and then we compare this side against this side right so this is the I this is the eye position here this is eye position so how do we do that well and we need to recurse on these two so what this means basically is let's say our function got called with Scramble for S1 left and S1 right and then s to the left and S2 right okay so these are the bounds so this would be S1 left this would be S1 s to the left sorry this would be S2 left this would be S2 right this would be S1 right S1 left right so what we are comparing is well we need to recurse on this side here what is this side what this side is just for S1 it's going to be S1 left to S1 left plus I right that's exactly what this portion is because we stop at I and then what is this portion well this portion is just for S1 first so for S1 it's S1 left plus I plus 1 right because it's the next spot and then S2 S1 right now what about for S2 well for S2 is just this position first which is S2 left ends at S2 left plus I the same way as S1 and S2 left plus I plus 1 that's the position next to I is just I plus one um so this is left by the way let's just make sure this super clear and then the last position is just S2 right okay so this is pressure forward because it's just X Plus y because we are keeping the same order we are not swapping but we would recurse and maybe for this substring maybe we will reverse the order and Swap this one to be here and this one to be here right maybe and that maybe gives us the right answer so that's why we try all of them okay so what's the other possibility well the other possibility is y plus X now for this I by the way we'll try all options so let's say for example for this one which is length four we'll try to break here we'll try to break in multiples or in all the i options okay so for the second case which is um the case where um we do X um we do s is equal to Y plus X so how would that work so for the case where we do s is equal to Y plus X um let's draw it out so S1 is going to be like this okay and then we'd have rs2 so what does it mean for so let's say this is the I position right so this means basically this is our X and this is our y so what do we want to compare against well swapping basically means that we want to compare this portion against this portion right because we will put y first and then we want to compare this portion here against this portion so what does that mean so that means for the left side we will pass will because this one is becoming the left we are comparing against the left so for the left we'll pass this one for S1 and then for S2 will pass this one so this would be our left and then for the right side we'll pass this one and this one right so how do we do that well that means we will recurse in a different way here so how do how does that happen so first for the left side so recurse one so that's going to be from this position to this position so what is this position so this is the S1 right so it's just going to be from S1 right minus I right to get to here right we need to subtract I because um because remember this eye basically dividing means that um what it's going to mean for us is that the length is going to be I right the length is going to be I and so we go from S1 right minus I to the end because this is the right portion and then for the S2 we were compared against to just S1 left because we start from the beginning S2 sorry S2 left all the way to here which is s to a left plus I right and then for the second part right for the second recursion we'll compare against this is the Xbox so we'll compare this one against this one so it's mean for S1 is going to be S1 just the remaining part of this is going to be S1 right minus I minus 1 right because this is where this is just what's left after taking is one right minus I right so what's left is going to be so we go from S1 right minus I to S1 right so what's left is from S1 left to S1 minus right minus I minus one right that's just the remaining part now what's the remaining part of this one well we stop at S2 left plus I so it's going to be S to the left plus I plus 1 all the way to the end which is S2 right okay I did write it here with right instead of just L and the r just to make it more clear right and so this is the clever thing we are doing here is that instead of actually going and swapping we'll just pass the boundaries different boundaries so when we compare We compare the right side here with the left and the left side here with the right that's the idea and so we'll just check if these two will end up getting us um scrambled garena's S1 equal to S2 because each time with our recursion here we'll stop when we have one letter and so for example in this case when we swap R and J we'll compare this r with this R it will be good we'll compare this J with this J it will be good we'll compare e with e it will be good a with a it will be good tooth T's will be good right because we will go all the way down until one letter so that's the idea here I hope this makes sense because instead of swapping here all we are doing is we're changing the boundaries that we compare against and what helps really with this with knowing all the values here is just to remember that no letter will be left out right and so if we start from right minus I to S1 right that means for the second part we'll need to go from the left all the way to the spot before this one which is S1 right minus I minus 1 right and then at the beginning is just S1 left and similarly here because we stop at s two left plus I we need to start from the next position which is S2 left plus I plus 1 and we need to go all the way to the end so we need S2 right okay um I hope this makes sense and but this is pretty much the idea here now let's implemented and make sure it passes um okay so let's implement the solution we saw in the overview so we need our recursive function let's call it just scramble um and we set the boundaries will pass is both the left side and the right side of each of them of each string so it's going to be S1 left S1 right and then the left sides of and the right side of S2 as well right and we know our base case is if there is just one letter and one letter means that the boundaries for S1 are equal we don't need to worry about different length because the problem says the strings would have the same length so here in this case well it's valid only if we can get if they are equal right if the same letter is equal in both strings so S1 left it's one its own one left is equal to the same one in the same spot in S2 if this is the case then we return true otherwise we return false okay so now we said we'll try all eye positions now what are the valid eye positions well this is the substring we have goes from S1 left to S1 right so the possible length of I we have are just the length of that string so starting from zero right so it's going to be this one let's try this so these are the possible length we can have um Okay so now remember these by the way are inclusive bounds so this means that the strings start at S1 left and stops at S1 right exactly because otherwise we may end up with an empty string right so these are includes of bounds um okay so here now the length this means we will divide such that the length of the left side is I and the length of the right side is I right so length of left side is I and like the right side yeah and length of right side it can is the remaining or yeah pretty much right and so how do we do that then so the first normal case is the first case is S1 is going to be X Plus y so in that case we can just check that once we divide into these two parts right each one of them can get us equal to S2 so we divide for with I so let's say x to the left is going to be S1 left right although to get a length I is going to be all the way to plus I right and then for the right side it's just going to be because we are not um we are not reversing the order it's going to be the same so it's two left two s to a left plus one we are not changing anything in this case now what we need to do it for all the string right so what's the remaining part so the remaining part is going to be starting from where we ended here right but we need to do plus one so that will go to the next letter all the way to the end of S1 which is in this case the substring is just up to S1 right okay then what are the boundaries for S2 well just the remaining part of this similarly so it's going to be S2 left here plus I sorry so it's going to be plus I plus 1 to go to the next letter and then the second part so this is going to be just S2 right okay to get to the end um okay so if we are able to scramble and get to it from these we return true now otherwise the second case which is case S1 going to be divided like this well we said we will take the right path and put it in the left so that's going to be S1 right minus I s all the way to S1 right so the right side for to the left um and then um the left side is unchanged because we are comparing against it so it's going to be just as two left plus I and then for the remaining portion so what's remaining here so remaining from S1 which is the X part is going to be just the one before this one that's going to be our end boundaries but we need to start from the beginning because we don't need we shouldn't leave any letter not checked right so we start from the beginning and then we go all the way to this boundary here of the Y portion so S1 right minus I minus 1. and then for the second part it's unchanged because we are comparing against S2 so it's going to be just the rest of this one which is going to be left plus one all the way to the end which is S2 right okay and that's pretty much it now if we are able to get this case to be scrambled to S2 then we'll return true if we go through all options for I and we are not able to do that then we'll return false and now we just need to call our recursive function so we want to start with the entire string from the start from the beginning of course so that's going to be zero let's say n is the length of this these strings so this one so we'll go all because these are inclusive bounds we shouldn't put n we should put n minus one because that's actually the last index and then for the right side it's the same and then we return those um looks like there is a typo somewhere here um okay let's just um simplify it like that so we get this looks good like that here as well okay looks good now we'll get time limit exceeded here because with these variables we will end up calling this function with the same parameters multiple times right so the easiest way to do that in Python is just to do Ru cash but you can also um you can also you all or just cache you can also just use a hash map with these parameters right as the keys for your map um so let's run and let's submit and this passes looks good um but yeah that's the idea pretty much it's just doing Brute Force but um making sure we apply all the cases um I will let you do the cache using a hash table it should be pretty easy to do um but yeah that's pretty much it for this problem please like And subscribe and see you on the next one bye
|
Scramble String
|
scramble-string
|
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
* Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`.
* **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`.
* Apply step 1 recursively on each of the two substrings `x` and `y`.
Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`.
**Example 1:**
**Input:** s1 = "great ", s2 = "rgeat "
**Output:** true
**Explanation:** One possible scenario applied on s1 is:
"great " --> "gr/eat " // divide at random index.
"gr/eat " --> "gr/eat " // random decision is not to swap the two substrings and keep them in order.
"gr/eat " --> "g/r / e/at " // apply the same algorithm recursively on both substrings. divide at random index each of them.
"g/r / e/at " --> "r/g / e/at " // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at " --> "r/g / e/ a/t " // again apply the algorithm recursively, divide "at " to "a/t ".
"r/g / e/ a/t " --> "r/g / e/ a/t " // random decision is to keep both substrings in the same order.
The algorithm stops now, and the result string is "rgeat " which is s2.
As one possible scenario led s1 to be scrambled to s2, we return true.
**Example 2:**
**Input:** s1 = "abcde ", s2 = "caebd "
**Output:** false
**Example 3:**
**Input:** s1 = "a ", s2 = "a "
**Output:** true
**Constraints:**
* `s1.length == s2.length`
* `1 <= s1.length <= 30`
* `s1` and `s2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
| null |
1,859 |
Hello everyone, how are you, my name is Vikas Gupta and Solution Bhai also welcome all of you in this new video of the case, so gas, today's video I have picked up from the lead code, so today's video of ours is the question of write an algorithm date. Will sort the given sentence, so how do we have to write the algorithm that will sort the given sentence, then what will we give the contents? Here in the example, the text is input text, this is 2 sentences for this one, a three, so we People can see that we have number one in the world, which tells the position of our people, like sentence is on position, this is on fourth position, this is on first position and A is on third position, like here you guys are output. You can also see here written single space with no leading and trailing space 'H' word consists of lower and upper space 'H' word consists of lower and upper space 'H' word consists of lower and upper English letter. This sentence can be suffered. It is okay and it is such a journey, meaning in the successful gender, any word can be anywhere. We can just tag it, which character, which word is at which position, because we have given the number here, so the question is, should I solve it or should I solve it here, so let's solve it here. First I will do something like this, I will create a dictionary impati dictionary from it and whatever their key will be, we will put this character, number, in the key and our sentence, word will give it a value. We will put it in the right like if we give it to our dictionary the key will be you and ours which will be its value then the sentence will be four sentence key will be 4 the value of the sentence will be like this so we will keep it so without wasting any time let's move on to the lead. No, I do the job on spider and in the end I will run the delete code and show it. The sentences are fine because it will take parameters and in which we will store the output. First we set the flag, right, after that we get our word done. It is okay with sentences and if this is the input of our people, it will be a string like this, if we make it loop then one character will start coming out, which is what we do not want, we will have only one word voice, we will If people want then we will split it for that. What will the split do? Will it convert your characters into a list? It will convert your characters into a list on the basis of a space. I hope all of you are aware, so I have one more number to get out. For this, I am going to use regular expression, what will I do in this, I am half dot sir check in which we are looking for our pattern, what are we looking for in the pattern, we are looking for our number and what will be our string, find the type. We are searching in our world and after that it will return its objective match objective. Matching is ok, so it is decided that there will be a number in each word, ok, we do this and if I call this number then whatever match will happen. It will be from its zero index till its last, where will it be launched, okay, I store it like this, okay, so I copy the start index in it and this is what I copy both the end index in it. Start, which is our number, where in this world can we get its start and end index, okay gas, after that we will find the number, if we find our number, then the word and start index in it is fine and through slicing, everyone has come out. After that we find out that we have got this number from this word. If we have got the number from this word then we do not want to store the number. We keep the number in the key. And whatever value is there, let's keep it in value. Okay, like there is two, we will keep it in key and whatever is I, we will keep it in value. So we are sorry for gas, where has it gone, after that we make these new words in which We will remove the number, I will not do anything to remove it, I will easily run a replace, someone will replace the number, what will replace it, then gas, here I have made a new word, in the new word our 'A' is this and that. in the new word our 'A' is this and that. in the new word our 'A' is this and that. We have words and our number goes into it, so I store it in the output which we have created above, sorry, I have forgotten slicing. There is an update function which takes a dictionary and will update it, so we will first store the number and convert the number into an internal so that since it will be a number basically, we will convert it into an integer and what will be its value. Will give new word right. If I run this much and show it to all of you, then you will get the idea that we have done the input sentence. Let me run this much and see, we will pass the input sentence in it and print the output. Take two, whose number is two, the position of the sentence, which is the number, which is actually the position, where we have to keep that character What is the range, till where we have to run the output, whatever is ours, we have to run it till its length, output What is the length of the key? If it is 1234 4, then it will run four times and out of that, whatever we will append in the sentence, we will captain, we will append the value of the output, that will also be a position, then how will the positions be removed from the output, this is ours, which will be zero. If it works, then we will add van + 1 in it, because we have got the van + 1 in it, because we have got the van + 1 in it, because we have got the store done from van, so we will pay here from van, so now the first position will be inserted in the first time or what does the friend do, he keeps inserting it in the last. It is listed and we keep inserting it at the last one, so in the first time it will insert the value of Van, in the second time it will insert the second value , , , then we have to return it in the string as we will write here, let us get it done, what does join do? Converts all the iterators of the entire string into a string. Right, we will pass the sentence inside the join and now we will not change anything here. The input string will remain the same, our output string will also remain the same and we People get tested to know what is the output, so gas, we have passed this sentence for this van and A3, so one of our orders has come after that number has been removed and not one more, yet another test. Let's do this otherwise I do another test like my self you me van I four pe hai iPhone To return the sentence to us in a sorted order so that which is of the lead code so What do I want? Gas, I have not written the code here because I leave it for you guys in the task. You guys go here and go to the question number that people have and first try to solve it yourself. Even after I record it, thank you gas. Thank you for watching my video. Next video bye.
|
Sorting the Sentence
|
change-minimum-characters-to-satisfy-one-of-three-conditions
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence.
* For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`.
Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_.
**Example 1:**
**Input:** s = "is2 sentence4 This1 a3 "
**Output:** "This is a sentence "
**Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers.
**Example 2:**
**Input:** s = "Myself2 Me1 I4 and3 "
**Output:** "Me Myself and I "
**Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers.
**Constraints:**
* `2 <= s.length <= 200`
* `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`.
* The number of words in `s` is between `1` and `9`.
* The words in `s` are separated by a single space.
* `s` contains no leading or trailing spaces.
1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
|
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
|
Hash Table,String,Counting,Prefix Sum
|
Medium
| null |
239 |
hi so this question is sliding window maximum so uh you are given a in nums array and then also integer k so uh for every single k length inside the nums array with different index you need to grab the maximum value so uh this is not really hard to understand but it's really hard to call for sure so this is the size of k right so the maximum number is three so we will just allocate the value the three into what into the first uh into the first value and the second length should be what from here to here right and the maximum value should be three as well right so we allocate the second index and so on right so uh you just definitely understand that white action meant so how do you actually need to solve this and you will definitely need what like a day cue right so the reason why i use the dq uh i mean a red deck it's not the cube like it's already right so a red deck like you can actually pull first or pull last it depends and definitely you can add first or add less right so uh there are two different uh two different like endpoint that you can actually uh retrieve right so uh in this case right so um when we uh we need to check like we need to check the index if the index is actually within the bond right it's actually within a k uh k length right so imagine like you add a three into the red deck right and then at this point five it for index five right you need to know like this is four in this phi i mean there's zero one two three four in this four we don't need the value of three right so this is what this is all about for listing this right so uh just in case uh you don't know like this is what you need to get you need to set the boundary right so when i minus k and then plus one if this is greater than the then the index inside the dequeue then you need to what you need to pull first right so uh for every single value like when you check this condition you need to pull first this is because you add this value already right so you will keep adding the value at the end right so uh for every single value you will definitely add a value at the end and once you add this value right on the following index on the following so you need to check the uh the length k for every single index and also you need to y you need to pull when the current value which is what greater than the value inside the stack so i mean inside a red x right so a redex something like this right so if this is greater like the current value which is greater than the value inside the red deck from the m then you need to pull i need to pull last then for every single index if i minus k plus 1 which is square equal to zero which mean like you are starting because you are generating a new array right and then you need to write you need to keep uh updating the value for every single in uh for every single value and if this is greater equal to zero right then you would just peak first right because the value inside the red deck right for the first one is always the value you need to what you need to add into the new array so this is it right so it might be hard to like see it but i'm going to definitely like describe really clearly and uh while i'm coding so i need a red deck and this is going to be i need to push an integer right so i'm going to call this and this is a reddit and i need a returning array so new inch and the size of the interview are number length minus k plus one so just think about this is what size of one two three four five six seven eight right this is size of eight and what happened to this one two three four five six so eight and six so should be what a minus three which is five plus one right so this is how you get it and then we definitely need to return right and then we need to index all the result in array so this is pretty much it so i need to try version number and uh for every single value inside the inside of the list right then uh we need to add a value for the index we need to add the index for nums right so i would say let's start offer last ai so i add the index into the red deck and then when i compare i actually like peak first or pick less base on the nums so first things check if the uh if the list index the first i mean the beginning or first beginning index is within the boundary of k right so well definitely this is not empty and also i plus sorry i minus k plus one right we if like if this is greater than one uh list of p first if this is greater than uh if the value inside the list a red deck which is what less than the i minus k plus one then i need to pull right let's stop pull first and this is going to be pretty straightforward and this is what the value is less length turn that right so while this is not empty and also the nouns and list of peak last right which is less than or equal to the current value which is num say i and you should you need to list up whole plus so imagine like you add a three into the list already right and then i mean yeah the redex and then you also need to add negative one right but you know like negative one shouldn't be added right but however you add a negative one into the red deck uh whatsoever but on the following index you need to check right so you need to check the value inside the red deck and then you just pull last and then just keep your three inside the red deck until like until assigned sign assign assigned value into results uh in array results okay so if i minus k plus one this is going to be really similar to this one if this is squared equal to zero now you check the condition right result at index plus equal to num say what let's start what p first right you need to always append your first value inside the red deck into the new array right and then for every single time you increment your index and then you know like your next value is ready so let me run it so if i have error or not no i don't so this is going to be pretty much a solution so i know this is hard but you need to just follow the logic so based on the sliding window um there are a lot of way but this is kind of easy to me to understand and i made a note so just in case you forget and the time and space so for the time this slow this is going to be all of them and represent the end of the number hey it doesn't matter there's a while loop inside the folder because you actually need to pull the value you're inside the right deck right so it doesn't this should be constant right you're just comparing and then pull the value out quickly for the current iteration right and this is going to be all the fun for time and then this is going to be the space is going to be all of them uh you definitely need to add the value into the red deck uh relay for every single value right so the worst case is going to be at every single one of them right so this is all of n and i mean time and space are all the things so this is going to be pretty much a solution so i will talk to you later bye
|
Sliding Window Maximum
|
sliding-window-maximum
|
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the max sliding window_.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[3,3,5,5,6,7\]
**Explanation:**
Window position Max
--------------- -----
\[1 3 -1\] -3 5 3 6 7 **3**
1 \[3 -1 -3\] 5 3 6 7 **3**
1 3 \[-1 -3 5\] 3 6 7 ** 5**
1 3 -1 \[-3 5 3\] 6 7 **5**
1 3 -1 -3 \[5 3 6\] 7 **6**
1 3 -1 -3 5 \[3 6 7\] **7**
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `1 <= k <= nums.length`
|
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
76,155,159,265,1814
|
114 |
welcome to mazelico challenge today's problem is flatten binary tree to linked list given the root of a binary tree flatten the tree into a linked list the linked list should use the same tree node class where the right child pointer points to the next node in the list and the left child pointer is always null the linked list should be in the same order as a pre-order traversal of the binary tree pre-order traversal of the binary tree pre-order traversal of the binary tree so pre-order traversal is node left so pre-order traversal is node left so pre-order traversal is node left right and you can see we're going to go node left right and make this into a linked list supposedly it's still a binary tree but we're just going to use the right child pointer as the next now they want us to do this in place if you look at we're not going to return anything because if we were to just create a new binary tree it'd be pretty trivial we would just traverse and pre-order traversal traverse and pre-order traversal traverse and pre-order traversal put our values into like an array and then recreate our binary tree right but we don't want to do that we want to do this in place so how can we do that well normally with these binary tree problems you'd have to do something recursive and you'd have to figure out what you might be able to do at a single node so say that we're starting here what we would do is return a flattened list of whatever the subtree is right and put that to the right side and whatever the end of this subtree is it's going to be a flattened tree now we're going to put that right side as this temporary one here at that in here right so we can say okay here with 2 3 4 we're going to make this 2 3 4 here whatever this is put that in between and whatever the end point there is make that going to be equal to the right side of this node okay so that means we have to return two things we have to return the head of our new flattened linked list as well as the tail so we have to return both of those and what we'll do is um if there is something returned we're going to always make the left side a null and we will make the right side the first right side equal to whatever the flattening list is here and then uh move our end pointer all the way to the end of this tree and then attach whatever um subtree that gets returned from the right side to that okay so i'll show you what i mean uh the very first thing we want to do is create a helper method so we'll just call this dfs and we're going to pass in a node okay and we know we're going to return two things right we're going to return the head and the tail of our flattened linked list or flattened binary tree so first thing if not node we're just going to return none all right so there's two things we got to keep track of we have to keep track of the left and the um we'll call it left two that's gonna be the end the tail and what we'll do is just pass in the no dot left here and then we're going to do the same thing here with write 2 equal to dfs no dot write as well now first we want to do is reset our left to just be none and we have our left and left two values so what we'll do is uh we'll keep track of this and sort of pointer so call this the end and we'll start off just with n being the node so if there's a left what do we want to do well we want to take our end right and make that equal to uh left right and we want to now make let's see um and dot right to go to the left so now we want and to now equal what left two right and if there's a right now we want the n dot right to equal right and we want n to equal right two finally just return the node which is going to be the head and then the end which is now going to be the tail so if we just uh call this now with the root this should modify our binary tree to be a linked list so that looks like it's working let's go and submit it and there we go that's accepted so this is of n time complexity but because of this recursion stack i believe it's going to be o of n extra space this follow up here can we flatten the tree in place with just o one extra space that would basically mean we'd have to do something iteratively and unfortunately i just couldn't figure out a way to do that in oven because if we were to do this iteratively we'd have to re-like as we build our binary tree we have to refine the end each time in our iterative loop so it ends up becoming n squared so i don't know if that's better um you know if anyone figured out a o n with o one space solution you know feel free to put in the comments but otherwise i think this is good enough i know it's not all one space technically but it is of and time complexity so i'd say that's fairly optimal all right thanks for watching my channel remember do not trust me i know nothing
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
283 |
all right this lead code question is called move zeros it says given an array nums write a function to move all zeros to the end of it while maintaining the relative order of the non-zero elements relative order of the non-zero elements relative order of the non-zero elements so the example is the array 0 1 0 3 12 and the output is 1 3 12 0 because all the zeros have been moved to the end and then we have a note you must do this in place without making a copy of the array minimize the total number of operations all right the key to solving this problem is to use two different pointers at once and by pointer I don't mean actual point or like in C++ I just mean references to or like in C++ I just mean references to or like in C++ I just mean references to two different elements at once so we'll call the first pointer Explorer and we'll call the second pointer anchor what Explorer will do is advance until it finds a nonzero element in the meantime anchor will just stay back hence why we're calling it anchor it will only be allowed to move forward when Explorer finds a nonzero element and swaps with it at that point anchor can move forward I'll show you what I mean is Explorer on a non zero element no it's not so it needs to advance now is this element nonzero no it's not so it needs to advance again now is this element as 0 no it's not so what Explorer is going to do is give its element to anchor an anchor is going to give its element to Explorer so 6 will now go to the front and 0 will now be swapped so now explorer gets to advance as usual but this time Ankur also gets to advance why is that it's because we know that it's definitely not on a zero anymore how do we know that because Explorer just swapped with it and gave it a non zero so we can just advance as we can see anchor is effectively hanging back on zeroes and waiting for Explorer to switch with it so we'll do the same check is Explorer on a zero yes it is so we'll advance at one now is it on a zero no it's not so we'll do the same swap as before all right so as usual we advanced Explorer and again we get to advance anchor because it just swapped with Explorer for a non zero element so now it needs to move forward and we'll check again is Explorer on a zero no it's not so we'll just swap them and as we can see all of the zeros have been moved to the end of the array all right so let's get to the code what lead code has given us is a function called move zeroes it accepts a parameter called nums which is just an array whose zeroes you want to move to the end so remember we need two different pointers one we'll call anchor and we'll start it at the first element so let anger equal zero that'll look like this and the second pointer will call Explorer remember pointer is always advanced no matter what so that's perfect for a for loop so let Explorer equals zero Explorer or less than nomes dot length Explorer plus okay so that would put Explorer in the same place so right here alright now we have to check if Explorer is on a non zero number so we'll say if nomes Explorer doesn't equal zero but in our case it does equal zero so we'll have to skip forward to the next loop they'll put us here okay so now we check again is Explorer at a non zero number it is so now we can swap Explorer and anchors elements so Explorer will be zero and anchor will be three in the code we'll do a typical swapping mechanism so let temp equal numbers except some anchor nums anchor will now be replaced with whatever is in Explorer and now Explorer will be replaced with whatever was originally in anchor remember we've saved that to temp okay so now that anchor is definitely not a zero we can also advance anchor alright so that'll look like this anchor gets moved up and the next for loop happens so now Explorer gets moved out then we check again is Explorer on a non zero number no it's not so we'll advance it one it checks again is Explorer on a non zero number yes it is so now we can swap the elements 12 becomes zero and zero becomes 12 alright so now that anchor is definitely not on a zero we can advance it next for loop starts so we can advance Explorer it checks if it's on a zero yes it is so it advances it one more time and then we're done because we're outside the bounds of the array so that should be it let's run the code it looks good let's submit it all right so our solution was faster than about 85% of solution was faster than about 85% of solution was faster than about 85% of other JavaScript submissions as usual the code and written explanation or link down below if you liked the video please help out the channel by giving the video a like and subscribing to the channel see you next time
|
Move Zeroes
|
move-zeroes
|
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.
**Note** that you must do this in-place without making a copy of the array.
**Example 1:**
**Input:** nums = \[0,1,0,3,12\]
**Output:** \[1,3,12,0,0\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you minimize the total number of operations done?
|
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
|
Array,Two Pointers
|
Easy
|
27
|
693 |
discuss a problem on lee code it's a easy problem on vietnamese regarding manipulation and this problem wants us to check whether for a given positive integer if the two adjacent bits in a binary representation always have the same value if they have the same value return true if don't return false so for the number five uh its binary representation is one zero one and you can see that the adjacent bits are different but for number seven it is not right so the problem description is simple and uh our strategy is also very simple so um we're going to iterate through the number so and we want to iterate the number of times of how many digits are in the binary representation and for each iteration we want to compare the current position the bit in the current position with the b in the next position and if they all have different values then we can return true if one set have uh the same value then we have to return false we can just short circuit the for loop okay so the first thing we have to do is we have to um figure out how many um times we have to iterate through the loop right so this could be done many ways and today i want to do it using some simple math so first we're going to import the math module and we're going to set the number of times to be we want to log the number with base two so this will give us the number of this will give us so for five it would be two raised to the what power will give us five so this number is going to be between two and three because uh two is the second power is four two is the third power is eight so is got to be something in between but this is not going to return us an integer value because 5 is not a 4 power and not integer power of 2. so we can either round up or run down you could do it either way but in this case we want to round down so we're going to float for this value so this means that for the number five we would iterate through this loop two times and for the number 11 we will do it three times and uh we will see why we choose to round down once we have written this for loop so now we enter the for loop again there's many ways to do it but this is the way i choose to do it for this solution so for range d so in each iteration we want to extract out the current um the current digit and we want to extract out the digit after so one place let the left of the current digit right so um so for example in the first iteration we want to extract out this and how we're going to do it well we know that we could extract out the digit by doing some shifting and uh we have discussed this in the videos before and uh this is for the uh digit to the right uh relatively and we want to also extract other dj to the left which is my bad so um notice that we are keeping the keeping n the same so that we have to use rely on the index to access the place the actual place in the digit so we want to shift it by this amount for the digit on the right uh to the digit on the relatively to the left so n one would be this digit for the first iteration of the number five and two would be this digit okay so then we extract out the digits we want to compare them to see if they are the same so um we want to return true if the two digits differ we want to return false no we don't we want to return false if they differ but we want to keep checking if they are the same so remember that the operator that will give us true if the two digits have the same value the two digits have the different value would be the actual operator right so we simply use the actual operator to check whether um they are different so if they are the same so in other words if the xor returns false then we would simply return false because if one of them have that one pair have the same value than this digit this number doesn't have alternating binary representation so if every pair checks out then we would return true so if the for loop exits normally then we would return true okay so um now you can probably see that why we choose the four is because we don't need to get to the last digit because the last digit is only compared once to the digit before it so we already achieve it by getting to the digit before it and we have checked the last digit already which is the last pair that we need to check so we don't actually need to sealing it to reach the last digit and that is our code for the problem and we just want to run it to see if there's any problem with it okay and we want to submit okay so that is all for this problem
|
Binary Number with Alternating Bits
|
binary-number-with-alternating-bits
|
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
**Example 1:**
**Input:** n = 5
**Output:** true
**Explanation:** The binary representation of 5 is: 101
**Example 2:**
**Input:** n = 7
**Output:** false
**Explanation:** The binary representation of 7 is: 111.
**Example 3:**
**Input:** n = 11
**Output:** false
**Explanation:** The binary representation of 11 is: 1011.
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Bit Manipulation
|
Easy
|
191
|
896 |
hey guys in this video i'm gonna be teaching how to solve lead code problem 896 monotonic array let's read the question first an array is monotonic if it is either monotone increasing or monotone decreasing an array numbs is monotone increasing if for all i less than j less than equal to j numbers of i is less than equal to numbers of j n array nums is monotone decreasing if for all i less than equal to j numbers of i is greater than equal to numbers of j given an integer in nums return true if the given array is monotonic or false otherwise let's check the examples first in the first example we see that nums are a is given as 1 2 3. in this question in this example um the num's array get got constantly increasing or either it didn't increase in case of 2 and 2 um let's check the question again in this question they told us that the number is said to be monotone increasing if the numbers of i is less than equal to numbers of j which means it is okay for 2 and 2 to be equal so the example 1 return true similarly example 2 we can see that the numser is 6 5 4. it either decreased or it didn't have any change which means the output is returned is true but in the third example we see that there is an increase and then a decrease so it will not fall now let's get into the code first uh in order to solve this problem we can have two variables both variables let's set them as is increasing and another bold variable becomes is decreasing okay now we are going to set these two true what these variables do is uh they update the status of the array as we i did to through the entire array uh in case in between if we find that the array is not following the is increasing principle or is decreasing principle uh within written faults that's the simple idea of the entire thing um now let's um create a for loop in this slope let's loop it from uh index i is equal to 1 to the last of the last index of the array i less than early.size i less than early.size i less than early.size okay that's pretty good so okay inside this we are gonna insert two if statements one to check if there is a change in the is increasing principle or and the second one is to check if there is an uh if there is a change in is decreasing principle okay so i'll implement this for you so that you can understand better it's less than of i minus one okay now we are gonna in case uh the current uh element is less than the previous element um which means that it is not constantly increasing so now we can update the is increasing value to false similarly we gonna do it for is decreasing array of i is greater than a of i minus one okay in this if statement we're gonna check if the present array element is uh actually greater than the previous element now in case this happens we are gonna update the is decreasing variable to false just as the previous one okay now in case any of the statements is true any of the variables is increasing or is decreasing is true we are going to say that it is a monotonic array but if either of them is not working out if either of them is if both of them are false then it's gonna it's not gonna be a monotonic array so that is the idea what we're gonna implement here okay now let's check if we uh got the code right okay this is accepted so let's submit it yeah so you can see that it's faster than 50 of the remaining c plus submissions so i guess this is good quite good okay thank you for watching my video if you really like this video please hit on the like button uh share and subscribe to my channel thank you
|
Monotonic Array
|
smallest-subtree-with-all-the-deepest-nodes
|
An array is **monotonic** if it is either monotone increasing or monotone decreasing.
An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`.
Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,2,2,3\]
**Output:** true
**Example 2:**
**Input:** nums = \[6,5,4,4\]
**Output:** true
**Example 3:**
**Input:** nums = \[1,3,2\]
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-105 <= nums[i] <= 105`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
62 |
hello everyone welcome to my channel coding together my name is vikas hoja today we will see another lead code problem that is unique paths it is a medium level question and it's also a very popular question as you can see from the likes so let's read the problem statement first there is a robot on an M into n grid so we are given with a M into n grid where M denotes the number of rows and N denotes the number of columns so it has and the robot is at the grid 0 comma 0 and it has to reach the Finish point that is located at grid M minus 1 and minus 1 so in how many ways the robot can reach the Finish point the robot the condition is the robot can only move either down or right at any point in time it can move and only write or down so we have to find the number of possible unique paths that the robot can take to reach the bottom right corner so let's understand this problem with the same example drawn here the robot is at the position 0 comma zero and the robot has to reach the Finish point that is M minus 1 n minus 1. so we have to find all the unique Parts the robot can take to reach M minus 1 and minus 1 at cell so as we know the constraints are the robot can move either right and down right so one of the possible uh ways to find the solution is backtracking you know Finding recursively finding all the solutions from the starting point to the end point so suppose we start at 0 comma zero so at zero comma zero robot has two choices either to go right or to go down again after uh so suppose the robot goes down then the robot has again two choices either to go right or to go down and recursively it will again it will go to another cell right by taking one of the choices right and then again it has one of the choices until it reaches M minus 1 comma n minus 1 that will be our Leaf node so that is what we do in recursion one of the possible way is doing this right so if we you know find all the possible paths using this Brute Force so it will be of time complexity 2 to power M plus n right because the total depth of this tree recursion tree will be M plus n a robot can take m steps of the rows like it can go down till M and then go n uh cells to the right to join to reach the finish line so the maximum uh depth of the tree for any path will be M plus 1 M plus n right either it takes like it goes one two three and then go if it goes one right and then goes down then goes right so it will be always M plus n depth for any path so the time complexity will be Big O of 2 to power n plus M and the space complexity as I said will be M plus n because each path of this recursive tree will be uh M plus 1 M plus n an event in the uh stack in the DFS stack so how we can optimize this solution we can use dynamic programming so how we can see that whether this problem how we can deduce it whether it's problem can be solved using dynamic or cropping that is first optimal substructure and repeating or overlapping sub problems so these two conditions uh indicate that we can use Dynamic program so what is optimal structure a substructure is that using the larger sub problem larger problem can be solved using smaller sub problems okay this is the optimal sub substructure so how this satisfies this optimal substructure that whenever robot moves either down or right I whenever the robot moves right or down the grid the area of grid reduces right area of grid reduces area of the hours problem gets reduced to a smaller sub problem right if you see if the robot moves down the grid becomes this much the highlighted one right because it cannot go back right it cannot go up if it is moved down it can only go right so the area or the grid has reduced so our larger sub problem has due to the smaller sub problem so again if the a robotics right so again if the robot takes right then the grid will become then the grid has reduced to this much right this is this portion so at every step the grid size is decreasing right the grid area is decreasing so it's a smaller it's a optimal substructure so now overlapping sub problems the second point is over sub overlapping sub problems yes it's a overlapping sub problem because in this if you'll draw this recursive tree for a particular grid you will see that many of the cells are repeating right the robot might be reaching this cell so if you see the robot might reach this cell from here right from just the right the left of it so from here the robot can go right and reach this cell and from above also it can reach this cell so it's a overlapping sub problem right so the question is meeting these two conditions hence it's a dynamic program we can solve this by dynamic programming so we'll use what is called tabulation approach that is iterative iteration method you can say iteration approach you can say now in this we go from bottom to up right from bottom to up now we have to understand uh what bottom to up means from a smaller we have to find the smallest sub problem will solve the smallest sub problem and we'll find the optimal solution for it and using that smaller sub problem optimal solution will solve the will keep on going up and up solving larger and larger sub problems till we solve for the whole problem so that is the tabulation approach what is the smallest sub problem here so suppose the robot takes one step right so if robot is present at this cell so we are sure because there is no cell above so the robot has taken only one step from the left it has reached this cell the dotted one from the left only right so to reach this cell there is only one path right also if you talk about this cell so there is only one choice for the robot so how would a robot Reach This cell is only from this left cell right only from left cell so to reach this cell only there is only one path there is only one because there are no above cells right so for this complete row we will be having only one path right there will be only one path to reach this cells now if I see the First Column also to reach this cell the robot is on will only take will go from up to bottom right the cell just above it cannot go it has it cannot come from the left side of it because there is no cell yeah similarly if you talk about this cell it will come from above so for the first row and the First Column there is there are only one paths at all right there are one only one part so if I draw this in the tabulation approach so if I talk about 0 1 2 3 Let's Take let's take a smaller grid right let's take a smaller grid with four columns and three rows three into four grid now as I as we saw above so for uh each uh cell right for the each cell it will be one only right it will be one only One path right so to reach the starting point it's only one because there is only one path uh it reached here it reached the start so the first row and First Column will be all one now we will when we are at this cell now let's talk about this cell when we are at this cell what about this cell so the robot can come from up to the cell and can come from the left the robot can come from left if the robot can take the right and robot can take the down step so what we have to do we have to add the DP of the cell just above it right and what this DP represents the number of unique paths number of unique Parts the robot uh can take to reach this cell right and this cell so we'll have to add the DP of 1 comma 1 DP of 2 comma zero right so it will be DP of 1 comma 1 plus 1 comma 1 plus DP of 2 comma 0 that will be 2. right so what we have added to calculate the DP of 2 comma 1 2 for DP of this cell right we have to add the number of unique Parts a robot can take to reach the cell and this cell the cell just above it and just sell just left of it right now at for this cell again we will add the DP of this cell and DP of this cell that is 1 plus 2 right so 1 plus 2 is 3. so there are three unique paths for a robot to reach this cell right now for the DP of 2 comma 3 right for the DP of 2 comma 3 what we add is DP of to 1 comma 3 just the cell just above it and 2 comma 2. so what is 1 comma 3 and 2 comma 3 1 plus 3 that will be equal to 4. right for this cell 1 plus 2 that will be 3 right the cell the DP of the cell just above it and DP of the cell just left of it now for this cell what will be 3 plus 3 that is 6 and for this cell it will be six plus four that is ten so there are ten possible ways to reach the Finish point so let's see the code part of it okay so here we have initialized our DP right DP will be a 2d array within size M cross n right for each cell we have a DP we'll representing each cell now we will call our helper method where we are passing the MN n the rows and the columns and the DP so we'll iterate over M and N for each cell right for each cell if I equal to 0 or J is equal to 0 we're initializing our DP as one so for the first row and the First Column the values will be one so we have initialized as one else for the another cells it will be the DP of the cell just above it and plus the DP of the cell just left of it right these two cells as we talked about this one for this the DP of this cell it will be this one plus this one right the sum of these two cells will give the DP of this one so in this way finally we as we know the last cell the DP of M minus 1 n minus 1 will give you the total number of distinct parts to reach this Finish Line right so ah and finally we will return DP of M minus n minus 1. so as we talked about the time complexity of it so we have four two Loops for two for Loops that are running so the time complexity will be we go off Big O of m cross n right so let's run this solution it's running fine so the solution is correct so hope you like this video If you like this video please share and subscribe and like the videos thank you for watching
|
Unique Paths
|
unique-paths
|
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100`
| null |
Math,Dynamic Programming,Combinatorics
|
Medium
|
63,64,174,2192
|
414 |
hey what's up guys isn't it quite here I do tech accounting stuff I'm twitching YouTube you can check the description for all my information I have Lee code premium problem solutions on my patreon and if you want to reach out to me you can hit me up on disk or to try and get back to everyone this is a problem that I've solved but for some reason I just never made a video for it so I have it in the algorithm study guide but I didn't make this format so we'll do that for fourteen third maximum number this is given a non-empty array of integers is given a non-empty array of integers is given a non-empty array of integers returned the third maximum number of an array so we're given iran integers it doesn't have to be it's not sorted it doesn't have to be sorted and we want to return the third max so if it doesn't exist return the maximum number time complexity must be linear okay so you can't sort sorting takes n log n so you can't just sort it because that's too slow so we want a linear solution and a hard-coded solution is pretty easy one hard-coded solution is pretty easy one hard-coded solution is pretty easy one thing you have to notice is if we look at these test cases third max here's one that's obvious third max here doesn't exist so we return the maximum because it says to do that says if it doesn't exist return the max so there's no third number at all so you wanted to search around the max of these two which is two in this case look at this is what we have to know the third maximum here means the third distinct a number so what I would have thought is okay we have a three this is the max second max this is the third max but that's not the case it needs distinct numbers so apparently both of these counts the second max so that's something we really have to pay attention to okay other than that the solution I'm gonna go with is just having three variables for Max third Max and second max on third Max and then just setting them as we loop through a linear solution not exactly scalable if you want a scalable solution you might want to use like a heap and then you can go up to whatever number you want like the seventh maximum or eighth maximum I think a heap would work in that case but we're gonna use the integer class because we can actually set these variables to know at first which comes in handy makes it a lot more smooth third max sorry equals no just for this loop because we can loop the for num nums and what we can do is we can say okay if max is null first of all or if no the current number is greater than the max that's when we want to set the max to the current number right because if it's null anything is gonna be greater than the maximum it's null right so if it's a negative 50 is better than null so we set it to whatever number after that if it's negative 50 and then we see like 100 is greater than negative 50 so we want to set the maximum right else and then we'll just copy this if and this is gonna be the same for the other ones pretty much it's gonna be except if second max is null in num is greater than second max if third max is null and numbers greater than third Max and we want to say my second max is equal number max as you go along so if second max is Nolan we find a number that's after we set max then that'll set second max to the current number which is better than null same for third Max and if we find a greater number it'll set those so this is all good the only thing we have to worry about this is fine right third maximum gets set if we find a number greater than the third maximum it gets set that's fine if the second maximum gets set you have to think about this the second maximum then gets bumped down to the third maximum because we're finding a number greater than it finding a number greater than you know we have the highest number the second highest number and if we find a number greater than the second highest number it's like you got passed in a race so it gets bumped down a spot so it would actually become the third maximum so what we want to do is run a third max equal to second max before we lose reference to it so before a second max gets set to the greater number we'll just set third max the second max because it got bumped out and it's the same exact idea for this when we find a number greater than the maximum we the second maximum to the maximum because that gets bumped down and we set the third maximum it's at the second max before that happens as well so we don't lose references and yeah this should be good to go the only thing like I said earlier is we have to worry about those distinct numbers so that's why we use that wrapper class because it's easy we can do dot equals and just check if well first of all the null part is good because you could have set it to null and we could check if it was set to null and also the wrapper class is good because we can use dot equals and say if num dot equals max or second max or third max it's not distinct so we can just continue through the loop there's no point of even doing anything because it's not gonna whatever operations we do are going to be useless with these numbers all right second max is set to 2 and we see another two it's gonna we're not doing anything like we saw in that example right so when we see this two we set second max to two and then we see another two when it's like okay well nothing's gonna happen it's still the same so we just continue now all we have to do at the end is these will get set throughout the loop this is just a linear loop through the array third Max is null at the end like the problem description says we just want to return max otherwise we can return third max and we should be in the clear so there we go that's your linear solution if you're looking for something scalable so that like they can give you like int K where K is the you know whatever degree maximum you want like the 7 if K was 7 you want the 7th max or if Kate was 6 you want the 6 max check out maybe using a heap or something like that's probably a better idea but it does take up space so if it's strictly this question you want to do the hard coded version so for this specific question this was a perfectly good solution linear time let me know we get think let me know if you have any questions think it's pretty straightforward pretty easy and appreciate you guys lovely everyone that watch the videos thank you guys I try and make them as much as I can if you have any problems you want me to do send them in the discord that's it thanks for watching see you in the next one
|
Third Maximum Number
|
third-maximum-number
|
Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_.
**Example 1:**
**Input:** nums = \[3,2,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
**Example 2:**
**Input:** nums = \[1,2\]
**Output:** 2
**Explanation:**
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.
**Example 3:**
**Input:** nums = \[2,2,3,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Can you find an `O(n)` solution?
| null |
Array,Sorting
|
Easy
|
215
|
349 |
hello guys my name is Arsenal and welcome back to my channel and today we will be solving a new lead code question that is intersection of two arrays with the help of JavaScript so the question says given to integers array nums one nums to written and intersection of their array each element in the result must be unique and the result the and may return the result in any order so if the word unique comes we have to create a set actually here so unique means that every value should be distinct so we will be creating a set obviously here so then we will be applying some method here so what actually we are asking is that we have to take unique values from here and the and check for that if the if they are if they have intersection here so if you check that the intersection of this is 2 here because two comes twice here but we have to only return one time because we have to check for one uh one time only because it should be unique so if I put a side method here it will give me one two and it will give me two so the intersection will be 2 similarly here four nine five and nine four nine eight four this will after applying the set method I will give I will be getting nine four eight so their intersection would be nine four or four nine in any order is accepted so we can uh okay give the answer in any order but uh but the trick is here that we have to uh put the distinct value so let's start coding this and just before starting solving this question in case do subscribe to the channel hit the like button press the Bell icon button and book bar bookmark the playlist so that you can get the updates from the channel so my first step is to create a set here let set 1 is equals to new set that if my numbers 1 and let's set 2 is equals to Nu iser XX set that is my number two actually numbers it should be numsu not num2 okay now I will be creating an empty array here in which I will in pushing the values of the set so if numbers one what here I will be getting um what uh set one will be having uh one and two and here I will be getting only 2 so I will be pushing all these values here this and apply for uh that they are intersecting or not so for that I will be using for well of say let to end of um set to one meets these values of I mean these two I am considering this value 1 2 of that so if means if said 2 dot hash means as this value or not then if they are then push those Revenue and I will simply return array now run the code now okay so I have everything put some error here what actually is here is new set okay so I have 2 means use the capital here not small because this r p I guess a key sensitive yeah I am getting the answer now uh I have already applied for multiple test cases so you see that we are getting the values here so you know that if you instead of value if I put I also or any other variable it will give me the same answer if I put I here or anything you want to put keep the input it will get a cell we still will get the answer okay so the trick here was to create an empty uh array and then we obviously we have to create two sets because we have to take the unique value so whenever comes the word unique so we have to uh think that or think of the possibility of creating a set most of the chances are creating uh is to create a set so that we can get the distinct value then I've created an empty array and I have push all the values which are inside two and set to 1 so first of all I'll check for uh for set I uh then values in set I is equals to it if it has means all the values of set I are if in this set 2 then push those values in uh array so let me write it well only because it is more readable so that's what this was all in the question guys hope you have understood the concept hope you have liked the video thank you guys for watching the video and see you next time
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
173 |
Hello Hello Everyone Today Going To Solve - Rider Hello Everyone Today Going To Solve - Rider Hello Everyone Today Going To Solve - Rider Problem Points Problem Will Have To You Have Given Now Edit Class Book And Have Implemented 251 Construction In Which Were Given You Will Be Beat Team And Root Of BSP End Have Time Hans Wishes Numbering Traversal Tubelight Both point Amazon Alex element in BSD and next will return data element OK so that SMS withdrawal oo a blatant element full episode 115 surplus drug sells hi honge se zara Subscribe now to receive new updates problem subscribe button and traversal preorder traversal subscribe to ar Rahman 935 Veerwati Ne Return 0 Subscribe Want to Know The Best Different To-Do List Will Return To-Do List Will Return To-Do List Will Return Non Evils Pain Ne School Where Does He Not Only Will Run Lutaaye Ours Ego Ok What We Can Do It Is Begins To Denoy Driver Ne Sansektor 30 Hai Jhaal Independence Look Behind 204 98100 Happy To Help Next Jewelry Beginners Take That Is Our Eye Is Loop Our Back Side Not A Glue Subscribe BSP Meanwhile Student Suicide 208 A Nasty Possible Otherwise Essential Not Possible Then Must Be Remembered And That SMS Function Hands Return Gift You can see a and edit ankit ki android platform 18182 for the next vijay split in this valuable comment aayi to varvar ko kuch der possible aa gaye lesbian that they two not need to take and subscribe button subscribe pluck e agree with you Friends and Next and the Hydrate Avengers Dual Inorder Traversal and Supply Department Up Subscribe Time and Space for Traffic for the Time Chiefs of Mike Ludhiana Refer Into Each and Every Element to Make a Model Travel White Forces Wave Yourself and Time Complexity of the Switch Off One End Next Video One End Disbelief And You Need A Speech I Will Be Online This Zinc Space For Pack And Is Higher Oil Or Elements Mode Winner Last Point Question Nirbhik Tube I 16 Portion Will Be Can Reduce The Space Complexity To 9 Inch Delhi's Curved Honge from nod32 phase Baikunth and to lo facts in every state under estimate allegation will be and Amit that in these to in every age it will augment candidates from space and to lo fat to switch off food across by looting much tensed director that in the world that Just Tell Me What Is Life Instituted Of Inorder Traversal Smiley Inspection Yes 8959 That Will Be My Videos Widening Maths Law And Order A Personal Call Me Store In This Quest A Post Previous One To Do Something Similar To The Tune Of That And Put All Heart Element Given Report All Elements What Will Be The Top Talk With Me Vansh Element Which Acts Like A Smaller Limit Will Mean Of Airtel App Vighn Element Flash Light Chalu Karo Ki And Distic In Distant Villages For All Elements From 7th Points 69 108 Length Reel A National Element Left For ever going to exhaust fan who is this spiderman and only want all the left element and free mode on debit the written test will be written where will return tower than oak voice mail installation of that all divine torch light element will be the noida elements of the state Or Not Good Post Issue So Let's Move To 9 Benefits For Boys Were Written 70 Posts 473 761 Udayveer Vibes Pe 198 Most Influential Ki Nano Der Left Element Is Pluto Woh Sunao Next9 Admin 02's fast will return to aise zor limit me to go To How To Celebrate The Festival With No Limit On That Media On Difficult To Any Element It Means It's Possible Next Element Will Be A Few Positions Left Unchanged Officer This Is The Code Of Pollution In Which Year You Ringtone Laptop Hue Bread First Of All Will Just For Awareness 430 An Order Traversal Inorder Traversal List And All Elements In The Back To Back And Wife And E Connect With Just Everywhere Ways Just Returned And MS Word Elements Were Great Value And Improvement Of National Inter OK NY Just That Is Not Want to request no say no TV channel subscribe admin kids have admitted in pills suicide notes element will be left to beg for this is the worst position let's discuss the second position on karo it is difficult to obtain in during this time that is instituted Vector and will just first all its left will not be in the Thursday he not forget I not a national awardee died while the next five years of elements and influence or extract top right element is written as value only and take good wishes not possible and elements Are Not Hidden in the House for Rent in Description Thanks for Watching
|
Binary Search Tree Iterator
|
binary-search-tree-iterator
|
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST):
* `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
* `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`.
* `int next()` Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST.
You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called.
**Example 1:**
**Input**
\[ "BSTIterator ", "next ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 3, 7, true, 9, true, 15, true, 20, false\]
**Explanation**
BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `0 <= Node.val <= 106`
* At most `105` calls will be made to `hasNext`, and `next`.
**Follow up:**
* Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?
| null |
Stack,Tree,Design,Binary Search Tree,Binary Tree,Iterator
|
Medium
|
94,251,281,284,285,1729
|
40 |
hello everyone in the previous video in the backtracking series of permutation combinations we have discussed the problem combination sum 1 that is the 39 so in this video we will discuss the problem 40 that is the combination sum 2. so the problem statement is saying given a collection of candidate numbers candidate and a target number target find all unique combinations in candidates where the candidates number sum to target right each number in candidates may only be used once in the combination note the solution set must not contain duplicate combinations so if we talk about the difference between the previous problem that is 39 combination sum with this problem that is only be used once means the number whatever is present here so that number only we can use once not twice right suppose for forming eight previously what we did is we add 2 4 times so 2 plus 2 and made 8 and that was a valid combination in the previous problem but that is not the case here we have to only use the number once and one more thing here present is you can see that one number can present twice or thrice means not one time so here if you see one is present twice so that case also we have to handle because here it is saying the solution set must not contain duplicate combinations because 1 6 is answer may be later point of time by calculating you will get again 1 6 right so that time it is not a like unique solution right because as we have like numbers which are repetitive so that's why we have to handle that case also so how we will solve this we will now check so first thing what we will do is we will directly copy and paste this 39 combination sum solutions problem and we will check why it is failing and what to fix here okay so i will just copy this problem from here and we will go to sum 2 and i will paste it here okay and now i will run it so if you check here we are getting answers like which are combined to 1 and it will end up to result 8 but this is not the use case right so 1 plus 1 like 8 1 combined together 8 is not allowed because it is said the numbers we can used only once okay and we can see if we scroll down a bit uh there are so many repetitive results so if you say here one it was present before also right but we need a solution which should be unique okay because we want the answer is one six one two five one seven two six here whatever numbers are present that we just take to once from this candidate list and uh the solution is also unique okay now we have to check uh like why this solution is not working and what kind of modification it needs then ah the purpose will be solved let's take one example and understand it more we will draw the backtracking tree diagram and lot of things will be clear from here and i hope you have watched the previous video because it's a continuation of that so you will understand more like if you have watched the previous video and it is highly recommended so now here uh i have taken one array two one five six five here if you check this five number is repeating okay and the target value is seven so in the previous video what i told is if we have to find any target sum that time it is always better to sort the array first because maybe the target will be very minimum value and for that purpose we do not have to visit the numbers which are higher than the target value because that will not contribute to the solution right so now uh in the previous case what we are doing is suppose we are starting from 1 so let us say take this one and we want to find combinations using this so we are using all these numbers right so maybe another tree will start from one ah another one will be two that means it's a sequence like my result contains one plus one as of now and here it contains one plus two then 5 then another 5 then 6 and then 7 right so from each and every one solution we are again doing like 1 2 3 like that way and for 2 we were checking from 2 then 5 and that way we are going up to seven here also up to seven from five we have to go from five till seven for six it is six and seven for seven uh we can again use only seven if it is permitted right and what we are doing is we are keeping the result sums means one plus one like that way for that path and if it is reaching say seven uh then we will say that we got the target value so that's why if you see in the when we use the previous solution that's why you have seen like one plus one together it formed eight and that we collected as a result okay but in this case we should omit that thing so ah if you check here when it was one that time in the next level i have choice to use one two five six seven in the previous case when it is two then we have choice to use two five six seven when it is six it was six seven that means the number from where it is starting then till the end we can use them to create the next combinations but uh if you check here suppose here say one has i value as 0 right suppose the index position is 0 in that array next time uh as we are again starting from one two five six seven so it is also zero then one like that way it is growing now uh like i will change the color it will be better so now let's say uh why it is repetitive because next time also we are starting from the same index position here also if you see two's index we are again starting from here five also same but instead of that if we start from i plus 1 that means next series if we start from i plus 1 instead of i then we can omit this part right then this one will be not repeated in our answer we can only make choices 1 then it will be 2 5 and 6 7 like that way okay then we can omit this one so we have to start from i plus one so now let's do this modification first and check like uh how our solution is behaving so now the first thing what you will do in this solution is instead of i in the next level we will pass the start as i plus 1 okay and see what it is doing so now here if you check all this 1 plus 1 those solutions are vanished means here at least we are using the numbers once but here also one problem is there maybe we are getting the result using one but some results are repetitive one six uh is one but one two five we got here also right one seven we got twice okay so this two value we got twice that's why it is not matching with the expected result now we will discuss why this thing is coming and how to resolve this now let us discuss why the repetitive solutions are coming and how to avoid that and what is actually causing that problem so here i have drawn the tree for 1 so if we are starting with 1 then the next choice will be two five six seven which we just now rectified like previously we were starting with one two five six seven but as we discussed that we have to start from i plus one so if you check like the tree how it is growing for one the next step we can take as two five six seven for two it will be five six seven four five it will be five six seven four six it is seven and four seven nothing right now if you look closely that uh here the solution is one two five one path is there maybe it is not the solution uh just the path i am talking about and we can see another reperting path as 1 to 5 here so if you follow this path right this is also 1 2 5 this is also 1 to 5 and if you look closely one path we have as 1 5 6 and we have another path also that is also one five six this one right and uh one five seven also see one five seven and here also one five seven is present right so repetitive paths so why this repetitive paths are coming and what will be the solution let's clean up it a bit okay now the path here if you see it was one two five and here also it was one two five right why it is coming because when i am here my left side adjacent value is also same as me that's why if i grow it ultimately some portion will be same here in this example you will better understand this here 1 then it is 5 right so ah when it will grow then five six seven it will be right so after six and seven that will be a complete match see five six seven and this part if you check it's a complete match because my left side number is same as me that means practically there is no need to grow this tree if my left side value is same as me already and that we can easily achieve because as we already sorted that means if any duplicate numbers are here already present they will be grouped together right so if we have five another five okay so only grow the tree for five no need to do anything for this one and this one because they will contribute to repetitive uh combinations so the solution will be if i see that my left side value is also same as me okay then that time no need to grow the tree okay because that will create repetitive things one five six one five seven again it is one five six one five seven right so only do for the first one no need to do for the second and going onwards so we will modify this part in the solution now so now we will do the modification here so what we will do is we will put a if condition here so what is the if condition if my i means the like index is greater than start that means i am in second onward positions right and uh if the candidates are as i position which is my current position is equal to candidates of i minus 1 means my previous position then nothing to do we don't have to form any uh dfs tree for this and we can skip it then only we are done so if we now run this we are getting the exact result now we will submit this so it is working thanks for watching
|
Combination Sum II
|
combination-sum-ii
|
Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.
**Example 1:**
**Input:** candidates = \[10,1,2,7,6,1,5\], target = 8
**Output:**
\[
\[1,1,6\],
\[1,2,5\],
\[1,7\],
\[2,6\]
\]
**Example 2:**
**Input:** candidates = \[2,5,2,1,2\], target = 5
**Output:**
\[
\[1,2,2\],
\[5\]
\]
**Constraints:**
* `1 <= candidates.length <= 100`
* `1 <= candidates[i] <= 50`
* `1 <= target <= 30`
| null |
Array,Backtracking
|
Medium
|
39
|
235 |
hey everyone welcome back and let's write some more neat code today so today we're gonna solve lowest common ancestor of a binary search tree and if you recall a while ago in a video i showed you guys this sheet of the 75 blind problems that have become pretty popular and so this is basically a spreadsheet that i showed with an entire list of those problems and i've actually ended up making videos for most of these problems so far the video that we're doing today is actually going to be lowest common ancestor one of the few problems that i haven't done yet so i will be linking this sheet in the description if you do want to take a look and i'll probably be trying to wrap up most of the problems in this list i think one of the next ones that i'm going to be doing is alien dictionary because i really like that problem and once i've gotten this entire sheet of problems done i'll probably be making a playlist for it but for now you can watch the videos that are currently available for this list of problems so in this problem we're given a binary search tree and we're supposed to find the lowest common ancestor of two given input nodes in the binary search tree and so the lowest common ancestor is basically defined as being the lowest node in the tree such that p and q are descendants of this node or p or q happens to be equal to this node so basically what we're saying is six can technically be a descendant of itself so for example in this problem in this example we're given p equals two q equals eight so we're going to start at the root because the root is always going to be a common ancestor of every single node in the tree right that's just kind of basic right for you know this node in this node of course this is going to be a common ancestor it's not necessarily the lowest common ancestor but it is a common ancestor so what we're gonna see is p is less than six therefore it's going to be in the left subtree and it actually happens to be a direct child of six eight happens to be greater than six so it's gonna go in the right subtree so basically if we went in the left sub tree two is two going to be a ancestor of two and eight of course not right two can't be an ancestor of the node eight if it's in a different subtree similarly eight is not going to be a common ancestor of two so basically if we look at this level or if we keep going down we're never gonna find a common ancestor between two and eight so the lowest one that we found ended up being six so we notice if there's a split between the nodes that p and q are going at if they're going in separate sub trees where that split occurs is going to be the lowest common ancestor so if i change this problem slightly and i gave p as 7 and q as 9 we would once again start at the root because we know this is going to be a common ancestor of these two nodes and so now we're going to check okay 7 is greater than 6 right and 9 is also greater than 6. so therefore we don't need to search in separate subtrees we can just go to the right subtree to look for both of these values we know that this is not going to be the lowest common ancestor this could potentially though be the lowest common ancestor so now once again we're going to repeat that we're going to say 7 that's going to be less than eight so for a seven we're gonna have to look in the left subtree nine is greater than eight so for that we're gonna have to look in the right subtree so since this is where the split occurred that means this is going to be the lowest common ancestor for this input so we would return this node as the lowest common ancestor so one last case is if we changed q to be a six so once again we would start at the root right before we were checking if p and q were both greater than six then we look in the right subtree if they're both less than six then we look in the left sub tree if they're if one of them is in the right sub tree and one of them is in the left sub tree that's how we know this is the lowest common ancestor but what about the last edge case where one of these nodes happens to be equal to the root node in that case this is potentially the lowest common ancestor it's definitely a common ancestor of both of these but now if we go lower for sure none of the descendants of this node nothing in the left subtree or in the right subtree is going to be a ancestor of this node itself right so basically if we ever reach the node itself for example six then that's going to be the lowest common ancestor so it's an ancestor of itself and it's also an ancestor of seven which can be found down here right so this problem isn't too difficult once you can kind of understand that if there's a split between these two nodes then that's going to be the lca the lowest common ancestor and since we're doing it this way we don't have to visit every single node in the entire tree so the time complexity is not going to be big o of n it's going to be log n because we're only going to have to visit one node for every single level in the tree so basically the time complexity is the height of the tree which is usually going to be log n and the memory complexity is just going to be big o of 1 because we're not really needing any data structures or anything like that being said let's jump into the code now so as i mentioned we are going to start ourselves at the root node and we're basically going to continue until we find our result so we're guaranteed to find a result p and q are guaranteed to exist in the input tree so what we're just going to say is while current is not null now it's never going to be null because we are going to find a result but this is just a way to get it to execute forever until we find that result so one case would be if the p-value and so one case would be if the p-value and so one case would be if the p-value and the q value were both greater than the root value or the current value that we're visiting and in that case we would have to go down the right subtree so since we're going down the right subtree we can update our current pointer to current dot right now the else case is basically going to be the opposite of this so i'm just going to copy and paste that basically if both of the values happen to be less than the current node that we're visiting in that case we would want to go down the left subtree so in that case we can update current and set it equal to current dot left now the last case is basically if our split occurs or if we end up actually finding basically finding one of the values p or q and in that case it basically means we have found our result either way so we would just be able to return current itself now we don't have to put any return statement outside of the loop because we're guaranteed that this is going to execute at some point so as you can see this is a pretty efficient solution so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Lowest Common Ancestor of a Binary Search Tree
|
lowest-common-ancestor-of-a-binary-search-tree
|
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8
**Output:** 6
**Explanation:** The LCA of nodes 2 and 8 is 6.
**Example 2:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4
**Output:** 2
**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[2,1\], p = 2, q = 1
**Output:** 2
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the BST.
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
236,1190,1780,1790,1816
|
513 |
hi everyone welcome back to the channel and today we're going to solve it code daily challenge problem number 5133 find bottom left tree value so it's a really simple problem to solve and we'll first check out the problem statement then we'll look into the approach which you're going to use and towards end we'll see the code as well so starting with the problem statement it is given that uh given the root of a binary tree return the leftmost value in the last row of the tree so let's take this example uh in which we have uh these seven nodes and uh we have to return the leftmost element so basically four and seven qualifies for it of the last uh level of the tree so seven is the answer okay so this is what we have to do and uh we can simply use the uh simply solve this question using the bread for search approach and what we will be doing is we will be maintaining a que and we will initialize it with the root element okay at every step like uh whenever we'll go into the Q we will take the first element of the Q at that moment for example uh we are in Q at the moment right now okay so I'll write a loop saying uh while we have element in Q's I want to basically pop uh element from the left side of it so I'll write it like current Q dot pop zero okay so basically uh pop uh removes the element from the right by default but if you add zero in it will uh you know pop the element from the left so this is uh the you know this is how we will be traversing it and when you pop the element it basically gets out from it okay now check if uh whatever node you have popped is has your a left and a right sub tree or right yeah node or sub tree whatever you want to say so if current dot left then we will add that in the tree and if current dot right we will add that into the que again so it will look something like uh write let's say three and two okay so uh If You observe each time you know when you are entering the que you will have uh elements like for example in the first iteration you just had the RO in the second iteration you will have your this level okay in the third iteration you'll have this level in the fourth one you'll just simply have this one so this is what exactly is happening and if you just keep a track of the current you will basically get your answer from the question okay so let's uh check out the code for the same it's going to be a really simple one you to write as well so here what we are doing we are maintaining a Q and uh we have initialized our current uh value with the root node itself okay so you know if uh the tree only had the node the answer will be root right and we initialize the que with the current node or the root node whatever you want to say now I'm running a loop uh till we have elements in the CU and uh we like at every step we are just uh taking out the leftmost element from the Q as a current value and that is the value which we want to return at the N okay and if we have any value on the right we are appending that in the Q if you have any value in the left we are pending that again in the CU and towards then we are simply returning the uh you the value of the node which is in the current uh variable so let's check out the test cases and as you can see the test cases got clear let's submit it for further evaluation and the solution was accepted I and like run time is not that great so what you can do is like instead of using a simple uh list or array you can use DQ or Q uh methods which are uh you know python based methods to maybe more optimize it but yeah this was the solution guys thanks again for watching out the video stay tuned for PS don't forget to like the video and subscribe to the channel thank you
|
Find Bottom Left Tree Value
|
find-bottom-left-tree-value
|
Given the `root` of a binary tree, return the leftmost value in the last row of the tree.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,2,3,4,null,5,6,null,null,7\]
**Output:** 7
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
328 |
so the first node is considered R and second of this country are even and so on so note that the relative order inside both even and Earth should remain three and yeah I could say that you have questions with alternator so they're in the so you could see this link is starting with the order so ordinable with first and then even though but the relative ordering replaces in two and four and also they will start with even note so even notes are all first then all good so all liquids will contain our head and even an interesting content in your hands so let's you know in this example if you take this example now so all link is this content uh first notice or so all linklets want to help but if you see even head even necklace then one head will count to a head dot mix because this is the first you are not present so headed out next one so now this is the head of the two nucleus and we need to have one no for both our head and your head request so we will have t work or we will have one counter or something to order that is foreign so if this is particular now we can say the next given node is present to r dot next so or equal to all dot next so after this given next table node is present so the this is odd head even head so this will contain one emission and this is the next element to this is three and now even the next will be equal to on the X that is over here so now Point even equal to P 1. so even using so even you know multiple content so next again similarly start again so get this and point it over here and all the way so this one more in here together I even look next video so all those things will continue so even not next month introduction so at this point e or equal to one so at this point zero you can stop this nut so until D1 is not equal we have to do this same thing so here is this one now walking into the human responsible no every question is that no all the dot next whatever you have for that I'm given Dot so on top next hence the relative ordering units the same and they start from here so this is R and this is P1 Super Eight percent Contour here so R will move here again great this folder and even you know here and even if so at this point you can stop next this is no the resultant inner one and then three then two and four it is our head this is your head so r dot next whatever that will point to given dot head so two conditions if you enter the nucleus is in order then uh even not equation with length of the increases even then even though X is not detected until then this condition is but in this example we started off seeing the almost to all and on because if the filter starts with even it doesn't matter because as they said alternately they have ordered so if we started or then this is sick so yeah we can start writing the code now list mode or head is thank you for traveling travels into our head linked list so next will be foreign yeah well in the life of P1 not equal to 12 and even dot next dot equal so now r dot next will be equal to even dot next and R will be equal to r dot next so next given dot next will be equal to Odd as X and even if foreign
|
Odd Even Linked List
|
odd-even-linked-list
|
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second** node is **even**, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,3,5,2,4\]
**Example 2:**
**Input:** head = \[2,1,3,5,6,4,7\]
**Output:** \[2,3,6,7,1,5,4\]
**Constraints:**
* The number of nodes in the linked list is in the range `[0, 104]`.
* `-106 <= Node.val <= 106`
| null |
Linked List
|
Medium
|
725
|
218 |
hello friends today less of the skyline problem so we are given array of the buildings and actually this means the location and the height of all the buildings so we need to first get the outline of all the buildings and finally we output the key point and the key points means the left end point of a horizontal line segment so if the given buildings are these five buildings we should output to this line at this point but we do not output this point because it has a it is overlapped with this red building so we only output to this point and we do not output this point because it's not the left of this horizontal segment but we mean that you output at this point because this is the rightmost building ends so we also needed you I'll put the last key point which has a zero height so for this two building we needed to output this point in this point so how to solve this problem I believe you will have the intuition that this problem needs us to do the sort thing why because you see we need to iterate these buildings but the given buildings are not so cheedo so we first need to source these buildings by is left index for a given building we have this left index right index and is height so it seemed that we need to first assault all the buildings by their left index and we iterate all these buildings and try to get the after endpoint of the same horizontal segment and as I said before you see for this green beauty we do not add at this point because it's just lower than the red beauty so it's in there we also need to record the highest building chill now so how do you cancel like the highest beauty the max Keeble is suitable for this question we can get the largest element in log n time complexity and also we also needed to note the end of these buildings so how do we know this is end you see for everybody we have its left in that array index so when we try to process the left illness that means the start of this beauty but when we try to hand out the right index that means we have finishing I've finished the process of this building so that means we need a like a map for the key like the left to index right index and qu its beauty so there's the use of this map but at first we needed to solve them so why not we just use a sajdah map that is tree map for every beauty we map its building through the left index and the right index so this is the true imported data structure we may use one is a tree map another is their heap okay let's see how do you use these two data structures if we are given buildings of these five buildings this is to nine this is a high ten and this is 3 7 15 and there will be 5 12 and 12 this is the story building and then 14 2010 there will be 1924 and 8 so as I said we already know that key points and we needed to build a tree map so basically you followed given five buildings we may have 10 key value in the tree map but actually you will find that maybe sometimes they have the same index you see this example we are we have these two buildings 0 2 3 and the 2 5 3 this is true beauty and they have the same index which is 2 so we cannot simply use the integer map to an int array because they may have the same index so we should use a list here okay that's there since you need to pay attention to and then we get for this to give an example we do not have the same index so we have their ten key values map so this is a ten Kim Bell map and as in the tree map so it's so cheated two three okay so how do you know that is the end or after a beauty women I mean is the right index other than the left index we just need to compare the key with the index zero value like if this - with the index zero value like if this - with the index zero value like if this - if you quote to the truth that means it's the left index and for the line the nine not equal to the two so we know that is the right index so we have finished a process in this beauty okay so how do you get a result we iterate this tree map for this two we find it's the you court user p0 we call this array B so this is B 0 it's the same so we know this left index and as currently the results list is empty so we know there must be left endpoint of the whole and whole segment so we just put this true team intruder result to this now the first will be the truth hem and then as this is the same is the start we start two processes building so we put this building into the heap and then we process this R is 3 7 15 is still the same so we this is a new building so we put this beauty into the hip and now we find the max height of this hip is 15 now his 15 right is 15 and we find the real result is the last Butte that's the point we save in the result list is this 10 change different from this 15 so now we know that we needed to save this 15 height into the result list so we will save this 315 to the result list okay then keep going then we try to handle this firefighter of listen already it's also a new building because five new core tutor be zero and we also put this building into the hip so we get a 5 12 and now the largest height in the beauties is still this 15 and the last height in the readout is also 15 so that means we do not need to save this height in the roof dollies that's correct then we keep going then we try to handle this 7 3 7 15 because they were not equal to the B 0 we know that is the right index of a beauty so we remove their building from the hip we remove this beauty and now currently the maxima high in the he meets the 12 right in the trough is different from the last height in the result list is 15 so now we needed to save this 12 so we will save this 9 12 into the result list ah actually it should be 750 well yes it's 7:15 because the current leak is 7 so we 7:15 because the current leak is 7 so we 7:15 because the current leak is 7 so we save this seven chops sorry I made a mistake because the large in height is 12 so we saved this seven tough into the this yes it's correct okay then we will process this 9:00 to 9:10 and 9:30 culture that this 9:00 to 9:10 and 9:30 culture that this 9:00 to 9:10 and 9:30 culture that you so we do the same to remove this building from the hip and now they only left one building in the hip which is a 12 and the trough equal to the last hiding a result so we just keep going and then we try to process the 12 fighter up 12 which is this line actually and we find it's different so we also remove the fighter of tougher on hip so currently the Hiba is empty and here it's empty we know we have finished processes buildings who needed to add the rightmost end point into the result list so we will put this 12 this is a kid of zero into the result list and so on so forth and finally we will get the correct answer okay that's our algorithm so if we you are nothing you are not sure what is the key point you may try this example this is a buildings of this the location in the height of these given buildings and that is the correct answer of these key points we will see this is the laughter and also this he left not this one because it overlaps and this one don't care if is only one beauty we also needed two recorders and the point of the rightmost line this one is one this one okay so in summary we needed to just a record a different height so we needed to get the maximum height from the hip compare the height with the last height in the result list if they are different we needed to save the maximum heat sorry maximum height and current the key to the radar list okay so well made the left index we'll put a building to the hip and the otherwise we remove that building from the hip and enough again when the heebie is empty we need a true record to the last and the point okay so we use the tree map and we also use priority queue both two data structures have the time complexity of a times log on because the business okay though there are structures and this is use of in the for loop we iterate this tree map and the folder tree map we will we also have iterator have to reiterate the inter buildings that have the same index okay now let's write the code however you can understand this algorithm we first needed a tree map there will be integer he and the list into array new map we do not need to write a comparator because in default it's sorted by the key extended then for every beauty we will see that pooch if absent zero yes zero we put oh yes so we add this B and there can't be one and we also add at least beauty okay so now we builded this map and it also need a priority queue we also use the in terrain we now meet max here because we get to the always get the max height new priority queue now because we saved by their height so for AP we solved by their beach - a - we also need our their beach - a - we also need our their beach - a - we also need our result list so iterate all the key dynamics a in the map is that we try to get released or they'll have the same index so that will be recorded beings because buildings so Mac get this a then so every building if B 0 equal to 8 which means is the left index we put it out into the heat of that beauty otherwise we eat okay so here if the max heat 1 is 0 equal to 0 L mix with end index so we use our template so temporary will add know which like a right and the height will be 0 the result will add this chunk reduced else if not equal to 0 we first get a max height let's have will be the max heap peak and there will be indexed to so if the result size equal to 0 or without yet last and Plaza height size mines minus 1 we get it and we get there get one right because it's a height don't we go to the max height which means they are different only there are case we need to save that to tutor without every atom viii temporary answers or mass right and the result is temporary so I know you saw result okay thank you for watching see you next time
|
The Skyline Problem
|
the-skyline-problem
|
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_.
The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`:
* `lefti` is the x coordinate of the left edge of the `ith` building.
* `righti` is the x coordinate of the right edge of the `ith` building.
* `heighti` is the height of the `ith` building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`.
The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.
**Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`
**Example 1:**
**Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\]
**Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\]
**Explanation:**
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.
**Example 2:**
**Input:** buildings = \[\[0,2,3\],\[2,5,3\]\]
**Output:** \[\[0,3\],\[5,0\]\]
**Constraints:**
* `1 <= buildings.length <= 104`
* `0 <= lefti < righti <= 231 - 1`
* `1 <= heighti <= 231 - 1`
* `buildings` is sorted by `lefti` in non-decreasing order.
| null |
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
|
Hard
|
699
|
235 |
hello everyone my name is alvaro and in this video i will be covering another problem in the blind lead code 75 problem list today we will be doing problem 235 which is called lowest common ancestor of binary search tree this is one of my favorite problems i've never gotten this one asked in my interviews however i think it's a pretty good problem to you know learn a little bit of recursion and understand the properties of binary search trees and how they apply to recursion so yeah definitely good one to practice especially for beginners that want to start practicing problems related with either recursion or binary surgeries so let's get to it given a binary search tree find the lowest common ancestor of two given nodes in the binary search tree according to the definition of least common ancestor or lowest common ancestor sorry the lowest common ancestor is defined between two nodes p and q as the lowest note in t that has both p and q as descendants okay where we allow a node to be a descendant of itself so this might seem a little bit wordy but don't worry i'll clarify this a little bit example one we are given this tree right here and the two nodes are two and eight so the lowest common ancestor is the six here because if we go further down here right the eight will not be able to be found so this is as low as we can get in the tree so that we can still find two and eight as children of the current root sorry uh because remember that whenever like whenever we're dealing with trees right every node is also a sub-tree of right every node is also a sub-tree of right every node is also a sub-tree of the tree itself so for example if we were given let's say actually let's check another example here two and four this is a good example so two and four here if we go to the left we can still find two and four in this sub tree right here composed of these five nodes two zero four three and five so our lowest common ancestor must still be in here the moment in which we go down and one of the given nodes can't be an ancestor anymore one of the given nodes can't be a child anymore then we already know we've gone over the limit so here the output will be 2 because 2 is the lowest common ancestor of 2 and 4 because remember that a node is allowed to be a descendant of itself here we have example 3 2 and 1 which would be a tree with a two and a one so the output would be two so okay if you want to try this problem by yourself uh now would be the time to pause the video i'll explain a little bit the approach that we're gonna take and then i'm gonna get to program it all right so i guess in order to solve this problem right we can clarify a couple properties of binary search trees or at least just one that's um very useful in here in a binary search tree at least the way it's uh the way that we're dealing with binary surgeries here is that every left child of a node must have a value that's less than that of the node and every right child must have a value that's greater than the value of the node so for example this subtree has all values that are greater than six because they're the right child the right children of six and conversely all the numbers in this sub-tree right here starting at the two sub-tree right here starting at the two sub-tree right here starting at the two have a value that's lesser than six because they are the left children of six now how is this going to help us to find the lowest common ancestor well the answer to that would be okay suppose that we start at a number right if we are at a node sorry we started a node so if we are at a node that has a certain value right if one of the values that's given to us so p is less than the value of the current node and the other one is greater than the value of the current node then those two will split into separate subtrees so no matter which subtree we go to one of them will not be in it therefore the current node will be the lowest common ancestor so for example in six right if we're given two and eight we have six two is less than six and eight is greater than six so no matter if we go to the left child we will not be able to find eight and if we go to the right child we will not be able to find two therefore six will be the lowest common ancestor in this example right we have a six since both two and 4 are smaller than 6 we know that we can traverse to this left child right here because 2 and 4 are both lower than 6 so they will both be in this part of the tree and if i'm not mistaken p and q are part of the tree so they're guaranteed to be there uh p and q will exist in the binary search tree that's one of the constraints yeah so two and four are both less than six so they're guaranteed to be in the left side on the left side of the tree if we were given let's say seven and eight and we started six then we will go to the right child because both seven and eight are greater than six so that will be the way that we will solve it for and what happens when the values are when one of the values is equal so for example here right we traverse to the left subtree and now we're looking at node two and we're still we still have p equals two and q equals four at that point when one of the current nodes when one of the values of the nodes that it's given to us is equal to the value of the root then we will have to return the root because that's as low as we can go we will now be able to find two either on the left subtree or the right subtree because 2 is the value of the root itself in that subtree so whenever the value of the root is equal to p or q i guess p that value and q dot value because p m q are tree nodes as specified in here whenever the root is equal to the value of p or q then we will simply return the root and also whenever the two values like one of the values is smaller and one of the other values is bigger and then we will also return the root and those will be the cases in which we found the lowest common ancestor whenever we don't find it we either have to traverse to the right or to the left and that will be determined by whether all the of whether p and q are smaller than the root davao or if they're greater than it and that'll be it i guess another base case would be that if the root is none we simply return none but i don't think we will ever reach that nonetheless i think it's good to write anyways so if root is equal to none then we return none l so let's write the conditions to find the lowest common ancestor so the first one would be if root that value is greater oh let's see if p value is less than root that value and q that value is greater than root that value so those would be the cases in which they're different or the opposite thing happens so whenever that happens we return the root because remember that's when we would have to bring when the nodes branch out so no matter which child we go to one of them won't be found in that subtree and what is the other case well the other two cases will be when either the root equals p dot value or whenever it equals q dot value or p dot value equals root that value or q that value equals root that value so that point will return root so what are the other cases left well we've already checked whenever either p dot value is equal to that or q is equal to that or whenever they're different so the only two cases left will be when both of them are less than the root or when both of them are greater than the root and in that case we simply we can simply just check one number because we've already covered the other cases so it's good enough to simply just use one comparison so if p dot value is less than root that value then it's guaranteed that q that value is also less than root that value because q that value being equal to root that value or greater than root that value has been covered already by this if statement right here so whenever that happens that means that it's smaller right than the root so we will have to traverse the left substring and return whatever that returns self dot lowest common ancestor root that left and then we simply pass the same notes and the other case will be when p that value is greater than root that value so in that case we traverse the right subtree and that should be it as you can see obviously the as usual like the run times are a bit inconsistent but nonetheless like they should work eventually um yeah so that would be the solution to the problem um what is the run time of this problem well the runtime of this problem uh once again think about it um in terms of the worst case will be if we have a skewed tree in which p and q are the penultimate and the last element in the tree so the second lowest and the lowest in that case we will have traversed pretty much the entire tree so the runtime of this algorithm is big o of n similarly the space time complexity is big o of n because in the worst case scenario we will go d like all a lot of levels deep uh pretty much all the levels except one because we will reach the second to last or penultimate node and at that point we will have big o of n calls in the recursion stack trace so yeah that would be pretty much it i hope you enjoyed the video and i hope that you found it helpful and see in the next one bye
|
Lowest Common Ancestor of a Binary Search Tree
|
lowest-common-ancestor-of-a-binary-search-tree
|
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8
**Output:** 6
**Explanation:** The LCA of nodes 2 and 8 is 6.
**Example 2:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4
**Output:** 2
**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[2,1\], p = 2, q = 1
**Output:** 2
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the BST.
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
236,1190,1780,1790,1816
|
1,277 |
Hello Hi Everyone Today At 2am Let's Solve All The Problem Is Account Square Samay Tricks With All We The Software Give Employment Matric 60 Have Bank Account All The Square Submit Research Form With All Once So Let's Rock Example We Trick Share Loot Of Three Crush 40 And For Columns Sworn In 2013 Loot Columns And Through S And Behave Values Here Let Me Feel Values Here 0021 Morning Here Let Me Feel Values Here 0021 Morning Here Let Me Feel Values Here 0021 Morning Account All The Square Time Tricks For My All One Sharing Basis Of Every Individual One Is That Understanding At This Time Tricks Of This One Crossword Solve That Subscribe 151 Ki And Governance Of Tuk Ra Studio Man Similarly Subscribe Total 20 Subscribe And Subscribe Hello One Two Three Four Square Sub Matrix Of Ki Aishwarya Dabangg Ashwini Stand 9842 Cross Two Square Matrix Form With All Words And Deeds And In This Affair One Here Three Question Square matrix suvan electronic plz join this one state wise zikar samay tricks 200 total feature hai total bhi fifteen samay tricks for this example1 soya answer is pain ko select me.in one more time to clear select me.in one more time to clear select me.in one more time to clear how can we regret problem solve this problem basically An advancement of the problem there is another problem in last man challenge to find the biggest subscribe 18101 matrix whole jawan ka alam hair soft very soft is matrix further in a grease one 2008 problem if you are ladies familiar with the problem is like just very busy but Let me explain the problem that should be addressed Will look at this point The effigy of values in the form of your Idli with a of values in the form of your Idli with a of values in the form of your Idli with a smile Give them one Subscribe The index position with its opposition Weather its form in Superintendent Vasundhara Edison Incomplete Most Obscure Now left channel to Subscribe From This subscribe and subscribe the Channel Now School Re Posted In Dishaon Gram Saunf Backem Soggy 's Market S2 Similarly They Continued For 's Market S2 Similarly They Continued For 's Market S2 Similarly They Continued For These Sides He Also Been For Over Two Years With You He Also Can Not Have Them Into To Do Subscribe In This Live Wallpaper Has to Subscribe My Channel Subscribe Problem subscribe for Live Video Ko Majboor Hain English So Ifin Check Weather How Many Meter Isse Simply Check The Matrix of Measurement Ko Majboor Hain Ki Kaua Tha Aayi Ko Majeor - Ki Kaua Tha Aayi Ko Majeor - Ki Kaua Tha Aayi Ko Majeor - Is Vansh Dutt Is Minimum Vishwavijay Simply absolutely minimum was present Value Safai minus one and that minus one that and after the minimum Africa Coordinator Candidate Looting this one and only then will depend on one's devices so let's start implementation of this problem solve APN is who subscribed to YouTube channel Do and subscribe the channel is written 119 difficult jaisi use metro tracks countless tata coffee with 20 and no uniform login more 1208 sexual matrix dot ninth ki i plus hai aur inko jula20 apne jewelers 10-umar trick shooting length apne jewelers 10-umar trick shooting length apne jewelers 10-umar trick shooting length pm dj plus e Will Check If You The Matrix School The Matrix Oil Good Grade 4200 And Died Later 20 Gene T 20 That Than Gay Tweet Matrix Account Of Matrix Of High To Strong Physical To Maths Dot Min Updates Reviews Mon Admin Of Matrix Of I - Vansh Kumar GD Of Matrix Of I - Vansh Kumar GD Of Matrix Of I - Vansh Kumar GD Form of birth dot meaning of a half the matrix form of eye comedy well - 1m matrix of eye comedy well - 1m matrix of eye comedy well - 1m matrix of eye - one - one - one jai hindi jai - at one in after effect will jai hindi jai - at one in after effect will jai hindi jai - at one in after effect will get minimum balance fear and updater mattresses for this the condition k6 players will guide the Sum of the matrix home and its effects 5210 is the condition mattresses lineage after the hello viewers sample account receiver shop plus matrix of oil kumar jain and after deol process small businesses and account members next right to front is that rotten loot i think they Hey Waiting For Which Is Wrong 200 What Is Missing Hair Matrix Start Length Matrix Iodine Equal To Zero And A Great Think 120 Phone Oil 520 Will Do And Simply Click On Continue And Plus One Is BTS Idol 10 From This And You For The First Love You will get research one to three and asked for this point after death we come here they chapter minimum of match start minimum of this value of management and this will give social matrix of ninth chapter will have wave in this that this here is so sweet absolutely oh hi I Sharing Dhawan This is Very Big Mistake is ID Password Don't Forget to Me to the Quality Sharing Dhawan More Focus Tours and Subscribe for Example 210 More Benefit Little Bit Meerut Ka Mundan That These Just Right First Try Another This Matrix of Just One Shouldn't Start Net Strike Churna Discussed With Concentration And Lucid Dreams What Is Expected To Getting Less Tried To Submit Your Work Code Luti Ne Se Gaya Cutting Special Dish Zaveri Simplest And Easy Solution For This Let's Meet Not Doing Some Places Over Time Complexity Is Form Of M A Game Is Number Of Producer MS Number Of Russia Ki And Animals Number Of Phone Calls Columns Settings And Space Complexity Pimple Which Zinc Want And Nurses Metric Per Gram Thank You Feel Like My Solution Please Like These Subscribe Button For The New Feature Videos
|
Count Square Submatrices with All Ones
|
largest-multiple-of-three
|
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones.
**Example 1:**
**Input:** matrix =
\[
\[0,1,1,1\],
\[1,1,1,1\],
\[0,1,1,1\]
\]
**Output:** 15
**Explanation:**
There are **10** squares of side 1.
There are **4** squares of side 2.
There is **1** square of side 3.
Total number of squares = 10 + 4 + 1 = **15**.
**Example 2:**
**Input:** matrix =
\[
\[1,0,1\],
\[1,1,0\],
\[1,1,0\]
\]
**Output:** 7
**Explanation:**
There are **6** squares of side 1.
There is **1** square of side 2.
Total number of squares = 6 + 1 = **7**.
**Constraints:**
* `1 <= arr.length <= 300`
* `1 <= arr[0].length <= 300`
* `0 <= arr[i][j] <= 1`
|
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
|
Array,Dynamic Programming,Greedy
|
Hard
| null |
509 |
number so Fibonacci numbers by F of n form a sequence called the Fibonacci sequence such that each number is a sum of two preceding ones starting from 0 and 1. so that is f of 0 is 0 and F of 1 is 1. there is starting two numbers so then F of n will be equal to F of n minus 1 plus F of n minus 2 or n greater than 1. then one the next number will be sum of its previous two numbers that is zero plus one will be two for the next number it's somewhere with the previous two numbers some of previous two numbers so one plus two will be three if you go further uh the next two numbers will be 3 plus 2 will be five then X amplify plus 3 will be eight so on so Fibonacci series it's formed by each number will be calculated by the sum of its previous number and its previous to previous number so in this case if you find next number eight plus five will be the answer that will be a team the serious question so this is the first Fibonacci number second third fourth fifth sixth so on so if they tell fourth F of fourth Fibonacci number then F of 4 will be able to find and they have said f of 4 is nothing but F of n minus 1 plus F of n minus 2. so that is what it means this Plus for f of 4 that will be these two F of n minus 1 so F of n minus 1 is nothing but 3. plus F of n minus 2 will be next if you expand F of 3 it will be the previous two numbers will be F of 2 plus F of 1. similarly for f of 2 it will be F of 1 plus F of 0 the previous two numbers now explained X Prime F of 2 that will be F of 1. plus F of 0. next again F of 1 for here so F of 1. and F of zero so we know F of 1 is nothing but one as I said before this is a fourth one and this is f of zero that should be predefined and this is starting to numbers next numbers are calculated from previous two numbers so one plus zero plus one plus zero so total it will be and we have got answers so these numbers recursively we call the other functions over here so how we will calculate this so we know if the number is lesser than or equal to 1 then that we have to return the number itself written either it can be 0 or 1. so that is for sure if not then we have to start the load from I equal to 2 till less than or equal to n I plus so here for this 2 till n lesser than equal to n I equal to 2 it starts so we know if they tell F of 4 then from 1 to 4 you are true right so 1 is already but now we will start from 2 here so you know F of 2 foreign so once you have these two or let's say uh instead of first lesson the second last let's say previous one and previous two previous one will be one and previous row will be zero that is the first previous and second previous zero one so to find the next number I equal to 2 till n we have to find so to find an X number we have to calculate current this is current value so int current equal to previous one plus previous zero plus one so this zero plus one will give you one so this is current and this will be subscripted to here so when we substitute 1 to this current for the next number for the next iteration will come to here right so for the next step here this will be the previous one and this will be previous two so before initializing previous one equal to the new value we have to initialize previous two will be required uh previous two to the previous one value to the previous because this was previous one before and here it is so initial is V is to equal to previous one then change the value of previous one equal to current why because if you directly initialize previously you will lose this previous one value before and this previous two will be again previous current valuation so that's it first initial previous one to previous to value and current will be equal to previous one so you have to make this until the loop ends so for if it is f of 4 we have to find so I equal to 2 it will be 0 plus 1 equal to 1 then I equal to 3 so in this case uh this will be 2. or not this will be one this is previous one previous two again for the next iteration it will be 2 plus 1B equal to 3. so that is the answer which I need to return so we will code this so we will we'll check if we have uh or let's say n is less than or equal to 1 then later in itself otherwise in previous one will be equal to 1 and in previous two will be equal to 0. so next for it I equal to 2 I less than or equal to n I plus so first initial is currently current will be equal to previous one let's previous two next previous two will be equal to previous month so after this spring is going to bridge let's start correct so at last we have to return the previous that will be the Fibonacci number okay this is 0 and this will be one so at that time it will be proper otherwise we can run the loop till otherwise we'll make this back only that let it be as it is so this will be written in okay here instead of previous we have to return the previous one because we are looping till equal to n if it was lesser than n then previous total will be written foreign
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
1,383 |
hi guys welcome to algorithms Made Easy my name is khushboo and in this video we are going to see the question maximum performance of a team you are given two integers n and key and two integer arrays speed and efficiency both are of length n there are an Engineers numbered from 1 to 1 wherein speed of I and efficiency of I represent the speed and efficiency of the ith engineer respectively we need to choose at most K different Engineers out of these n Engineers to form a team that has the maximum performance now what is the performance a performance of the team is some of their Engineers speed multiplied by the minimum efficiency among the engineers we need to return the maximum performance of this team now the answer can be a huge number so we need to return the modulus of it we are given the three examples let us go through them one by one first one we have six Engineers with the speed and efficiency given and we need to make a team with maximum of two engineers so now to choose these Engineers we'll choose the engineer with the speed of 10 efficiency of 4 and with the speed of 5 and efficiency of 7 that will give us the maximum performance which is 60. now let's increase K by one more that is k equal to 3 now the maximum performance that we can get is 68. if K is equal to 4 the maximum performance can be 72 and so on now let's see how we can solve this question we'll take the first example where we are given with k equal to 2 and try to solve the question what are the different approaches that come to your mind one is we take Engineers with the maximum speed and see whether they give the highest performance second is we take the engineers with maximum efficiency and see whether that can give us the higher performance so let's consider both of these approaches and see whether we can get the correct answer or not with that we know that performances sum of speed into minimum efficiency amongst the engineers that we are considering so considering the ones with maximum speed we have these two engineers and if we do the same with maximum efficiency we have Engineers with efficiency 9 and 7. let's calculate the performance in both the cases for the one wherein we have the sum of speed as 18 taking their corresponding efficiency performance we get is 18 into 2 which is 36. let's do the same with maximum efficiency now sum of speed for these two Engineers is one plus five and the efficiency is 7 which is the minimum amongst both the engineers now the performance become 42 but was this the answer no the answer was considering the engineer with speed 10 and speed 5 efficiency is 4 and 7. over here we are getting the performance as 60. so we can eliminate the idea that we can just take one of the things into consideration in order to solve this question we need to take both the things but one thing we definitely know is that multiplication plays a major role in increasing or maximizing your answer so what we are going to do is we are going to try to increase the rate of multiplication for which we are going to start with the person that is having the maximum efficiency now since we need to start with the maximum efficiency person we need to sort this data so what do we need to do is we need to sort the data based on the efficiency and since we need to sort based on efficiency we need to also sort the respective speed so we'll take a pair of integer or we can take an array of array wherein we'll take efficiency and speed so this is our original array wherein this is the efficiency this is the speed of 0th person first person second third fourth fifth index and the sorted array wherein we are sorting it based on the maximum efficiency that is descending efficiency is given over here so in this problem we are going to use this particular input so first step is cleared that is we need to sort the data based on the efficiency and we need to group the data as well now we have this data with us now what to do next in the question there is mentioned at most K whenever something like this appears in a question that is at most K or top K or frequent K wherein we need to find the subset of the input that is given to us and we need to take top or bottom let us Max or Min of it the data structure that is going to come into your problem is a priority queue or a heap so we are going to take a heap now what kind of Heap do you take Min Heap or a Max Heap since we need to maximize the result we will need to eliminate the smallest elements so for eliminating the smallest element we need to take the Min Heat if it would have been vice versa we would have taken Max Heap now we know we need to use the Heap what do we need to store in that Heap efficiency we have taken care of speed is something we are not taking care of till now what happens when you take two elements and you need to see whether you can consider this element or you need to go with the first two elements that you have considered so you need to eliminate the data based on the speed you'll eliminate the one that has the minimum speed and you will take the one that has the higher speed so that means we need to take speed into this Heap so this becomes our initial condition we are going to take a Min Heap wherein we'll be storing speed the Heap size will be the size K that is given to us and we'll take some variables with us that will be handy one is the speed sum that is the sum of the speed that we are looking for the minimum efficiency because the multiplication of these two will give me the performance and the third one is the max performance variable which will hold the result for us now taking into account the first element we have the efficiency is 9 speed as one since it is one single element the sum of speed till now becomes 1 and this is 9. now we won't need this into our code but just for your reference on what we are multiplying and how we are doing it I am keeping this over here but you will get to know that we are not going to need this I am storing this into my mini what am I storing the speed which is 1. now the performance becomes 1 into 9 which is nine maximum performance is the previous performance or this performance so this will give us 9 as well moving ahead we go to the second person now the speed is five sum of speed becomes previous plus current speed which is 6 and the efficiency becomes 7 because this is smaller than the previous one the current performance will be 6 into 7 that is 42 and we can say that current performance is higher so we'll update that and we'll go to the next one considering 5 comma 2 the speed is 2 efficiency is 5 but can I add this into the queue or can I add this to the speed sum and calculate the maximum performance no why because the Heap has overloaded we have more elements than we need we cannot consider three Engineers we only need to consider two Engineers so we need to now optimize which one we need to consider so now we will consider the one with the higher speeds and we'll remove the one that has the lowest speed which is we'll remove one so what we have done is we have added this to which was the current one and we have removed this minimum number which is 1. minimum efficiency over here is 5 C this 5 represents the current iteration that we are on so the performance becomes 35 which is still lower than the one we have got so we will not update it over here and we'll move on to the next one again we see that we have three elements over here so we need to remove an element so which one do we remove two so we add 10 remove 2 and the performance becomes 60 which is the highest one till now so we update the max performance now when we come to this three do you think that adding this 3 is going to make any sense in this Heap because we'll add 3 we'll see which one is the lowest one and we'll remove that part so this 3 will again get removed so there are two options over here whether you keep a check on adding a particular element only if it is greater than the one that you are going to remove or else you can just keep on adding the elements and removing the elements without seeing that it is a lower one or higher one because that is not going to affect this maximum performance score over here for now let's say we don't add it and we move ahead with 2 comma 8. now this 2 comma 8 we have 8 added over here and we'll be removing this five my current performance will be 18 multiplied by the efficiency which is 2. that gives me 36 which is obviously lesser than the maximum performance that I can get considering other engineers since we are at the end of our input the maximum performance variable will have your answer so that's the just behind how to solve this particular question now let's go ahead and code it out so let's take this sne we'll be taking a mod variable which is 10 raised to 9 plus 7 second thing that we are going to do is we are going to make the pair data so this is going to store the speed and efficiency data and now we need to create it so we'll take a for Loop and we'll add it into this pair array so zeroth element is going to have the efficiency first element will be having the speed and now we need to sort this and the Sorting is based on the 0th element which is efficiency and it is a descending order so we are doing B of 0 minus K of 0 that was the first step that we saw Second Step was to take the priority queue and we need to take a few variables which would be long and not end because our answer is going to be much higher number as discussed we are not going to require the minimum efficiency because that is the efficiency of ith engineer that will be upon now we'll iterate over our pair array and we will try to fill the priority queue and find the maximum performance as we go along the first thing that we are going to do is add the speed which is in P of 1 that is the first element in my P second thing that we are going to do is we are going to add this into the speed priority queue as well now there can be a possibility that the speed priority queue contains more element than K so we need to pull that so we check the size of it we pull it and we also subtract that particular speed from this speed sum now the speed sum is balanced the speed is also balanced we need to now take care of the maximum performance variable so that will be equal to maximum of either the previous one or the current one and the current one will be speed sum multiplied by the efficiency which is p of 0. finally we just return this performance but we are not going to return it as it is because this is a long variable we need int and also we need to do a modulus on it so what we are going to do is we will be converting it into int and we'll also do a mod with this mod and that's it let's run it and this is dot Max which I have forgotten it's giving a perfect result for this let's see let's try to run this for all the sample test cases and it's giving a perfect result let's submit this and it got submitted now what is the time complexity since we are doing an arrays.sort the since we are doing an arrays.sort the since we are doing an arrays.sort the time complexity over here becomes o of n log n the time complexity for this Loop is O of n for the priority Qs of n log K because we are going to have the priority queue of size K so the overall time complexity Becomes of n log n because of the Sorting which is the Higher One and the space complexity is for storing this pair which is 2 into n that is O of n so that's it for this video guys I hope you liked it and if you did please do like share and subscribe to our Channel and I'll see you in another one so till then
|
Maximum Performance of a Team
|
number-of-single-divisor-triplets
|
You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108`
|
The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values.
|
Math
|
Medium
|
2301
|
354 |
Loot ok hmm thank you MP3 song bhojpuri that if we have of this period is if we have of this period is if we have of this period is that if we go to the smallest line of the smallest bramble of its species then we can further check that who- Which is bigger so that I who- Which is bigger so that I who- Which is bigger so that I think of it in this so I have done unmute that Abhishek has also switched the bigger one, I keep it inside it and is suffering from one time that Nakul can okay and the height of lover Yashodhara is that Also the last one is cigarette accused here you can see that they have absolutely so think this if you will receive okay then we can say that hands will be available they are fitting inside each other okay so if see the stars here What does it mean if it comes out, if we make a note of it, the dry ginger will make the document, then we will do whatever is incomplete, it is okay that you will miss my reason, you will be bigger than the one who made it, so listen to my ghazal and do it. It is given because now it is the part between us, so yours should also be Anju and the smaller one which will come next, then because if it is smaller then put it on us inside it, oh my Heli, what will we do, okay friends, do we want increasing. Along with this, I can also add that if I say this, the second one will be this, the third one will be this, then it is possible that this may happen, then the second one may be here or somewhere else, it cannot be like this, then this is a week's time. Jadavan is such a person that I will fix everything, he says that we should always maintain the balance of our height here and there, which is going to be found in Aa Gaya Hero, it is fine from now on and we will come to Mexico together, you will have to maintain it. The longest also follows till 2030, so if we find out that we have added the height as well, that yes, whatever will increase, that is, if we find out that the longest is till the age, then we will get as per ours, this is your problem. The voice will come because Singh will be participating. Singh ji, you can take out as much as you can, but I would not like to do the quantity right now, if we have two with the same, okay, friends, see this here, see this one's increase and this one's increase. Even if it is okay for indifference, if it kills us, then how will we use it, keep in mind which one Ponting said is in Ahmedabad, we will have to keep in mind that we have the biggest height, keep in mind why so much attachment. It is famous that there is this thing in it, if we join it in this way, then what happened in it that you understood because the film is English, so the tips are complete, then what will we do that someone is always singing so much and someone is so cowardly that now yours Algorithm will do the right thing and create a problem here Yogi, you will see how to do it. I am angry with you, people are also surgical strike and metro but it gives time but in this case we need recruitment for 50 grams if we put it on inch then green remember the thing. If we want to do this then what will we do, then it is optional which works and is done one-time. optional which works and is done one-time. optional which works and is done one-time. These were the things that we know about photography. Now tell us how it is done. We know that we can log in with this LMB. If there is a vegetable shop then what will we do, we will start, but if we start, then we have kept 131 that you will be looted to the extent of one tomar, so I told 1947 do more scientific and said that employment is suitable for you to make efforts. The fourth one is our 8th photo, that is, you can keep which number is this, just after this we can keep one more, so we said that he kept the salt people like us, what new group did you create and his fire Given the whole that is smaller than the stormy back that I have just come, so I cannot go ahead of it, so what number is it on this side which is just smaller than five, okay, you have kept your whole which is a small one and there is a plant, so I have kept it there. But only Navya can get the lesson, you can see here that it will be visible, okay, which is the number here which is just a small one that Navratri 28 can get success, now this - neither Navratri 28 can get success, now this - neither Navratri 28 can get success, now this - neither can we explain it now, so I said Which is the number after which we can put - in then it is after which we can put - in then it is after which we can put - in then it is not a number so that you have not specified one yet, we can also put in Noida if we can drop it then my knowledge should have made more So I have the sun, it is possible that it consumes all these things, it is difficult, it will be you will be included in it is there, so just look at it will be all right, its answer is the pipe, about what we have a long sequence, isn't it the answer? If we look at it accordingly, here we have a lot of paste your guidance that agricultural scientists can pay, then how can I do this for a week, do you think that we should get it printed, which of my temple committees? Who can be the President? By seeing who is there, we mean by his number, how many numbers are there, that is the number, we will get no end, which is the maximum, if you have a channel, which number has to be entered, then we will give a little technique, a frequent one, that your shoulders will be looted. Lo Sudhir and Then eight from here Now what is the number that there will be more benefits about this now, this committee was done since then I am just What is the number that Amitabh's film Dhoom-3 Dhoom is just And only film Dhoom-3 Dhoom is just And only film Dhoom-3 Dhoom is just And only who are you Will repair this number Pre reduce Hello viewers give the number In the video there is a Coriander two chord A That this is to call Let's hate here To attack here August month ago Hi this is your photo game on if you get Purvi Disha Milegi Tujhe Kar Do [ get Purvi Disha Milegi Tujhe Kar Do [ get Purvi Disha Milegi Tujhe Kar Do I am saying that let's that let's that let's launch that you forget and directly Thank you for watching this video If you liked it then like Thank you so Mach
|
Russian Doll Envelopes
|
russian-doll-envelopes
|
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_.
**Note:** You cannot rotate an envelope.
**Example 1:**
**Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\]
**Output:** 3
**Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]).
**Example 2:**
**Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\]
**Output:** 1
**Constraints:**
* `1 <= envelopes.length <= 105`
* `envelopes[i].length == 2`
* `1 <= wi, hi <= 105`
| null |
Array,Binary Search,Dynamic Programming,Sorting
|
Hard
|
300,2123
|
404 |
foreign called sum of left leaves it's easy let's get started given the root of a binary tree return the sum of all left leaves a leaf is a node with no children a left Leaf is a leaf that is the left child of another node example one we have the root node three then 9 20 15 and 7. so here our leaves are 9 15 and 7 because they have no left to right children but our left leaves are only 9 and 15 because they are the left child of another node nine is the left child of three and fifteen is the left child of 20. so we sum up their values and output 24. example two we have just the root node one so while this is a leaf node it has no left or right children it's not a left Leaf because it's not the left child of another node so there's nothing really to add up here and we output zero so this is pretty straightforward what we need to do is find all the leaves in our tree and also check to see if they are the left Leaf if so then we just need to sum up all their values and finally output that now this is a tree problem and I say this before every single tree problem but it's really important that you know how to Traverse a tree I have my binary tree in order of traversal linked down below if you haven't already seen it give it a watch I cover both the recursive and iterative approaches on how to Traverse a tree so DFS and BFS watch that if you haven't already it's just such an important concept to know because you're going to be using it for any tree problem that you come across watch that it's going to take five minutes and if you're still watching this video I'm going to move forward with the assumption that you already have that knowledge now for this question specifically we want to sum up all the left leaves so we want to go down the tree and find all the Lefty leaves for this we want to go down which means we are going to be using a depth first search and to do that we are going to approach this recursively a quick recap on what a recursive approach is it involves two parts one is the base case that means our end points when do we stop and what do we return there and the second part is our recursive case this is where we actually put the logic together and before we get into all that let's just take a closer look into example one so I have example one right here and for any tree we are going to start at the top the root node three at any node I have three pieces of information I know what my value is and I know what my left and right children are if and so at this top note right here I see that I have both a left child and a child which means I am not a left leaf and there's really nothing for me to do at this point and I can continue traversing through both my left and right subtruths say I go down my left first I am at node nine and I can make checks to see whether or not I am a leaf so I have no love child I have no right child that means I'm a leaf but how do I know that I am a left Leaf because the only other information I have at this point is my own value so something we can do is when making a call so when three calls nine for example we can pass in a flag a simple true or false Boolean that is true if I am calling my left child otherwise it would stay false and we can just keep calling this in our recursive call and if that flag is true and I have no left or right children that means I am a left leaf but instead of doing all of that there's actually something else we can do that's much simpler we can move all our checks an entire level Above So at node 3 I'm going to see if I have a left child if I do I'm going to see if that left child does not have any left or right children in which case that is a leaf and I know it has to be a left Leaf because I just checked on my left child in that case what I'm going to do is return the value of my left child and continue going through my right substrate and if I don't hit that dead point in which you know I both have a love child in that left child's left and right children are none then I'm just going to go through both my left and right subtrees as normal so let's go ahead and code all of this up and then go through it line by line to really see how this recursive call Sac is being built so the first thing we want to see is our base case what if my root is none if there's nothing being passed in what do I want to return then if root is none I know I want to return the sum of all left leaves and this is just my base case the actual logic of the addition will be happening in my recursive case so here I just need to return some number and I'm going to be returning zero because there's really no left Leaf value that I need to return here and when am I not going to be returning zero well that's when I actually have my left Leaf so if root dot left so if I do have a left child and root dot left is none and root dot left dot right is none so I do have a left child and that left child does not have a left child and that left child also does not have a right child that means I have a left leaf in which case I want to return its value so return root dot left dot val now I want to return the value of my left Leaf but there's still my entire right subtree that I haven't gone through so yes this is a stopping point for my left side but I still need to continue going through my right so I'm going to be returning the value at my left leaf and recursively call so solve dot sum of left leaves on root dot right and if I don't really run into this left leaf then what do I want to return the self sum of left leaves on both left and right children so root dot left plus self dot sum of lift leaves on root dot right and that is it so let's go ahead and run this code accepted and submit it and it is accepted as well but before leaving let's go through an example and see what our code is doing line by line okay running through an example we're going to be taking a look at example one again and I'm going to change it up a little bit just so we can go into all the conditions this is my input tree and I start off with the root node three I'm calling this function sum of left to leaves with three so calling it with this what am I going to return here well the first condition is to see if my root is none it is not none it is three I'm going into the second one a if root dot left do I have a left child I do it's nine and root dot left is none nine does not have a left and root dot left dot right is none nine also does not have a right so all of these hold true which means I am in this return I'm going to be returning the left dot vowel which is nine plus recursively calling some of left leaves on my right child so sum of left leaves on 20. this means that now I have to recursively call on 20. I'm going to be going in this function again with root node 20. so what do I return here with 20 being called in I'm back into this function my root is not none and I go make these checks if root dot left it does exist and a root dot left.left is does exist and a root dot left.left is does exist and a root dot left.left is none which is true and root dot left dot right is none that's not true because my left does have a right so I'm not going into here I am out of these two if blocks and going straight into this return where I return the recursive call on both left and right children so I'm calling sum of left leaves with 15 as well as 7. and we read and evaluate left to right so I'm going to be calling 15 first with 15 I'm back in here my root is not none and I'm making this check I actually don't have a left child here so I'm already out of this if condition and I'm just calling this so at 15 I am calling the sum of left leaves on my left child but we know that's none so it's actually going to be calling it on none and my right which is four so again we have to evaluate left to right we have to call then on before we can solve for four and continue back up and if you see this is how our recursive call stack is being built so calling now with none I go back into this function and I see that my root is none this time so I'm going to be returning 0. so I can actually exit out of here and return 0 for this call now I can evaluate for some of left leaves at four so calling this function again with the input 4. my root is not none it is four and now I'm making a check if root dot Left 4 does not have a left and I am in this return right here so here I'm calling some of left leaves on root dot left which is none and root dot right which is also none so here again we have to solve for the left one first so I'm calling this again with none but we know that none is going to be returning zero so I can exit out of this call and return back to my caller with just zero and again we're going to be making this call for his right child which we know is going to be zero it's going to be another call with none and we're going to get 0 for that so at four I'm gonna do zero plus zero which evaluates to zero so at four I am completely done there's nothing else to solve for and I return to my caller with zero so I add 15 I have a total sum of zero that means all the left leaves in this subtree is zero which makes sense there is no left Leaf at fifteen or four so I'm gonna return back to the color of 15 which was 20 with zero and now we have to call again with 20s right which is seven so calling with seven what am I going to return here root is not none we're going to be making this check and I know seven does not actually have a left child so I'm in this return right here I am going to be calling this with none there is no left child of seven and this with none again there is no right child of seven and when calling with none again this is just going to Output 0 so I can pop this off I am done solving for this is simply zero and this is also zero over here at seven we have zero and we're going to return this back to our color to just be zero twenty we have zero and we can finally bubble back up to our original color with zero so nine plus zero is just nine and all the left leaves in this tree is sum up to nine because we only have the leaves of four seven and nine and the only left Leaf is not and this is how we solve sum of left leaves talking about space and time complexity for time because we're going through every single node in our tree that would be o of n if there are n nodes and same with space right if there are n nodes potentially our recursive call stack could go n deep so that space is also o of n if you have any questions at all let me know down below any comments any questions if not I will see you next time bye foreign
|
Sum of Left Leaves
|
sum-of-left-leaves
|
Given the `root` of a binary tree, return _the sum of all left leaves._
A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 24
**Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively.
**Example 2:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
1,377 |
foreign welcome back in this video lecture we'll be solving this problem frog position after T seconds so in this problem we have an undirected tree which consists of n vertices numbered from 1 to n so we have a frog here which starts jumping from vertex one in one second a frog jumps from its current vertex to another unvisited vertex if they are directly connected so there must be a direct Edge from the current vertex to another vertex for the Frog to jump from the current vertex to the neighbor vertex the Frog cannot jump back to a visited vertex in case the Frog can jump to several vertices that is we are standing on a node and there are more than one nodes which are connected by a direct Edge to this node in that case it jumps randomly to one of them with the same probability so the probability to move to any of the of those vertices is same otherwise when the Frog cannot jump to any unvisited vertex this is the case when we have a leaf node it jumps Forever on the same vertex okay now what we are given in this problem we are given an edges array and edges array is basically an array of pairs where each pair represents a two directional Edge between those pair of integers or nodes so what do we have to do in this problem we have to return the probability after T seconds so we are given integer T that the frog is on the vertex Target so we are also given a Target vertex so we start from the root vertex which is vertex number one we want to reach vertex Target we just want to return the probability after T seconds that the frog is on the vertex Target fine that's what we have to return in this problem answers within 10 raised to the power minus 5 of the actual answer will be accepted so this is the Precision for which the answers will be accepted so in the input will be given n representing the number of nodes edges array representing the bi-directional edges in the given nodes bi-directional edges in the given nodes bi-directional edges in the given nodes T which is the time to move from the node number one to the Target node and the target node while the output we have to return a double number which basically represents the probability to reach the target starting from the node number one fine so and let's see the constraints of problem the number of nodes may go up to 100 while the edges must be n minus 1 because it is a tree we know that for a tree having nodes the number of edges are n minus 1 and the nodes are numbered from 1 to n while the time variable may go up to 50 units and obviously the target must be one of the nodes from 1 to n so let's better understand the problem statement using an example so I'm starting in vertex number one I want to go down the tree while making jumps so whenever I make a jump there is a certain probability to move to the neighbor node fine so initially right at the position where I am standing the probability is one let's call it P it is 1 here or 1.0 fine and call it P it is 1 here or 1.0 fine and call it P it is 1 here or 1.0 fine and this is also this can also be one of the best cases like think about when we have exactly one node in the tree in that case the probability is always 1.0 right case the probability is always 1.0 right case the probability is always 1.0 right then we have to move to one of the neighbor nodes either I move to 2 or I move to 7 or I move to 3 so there are three choices to move down each choice holds a certain probability the that probability is calculated by dividing the number of that the node has so for node number one we have three child so I basically calculate so I basic the probability would be one by three the probability to move to node 7 would also be one by three same goes for node number three so let's say I jump to node number two so that's what I'm doing I have Traverse node number 1 I jump to node number 2 and the probability variable has become 1 by 3 then again here I have two choices so I calculate the number of nodes and I calculate the probability to jump to the neighbor node that would be 1 by 2. similarly 1 by 2 is the probability to move to node number six so from node number two I jump to left child which is this node number four and the probability becomes 1 by 3 multiplied by 1 by 2 for this path that we have taken and this would give me 1 by 6 at this point we have our Target node we have reached the Target and this is a leaf node as well so here I check what is the remaining time that I had since I had made two jumps so I keep a parameter a copy of the variable T which is 2 initially it becomes 1 at this node it becomes zero at this since T has become 0 and this is our Target node the probability would be one by six that means I can reach node number 4 within the given time constraint so I return this probability okay so let's try to understand the intuition to solve this problem so this problem we are given this graph which has seven nodes numbered from one to seven the frog is standing at node number one and you have to reach the lower number of 4 which is the target node within the time which is 2 seconds all we have to do is to find the probability to reach node number 4 starting from vertex 1. if we cannot do so then that means we cannot reach the target node hence the probability would be 0 in that case so how can I solve this problem how to think about the very first observation is that the given data structure is a tree data stuff so we know that for a tree having nodes we can have n minus one so what does that tell us it simply means since we have n minus 1 edges we have exactly one path between any two nodes so to take any two nodes of the given tree Let's Take 6 and 3 there is exactly one path that is this one take seven five there's exactly one path seven to one two three to five and so on for every pair of node that means from The Source vertex 1 to the Target Vertex 4 there has to be exactly one path and all we have to do is to travel along that path keep decrementing our time variable along that path and finally when we reach the target node check if T is positive or zero like if we have reached the target node within this time if it is the case then we just have to return the probability otherwise the probability is always zero because if we cannot reach within this T so that's all so that's our Target now the challenge is to implement the idea which we have understood here so we know that there has to be exactly one path so and we want to return and we just keep track in mind that we want to return a probability we want to return the probability so standing at the source node we have two variables initially the probability variable so what would be the value of the probability variable it would be 1 because I'm standing at the node number one so to reach the node number one the probability is 1. another variable which we have to keep track for every node is T and initially the t is 2 which is given as an argument to the function so these two variables which will have which we have to keep track for every single node Now we move down the given tree let's so first we jump to node number two how will these variables change what will be the probability at node number two we know from we know that in the problem statement we're given that to jump to any of the neighbor nodes the probability is uniformly divided so since there are three child one two three the probability to jump to each node would be one by it would be 1 by 3 for this it would be 1 by 3 so I jump to node number three the probability becomes 1 multiplied by one by three that is one by three we know that to jump from one node to another we consume one unit of time hence the time remaining at node number two is one second because we have consumed one second in jumping from node number one to normal so these are the two variables for this node now from node number two I can jump to two nodes which are node number four and node number six so what is the probability to jump to one of these nodes it would obviously be one byte y because there is equal probability to move to any node to move to any neighbor node the probability is randomly divided or the next vertex to choose is randomly chosen hence the probability to jump to node number four is one by two so what will be these two variables for the node number four there would be one by three multiplied by one by two which will become 1 by 6 while the time will become zero since the time will has become 0 that means I have to check whether the node on which I am standing on which our frog is standing is the target node or not if it is the target order then that means I have consumed the time and I have reached the target mode so here I have to check I have arrived at the Target node order and we have arrived at the Target mode so I return the probability from here what is the answer is 1 by that is the probability to reach the node number 4 starting from node number one in two units of time fine so that's the idea that so that's how we are going to solve this problem so if you have basic idea of graph traversal algorithms or three traversal algorithms like that first search BFS Etc so you must be able to implement the solution which I explained here it is just a traversal all we have to do is to Traverse down the tree while standing at any node we must know the probability to jump to the next this idea can be easily implemented using depth first so before you move to my implementation try to implement the solution by yourself because that would help you to better understand the problem and that will make your life easier to tackle these problems whenever they appear next let's jump to my implementation okay so I implemented the solution using depth first strategy so this is my target variable this will store the target node this is adjacency list which will be used to create the graph from the given edges this is the visited array used to Mark the nodes visited so here in this function frock position where we are given the number of nodes in the graph the edge list the time and the target node I resize my adjacency list and visited array for end nodes and then I iterate over the edges and create our graph then I call my dab for search function from the starting Node 1 and time T these are the two arguments which I am passing while the target is a global variable I can simply check the base condition without passing in the argument so let's see the working of the steps for search function in the next slide so this is my depth for search function which takes in the node on which I am standing so initially this node is 1 and the time which is remaining to reach the target so this is the base condition what is the base condition is simple so either the time has been consumed so while moving down the tree the time has been consumed so at any node I if the time becomes 0 that means we can't jump to any further node in that case all we left with is to check if the current node on which we are standing is equal to the Target node if it is the case then I have to return 1 from here otherwise I have to return 0 from in a general condition I visit that node I initialize a variable to Z 0 so what does this variable store this variable is simply going to check if for any certain node on which I am standing so let's say load number I so the this variable is either 0 or 1 y because let's say I have three sub trees in this let's say I have these three sub trees for the node number I and let's say deep down in the very first subtree I have my target node as 4. obviously we have exactly one target node in the given Tree in which I am traversing so here this is the current node I will Traverse all its I will Traverse all of the subtrees which this node has this subtrick and this final server so this address this res variable so since this subtree contains node number four whenever I reach node number four this will return 1 because that is the base condition hence this sub tree is going to return 1 because I have the because the target node is present in this subtree while the target node is not present in these subtrees this condition is never met since these trees do not contain the target load this condition that is I is equal equals to Target is never met whenever I reach a leaf node which is checked by this condition I am sure that leaf node is not the target node I am returning 0 right from here because the target node is present in this sub so the DFS function is going to return 0 for these sub trees hence the rest will store 1 plus 0 that is one so after this Loop ends I will have res either 1 or 0 1 is the case for those sub trees which contains our Target number so while here I am returning the probability how do I calculate the probability that is if for a particular subtree the target node is present then that is then in that case the res will be 1 and for that subtree all I have to do is to check for the number of childs which that subtree has and that can be calculated from the given adjacency list and here I have to check if the node on which I am standing is not the source node because for any node let's say this I have to count the number of childs with this node has I have to exclude the parent or the node from which I am that's why I'm subtracting this variable from here so I will return the probability right from and this will be 0 for all the sub trees which do not have the target to find so this is okay so let's discuss the time and space complexity for the implementation explained here the time complexity for the given implementation is same as the time complexity of depth first search which is Big of n while the space complexity for the given implementation is Big of one because we are not using any extra space while performing our depth first search although the stack space is consumed but the auxiliary space is not used fine so let's see the code implementation of the ID explained here okay so this is a solution class where we two functions depth first search function and frog position function the Frog position function takes in the number of nodes Edge list time and target node and Returns the probability to reach the target node while starting from the node number one let's declare the variables which will be used in the program this is the target variable which stores the target node for the given tree and then we have our adjacency list which will be used to store the graph then we have our visited array which will be used to Mark the visitor nodes in the trades okay so in this frog position function we resize our adjacency list and visited array to n then we assign the target node to the global variable Target then I prepare my graph from the given Edge list finally I call the DFS function from the starting Node 1 and I pass in the argument type let's see the implementation of DFS function so this is the base case in the DFS function it simply says if we have reached a leaf no mode or the time has exhausted in that case I have to check the node on which I'm standing if it is a target Road or not if it is then we return one otherwise we return 0 from here then I Mark the current node as visited declare a variable result which initialize it to 0 then it rate over all the unvisited child nodes of the current node I and for all those unvisited child notes the cursively call this depth first switch function and add the result to this variable so this variable of code after this iteration it will either contain 1 or 0 it will contain one for all those sub trees rooted at node number I which contains the target node and for rest of the subtrace it will be zero finally I have to return the probability to reach the target node from this node I that will be computed by calculating by dividing the resultant variable by the number of childs that the current node has so here and I'm excluding the node from which I have arrived at node number I or the parent node so this condition is used to exclude the parent load from all the adjacent nodes of the current node fine so this is the implementation in C plus let's see the implementation in other languages so this is implementation in Java and this is the implementation in Python language so that's all for this video if you like the video then hit the like button and make sure to subscribe to my YouTube channel and I would love to take your feedback in the comments below I will see you in the next video till the take care bye thank you
|
Frog Position After T Seconds
|
number-of-comments-per-post
|
Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.
The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`.
_Return the probability that after `t` seconds the frog is on the vertex `target`._ Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** n = 7, edges = \[\[1,2\],\[1,3\],\[1,7\],\[2,4\],\[2,6\],\[3,5\]\], t = 2, target = 4
**Output:** 0.16666666666666666
**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after **second 1** and then jumping with 1/2 probability to vertex 4 after **second 2**. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 \* 1/2 = 1/6 = 0.16666666666666666.
**Example 2:**
**Input:** n = 7, edges = \[\[1,2\],\[1,3\],\[1,7\],\[2,4\],\[2,6\],\[3,5\]\], t = 1, target = 7
**Output:** 0.3333333333333333
**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after **second 1**.
**Constraints:**
* `1 <= n <= 100`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `1 <= t <= 50`
* `1 <= target <= n`
| null |
Database
|
Easy
| null |
68 |
all right this is lego problem 68 text justification listed as a hard question so i'll go ahead and read the description given an array of words in a width max width format the text such that each line has exactly maxed with characters and is fully left and right justified you should pack your words in a greedy approach that is pack as many words as you can in each line pad extra spaces when necessary so that each line has exact max width character extra spaces between words should be distributed as evenly as possible if the number of spaces on a line do not divide evenly between words the empty slots on the left will be assigned more spaces than the slots on the right for the last line of text it should be left justified and no extra space is inserted between word note a word is defined as a character sequence consisting of non-space sequence consisting of non-space sequence consisting of non-space characters only each word length is guaranteed to be greater than zero and not exceed max width the input of the input array words contains at least one word so here's our first example we're given words as an array this is an example of text justification and our max width is 16 characters so the output looks like this basically we have three sentences and each sentence is justified so that there's spaces in between the words and that as many words fit on a sentence as possible but we couldn't fit example on this first sentence because it'd be greater than the max width which is 16 characters and each word has to have a space next to it unless it's the last word and then at the very end we have justification which fits within max width but there's some spaces so we do the padding at the end there okay here's another example what must be acknowledgement shall be so we have what must be if it's on one sentence with spaces acknowledgement fits on its own sentence or its own line with spaces at the end and then shall be with a bunch of spaces at the end and then the final one science is what we understand well enough to explain to a computer art is everything else we do so the last line obviously all this text justification because we couldn't fit do on the previous line because it's it would be greater than the max width all right so you can kind of think of this question like how you think about a google doc does text justification or word doc it basically tries to fit as many words as it can onto a given sentence and then justifies the space in between each word so that it looks nicer and then the very end we have you know space to pad so that every sentence is the same length okay let's go ahead and start building out our solution so we can see you know how this is solved all right so i'll start with a init method to declare some variables that we'll need as we go through this first one is going to be a return sentences variable and that's going to be an array because that's what we're going to end up returning here and the other thing i want to store is the max width we'll set it as 0 and then when this full justify method gets called we'll go ahead and update that with what was passed in here that's the first thing we can do is self.max with equals thing we can do is self.max with equals thing we can do is self.max with equals max all right a couple more variables we'll need we want to keep track of the current count that we're on for a given sentence one that's challenge set to zero and also the current words that we've gathered so far that'll be an array so let's start looping through the words array for word and if the length of the given word that we're on plus our current count is less than or equal to the max width then we can go ahead and add it to current words and keep looping so we'll do current count plus equals the length of the word plus one because we're going to add a space after that word so we need to keep track basically what we're doing is we're looping through words and we're saying can this word fit on the current sentence that we're on if so yes add it add the length of that word to our current count plus 1 because we know we're going to need at least one space next to it so this will give us four which is the length plus one which is five so current count goes from zero to five and then we also append the word to our current words array if the length of word plus current count is greater than max width then we know that we've gone down to a new sentence so we've added this with a space we've added is with a space and we've added and with a space and so that total count you know now we're at example let's check the length of example can the length of example fit with what words we already have in this array no so now we need to go add example to the next line so we'll go ahead and do we're going to call a method that doesn't exist yet but we need to create it add sentence is what we'll call it'll take in the current count current words as well which is our array so we'll go ahead and call that method and that's going to basically add the words that we've accumulated so far to return sentences and then we'll go ahead and reset these two variables so currentcount is going to start at length of word plus one as we're looping through and we get to example won't fit with these three previous words so it's going to go on to the next line so we'll go ahead and start the current count at the length of example plus a space and current words is going to start as an array of just that word which would be example and then we'll say if there are any current words left at the end of our loop if we haven't added them to the sentence already then we'll call self.add already then we'll call self.add already then we'll call self.add sentence one more time as a cleanup and we're gonna add one more flag here to tell this add sentence method which we haven't created yet we're going to add a flag at the end to tell it that it's the end because we do a little we do something different at the end where we do this padding at the very right side of the word so it's going to be a little bit of a different logic than the method when it gets called here and we'll go ahead and return self dot return sentences so far what we've done is we've you know set max with as a object variable we've initialized our current count to zero in our current words to an empty array we start looping through words which in this example would be this we'll go ahead and start looking at the first word we'll say is the length of that word plus whatever other words we've added less than the max width if so go ahead and increment our current count to be the length of the word plus one because we have to account for another space at the end and we'll append that word to recurrent words so as we go through you can kind of see what we'll create we'll go ahead and implement this sentence add sentence method and we'll just initialize it to do nothing and just so we can see what's happening right here i'm going to go ahead and print current count and current words through our loop so we can see you know what it looks like as we go through okay so we've gone through this array you know this is the example input this is our max width of 16. it starts out it adds this and current count gets incremented a five because it's the length of this plus one because of the space then we add is because we can still fit is plus this within our justification it's still under 16 which limit then we add and still under 16. then we get to example now example needs to go on a new line so we reset current count to the length of example plus one and then our current words is just example word an example of text and then justification if you look this is exactly what we want at the end minus the space parts the space justification which we haven't implemented yet i'll get implemented in this add sentence method but we do have what we need what i'll do here is you know just so you can see how this works i'll go ahead and append current words to our return so you can see how it will look and instead of printing here print here what will return which is close to what we want already so you know it's already pretty close it has the words that we want in the correct group and now all we need to do is the space justification okay so as we saw with you know our example return this is sort of what the add sentence method is going to be passed in it's going to be passed in this array or one of these arrays and then the current count which is what we've accumulated basically the length of all these plus one so what we need to do first is figure out how many spaces are available you know so basically we have the length of all of these words this is and so the total length of that is eight but our max width is 16. so we have eight spaces to divide up and supply in this overall sentence to make it justified so we're gonna have four space between this and is and we're gonna have four spaces between is and so that total character count is going to be 16. in this example on the second line we have example of text which is a total of 13 characters just with the text alone so we have three more spaces that we need to divide up and remember up here it says extra spaces between words should be distributed as evenly as possible but if it does not divide evenly then the empty slots on the left will be assigned more spaces than the slots on the right that's why you get two spaces between here and one space between here so we need to basically figure out first how many spaces do we need to supply in this sentence minimally it's going to be the amount of words minus one so if there's three words it's going to be at least two spaces to separate those words but if they're small words and there's lots of extra space then it might be greater than that so we'll have to figure out you know how many spaces do we have here so we are being past the current count which is you know the length of all these words together plus the spaces so from that we can calculate the spaces so the first thing we want to do is subtract the length of current words because we know that as we iterated through we added an extra space or an extra count for every word so if we subtract that length which in the first line is going to be three right here if we subtract three which is the length of current words from current count then current count is going to be the exact amount of character in this group and from that we can figure out spaces by taking the max width and subtracting the current count because max width is 16 minus the current count which is at this point now eight and you'll get eight as the spaces so right there we have our space now we want to create a sentence variable which is going to be an empty string and that's what will eventually append to return sentence now before proceeding on with the core logic that we mainly need to handle we first want to handle this end case right we created this end flag which is only used at the very end so let's go ahead and handle that first so if end and we know that we're dealing with the very last word such as justification so let's go ahead and create the sentence from that so it's going to equal basically a join of the words that we had so it might be shall be or it might just be one word justification with a period right it's going to be a join of that plus any extra spaces that we need to pad to create this end string so we'll go ahead and do a join uh of the current words we'll do a space join so that will create a string of all words that are in current words which is in this case just one at the end you know separated by space so that creates a string and then we'll concatenate that to all the spaces that are padded at the end so we've taken this little syntactic sugar is basically a python way of multiplying this value times however you know whatever the equation is of this so spaces in this case at the end is going to be the length of justification with a period minus max width which is 14 so now we have two spaces left over spaces is going to equal two and then we take out the length of current words minus one just in case there's multiples like two because in this case already added spaces for each word in between so we don't want to add too many extra spaces at the end if there's multiple words at the end so that will be our sentence we'll go ahead and append that to the return sentence array and then we'll go ahead and break out of this function because we don't want to execute any of the other logic we're about to write okay so we've gone ahead and handled our in case if it's the last words to be called by add sentence then we go ahead and do this simple logic to reconstruct the sentence appended to the return sentences and break out of the function now let's figure out the next steps when it's not the end and it's just a regular group of words like this or this because of this text justification and how there might be an uneven number for example the first line has eight so it divides evenly but the second line has three so we have to do the left justification what we can do is create sort of an overflow so we have an overflow of the length of this and then the number of spaces that we have divided by the number of words that we have to distribute through and then we'll have some sort of overflow so we can calculate that overflow with a mod on the spaces over the length of the words minus one that will do spaces mod and then max of length of current words minus one or one whichever is greater so in this example you know we have three words went in here the length of all these words is thirteen so the spaces is going to equal three now we take the length of current words which is three minus one which is two we divide two into spaces which is three and we see what our remainder is let's pull up the terminal here and you can see three mod two is going to give us one so our overflow is going to be one which is correct because what we would do is we would try and divide up our spaces and then on the first occurrence when we're you know doing this padding we would have some overflow and so we go ahead and add one on the overflow subtract from our overflow variable and then on the next one we wouldn't have any overflow so it'd just be one space we also need to figure out the number of spaces okay so we have spaces which is you know eight or whatever it is but then we need to figure out how many spaces do we apply between each word right so we can do that by taking the number of spaces that we have overall divided by the max of these two equations either length of current words minus one or one so we always want to at least divide by one so it's not divided by zero error okay so now that we have the number of spaces that we want to apply and plus we have our overflow that we'll need to apply for the first letters you know going left to right let's go ahead and start creating our sentence as we go so we'll start a for loop and we're going to call this current word in range in numerate of current words we'll go ahead and assign a variable and spaces which is going to equal at the start num spaces our sentence is going to get appended to current word that we're looking at so in this loop the current word would be of this so we go ahead and add this to sentence and if i does not equal the last index that we're on so if i does not equal you know length of current words minus 1 then we want to add it add spaces but we also want to add if there's any overflow so if overflow so remember overflow is all that left spaces that we need to apply because it didn't divide the spaces didn't divide evenly so if there's any overflow we'll go ahead and increase num spaces by one because we're going to add one space to this word and we'll go ahead and decrement our overflow by one and then sentence gets its spaces applied to it all right now that we're done with that loop we'll go ahead and check if length of current words equals one then we'll handle this base case because this you know sentence only gets spaces applied if the length of words is greater than one because what we're checking here as long as i does not equal the last element of the array but if the array is only one then this will never run this section right here so we just need to check that case and say if the length of current words equaled one the whole time then we'll go ahead and add all the spaces at the end because we never added spaces and now that we have our sentence we'll go ahead and append it to our return sentence so that it gets added in the overall return all right let's go ahead and run this looks like i need some parentheses for the order of operations okay and we do have a valid solution we did return you know as expected so we can go ahead and submit this and see how it runs great so there you go there's a solution to this problem it is listed as a hard problem probably one of the easier of the hearts on leak code and hope you enjoyed thanks for watching
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
1,071 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is greatest common deviser of strings so in this question we are given two strings s and t and we can say that t divides s if and only if s is made up of multiple concatenations of T so according to the question we given two strings S str1 and S str2 and we have to return the largest string X such that x/ return the largest string X such that x/ return the largest string X such that x/ both Str str1 and Str str2 so what is the common string among both the strings which divides them equally so that you can form the greatest common divisor of that string so let's take the example one here we are given string one as ABC and string 2 as ABC and here you can see string one will be made up of multiple ABCs which is string two so this part is Str str2 and this part is again Str str2 and we reach the end of the string one and this part is Str str2 itself so we can say that a b c is a common divisor of both Str str1 and Str str2 and in the second example you can see this is the greatest common divisor ab and this is also formed by three ABS so how are you able to solve these three examples and here you can see there is no common between both so you return empty string as the output so according to the question you have to find the greatest common divisor of both the strings so for any two numbers you have to find the greatest common devisor so in this case the length of the string one is six and the length of string 2 is three so gcd of these two numbers 6A 3 is equal to 3 so you find a string of length 3 so you take the substring of the greater string so you take the substring of length three so 0 1 2 3 so you take the substring from 0 to 2 which is of length three so ABC will be the output the length is 6 and the length is 4 gcd of 6A 4 is equal to 2 because 2 divides 2 is the greatest common divisor of 6 and four so you take substring of the first two characters so this will be of length two from string one so always remember Str str1 length is greater than Str str2 so take the substring from Str str1 only and this will give you AB of length two so AB is your output now let's Implement these steps in a Java program so here I written a helper function to find the greatest common deviser so here it will take two numbers of integer data type as parameters and you make a recursive call to the same function so each time you pass the number two and the remainder of the two by using the modulus operator so this helper function will give you the gcd and I'm call calling this helper function inside uh the main function so inside the main function I'm finding out length one length of string one and length of string two so here I'm doing a base check if when you combine both the strings and if they're not same you return an empty string like in example three here if you combine lead and code so here you can see lead code is not equal to code lead so you can never form a greatest commment devisor so in that case you return empty string as the output and in all other case both s strr 1 + S str2 is equal to S str2 Plus s 1 + S str2 is equal to S str2 Plus s 1 + S str2 is equal to S str2 Plus s str1 this condition will be skipped for first two examples and I'm calculating the result by finding the substring of Str str1 using the substring method we're starting from zero until the length of the greatest common devisor which we are getting from this helper function here and finally we are returning the output which will give you the string by forming the substring so the time complexity of this approach is O of 1 and the space complexity is also o of 1 that's it guys thank you for watching and I'll see you in the next video
|
Greatest Common Divisor of Strings
|
binary-prefix-divisible-by-5
|
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters.
|
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
|
Array
|
Easy
| null |
100 |
hello today we'll be working on Elite code 100 same tree our goal is to figure out if two binary trees are the same two trees are the same if they have the same values and structure any deviation means that the trees are not the same so the line of thinking for this is pretty straightforward if two trees are the same then we should be able to Traverse them in the same way and get back the exact same values at each point if at any point the values don't match then the trees are not equal all right so starting at the root we'll compare the values four and four those are the same so we'll Traverse into the left node and repeat the process it doesn't matter how you Traverse the trees just that you're comparing the same nodes okay so Nine and Nine are the same eight and eight are the same and once you hit null if both values are null the trees are the same however if only one of the nodes are null we've hit the end of a branch in One Tree but not the other meaning the trees aren't the same okay so we continue to Nine and they're the same 23 and 23 are the same 63 and 63 are the same and 17 are the same so these two trees are identical now in the right diagram I've switched out a node and made it null so we'll perform the same steps as the last algorithm once we hit 63 and null we know the trees are not the same all right so let's step into the code so the first thing that we'll do is check if both nodes are null if they are then we're at the end of a branch for each tree so we'll return true next if only one node is null then we hit the end of a brand for one tree but not the other which means the trees aren't the same so we'll turn false and then if the node values aren't the same we'll return false as well and you could combine the last two conditions but I find this easier to read now we'll perform our recursion so we'll return is same tree with the left nodes and is same tree with the right nodes if both calls return true will return true but if one is false will return false and that's all there is to it so let's submit this and there we go so I hope you found this helpful please leave a comment below if you have any suggestions and I'll catch you in the next video
|
Same Tree
|
same-tree
|
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
139 |
Ajay Ko Hello friends welcome to my channel Library - Yoga Kiya Bina Channel Please Library - Yoga Kiya Bina Channel Please Library - Yoga Kiya Bina Channel Please subscribe and press Bell Icon Flat Tubelight Film Tubelight Problem Solve What is the question of be I am I to give another subscribe request of the dictionary word with 300 Video Example of a Giver I Like So They Can See in Chief President I Like It Means Like Subscribe Samsung On5 Samsung and Apple Mango Man is the full form of B So here and this I B.Ed B.Ed D.Ed A B C D subscribe for watching this Video here I took the TV and took the CD, this is how the wound has become BCD, consider the exam BCD light difficult for A B C D shoulder possibilities of will be and you too, one but if we have two supporters unlike you Leaders Sirvi and death should make that question if this 90 then what will we do now then this is complete I am here just open the settings logical that if you are in B for me tip no I will shirt BCD help took my name now the child I have to search if I do not even find it, do not search even in this video, if I took subscribe, I had taken BBBBBBBBB BB more, I am getting a vacancy date Behavior Getting a video of Vidya Top I will try but am not getting it I will search here again in the mid day meal otherwise I will now set the screen brightness to full If you like this video then we have to do it then what will happen here is our reverse entry to Ghaghra Here I was our ABCD so I can do a search now song that we have done the middle of ka I had completed this letter earlier too, this letter is ok so here I have sent one searching less BCD I have sent here in reverse entry in send carrier then I will be searching baby in Bihar, will give CD in every question, after that I sent record minister searching to ABC, then I will leave here on Sunday in place of children, after that I will message ABCD, in case of shortage there, I will send them OK, I will send complete ABCD. If I search then I left here, so this was the benefit, now the one who went ABCD came here I have this here, then I will also send some searching, now look at our memory, now my CD has come here, so what is that? I told you to read something, if please, I sent a search, I also sent a reminder on the reminder that I will send an ad searching again, for example, BCD is ours, so came the exercise sending also for searching in the temple near ABCD, mine again, yes sir, I had touched it now. Here, when the country or in this one, I have given this one, which I have sent the Sachin poverty CD, in addition, whatever I have sent to Abe, it is directly here and you can find directly, this is our memorization happening, means, when we people CD's. Answer: I know whether it is available or we people CD's. Answer: I know whether it is available or we people CD's. Answer: I know whether it is available or not. Hey, why would I calculate this? Unwanted Calculator Green. Now give two of our D's here. I had gone searching for Biscuit Award. Both of these were found in capital letters. Answer: What happens in DP of Birth in capital letters. Answer: What happens in DP of Birth in capital letters. Answer: What happens in DP of Birth that at the end The dip that I will make, the first task will be interesting, the second will be interior, I will do this father-in-law in Himmat, and will do this father-in-law in Himmat, and will do this father-in-law in Himmat, and in the second, I will do wow yaar - show karoon agar hai ki saif if in the second, I will do wow yaar - show karoon agar hai ki saif if in the second, I will do wow yaar - show karoon agar hai ki saif if our defam in the middle, we are made up of Godhead, this is our video. We have not subscribed that. There is a noise in the DP that I had found that memorization will not be done and you must be understanding that here I have already calculated that it will not be given, I will use the laddus here also, just have to do this for Tuesday. Come to the distraught here what we have taken is the root of DP I have taken in the map and inside you map is its first parameter is string second remedy is in ticket psychological vision and India will take ticket investigated by default in map soon free great words in Beerwas - 100 gm free great words in Beerwas - 100 gm free great words in Beerwas - 100 gm Apna Yeh To Give Any Question This Function So I Have Sent Here Gare Natthu Parasol Function Of Delhi This Apna STD Hari Apna Hai Bhi Vector Tube Vector Now I Will Make A Famous If You Naan Saravana 2D Answer: Reorganized wash, so You Naan Saravana 2D Answer: Reorganized wash, so You Naan Saravana 2D Answer: Reorganized wash, so here I am my more, here I am in unmute map, turn on map, here I have burnt this function, I have taken one, now I have taken out escalator in add, will you add or do you mean people like the one who was ABCD, I am the complete ABCD Poem Searching Mirza here But ABCD had done it with all its efforts, if this match plan goes away, then I will not search here, mother, I have found it on ABCD. What did I say but AB, which is here, I will send the example search to ABCD and it is as if it would have been found in the meantime. If I get the points, then my people who will stay here will take 40 inches, otherwise I will check the size, make it a ribbon, it is ok, now after I have checked and the difficulty will be zero, then I will make it the Deputy President. Memorization is going on there, Tika said, it is difficult, it has been created, otherwise you will get the ad here, they got the answer, they will add the acid, and what have I done in the whole exam, I took acid from the people, here you will see the opposite, I All friends, I am sending a loop in it and then I will check each person in it, he is ready, but this is what I told you, this will be me, like this one here. I will first send a message ABC 1968 If they have to search then I have given here a dead disgusting form from one to head office this for such a decision and at such a time I took out from everyone for green means one element two elements in elemental element everyone I will search in Bihar, if we get it then it is ok even if there is less ad, then I will add fb2, now this Vaseline is F1, what does it mean, if we take a piece of ABCD, then it got ABCD, now it is ABC, now it is saffron. Here I will send my recording to the baby turtle to see what his answer is, so I sent it to him and checked that here he is also a forest, that is, it is face to face, that is, we are getting the whole string, the whole that is our rabbit, my tablet will be free, get it. I am going to Amino DP office, I want to roam around, so if this is my complete follow and I am not getting anything, I will post it. If you are not coming to the office, then subscribe this channel and press the bell icon to like my video. Subscribe to our channel, share as much as you can and if you like this video then please give a like to Ajay in this video.
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
983 |
hello everyone welcome to my channel i am shankar dhyan a final student of computer science and i usually make coding videos and placement related videos so that you can do good in your interviews and like without wasting any time let's get started hello everyone so this is the last video for this week that is dynamic programming and this question is similar to the coin change problem that you must have heard so the question is minimum cost for tickets and we are given some n number of days and we are given the cost for one day one week and a one month pass so if we consider the first example we are given these days that we need to uh like travel and we are given a cost for one day pass that is two and seven is for one week pass and cost is 15 for one month pass and we need to return the total the minimum cost using which we can visit or we can travel all these given days so in this if we can ah like if we read the example explanation so here we are we can see that for day one we need a one day pass and for day three we need a seven day pass so it will cover four six seven and eight and then again for day twenty we need a one day pass so the total cost will be two plus seven plus two that is eleven so similar is the second example so in this what we can do is we can create a dp array and we can store the cost of travelling at this given point of time so dp of i will be storing the cost of travel up to high days so if we are using a one day pass so dp of i will be dp of i minus 1 plus the current cost that is cost of 0. if we are using a 7 day pass so this dp of i will be dp of i minus 7 plus cost of 1 and dp of i will be dp of i minus 30 plus cost of two so this is for one day pass this is for two day seven day pass and this is for one month pass so using this formulas we can try to calculate the cost at all the days all the given days so in this for this case we will be taking the maximum of 0 or i minus seven so this is the maximum of this because for example if we have two days and the cost of one week passes less than the cost of one day pass so instead of buying one day pass we will buy one week pass so same is the case with this and in this 30 day pass also we can do the same thing now what we'll do is we will calculate dp of i for one day pass like every time and then for the other we will take the minimum that is dp of i will be minimum of this dp of i or this another value and for the one month pass also we can do the same thing so this is the minimum of dp of i and the cos that we have calculated so in this way we can solve this question so first we will take the last day that we have in the given days so it will be the length of like the last value of this array so days dot length minus 1 so this is the last day for example in the first example it is 20 so this last day will contain 20. now we'll take some value as n so it is the total number of click up to like one plus this last date so that we can create arrays using this n now we will create an dp array to store the values and we will have a boolean array to store if we have to travel this particular day or not so it will be boolean of the boolean array and name it as bull is equal to new boolean and the size will be n and then we will uh like the default value is false in case of boolean so we will make them true like for the days that we have to travel so for into d in days we will change the value that is bool of d will become true and now we can use this tp to fill the values so i will start from 1 and up to n i plus and in this if we have to visit the current day we will calculate the values here and else if we don't need to visit the day we can take the value of the previous day so this bool of i will be equal to bool of i minus 1 if we are going to visit this current day so we can use these formulas now this dpf i will be storing the values at like for every day and then we can check if we have if we can reduce the cost if we are using a 7 day pass or a 30 day pass okay so now we will have filled all the values in this and now we can finally return the last value of this dp that is n minus 1 or we can also take as last day okay it is i okay it is dp of i is equal to dp of i minus 1 okay and now it is accepted now for the time and space complexity for this question if we try to see the time complexity here we have constants like linear like constant time operations and here we have one for loop that is for days number of days and we have another for loop that is from 1 to n and n is the last day so it is a linear time and this last day can be up to 365 as it was given in the question now the overall time complexity will be constant if we take it as 365 but if we take this value as like up to any number like up to some n so then it will be big o of n and same is the case with the space because here we are creating a dp array of size n and a boolean array of size n so for this space also it will be linear so that's all for this question and you can like the video comment share and subscribe the channel and if you have any doubts or any questions that you are not able to solve or you want or you have any doubts in this video you can post them in the comment section below and if we are not able to solve this question then we can also check the solution so in this also we can see that they are using dp and like both are them both of them are a linear time and here they have considered total number of days instead of this n and if we see the discussion section then we can open some of the top links so i have opened five links here so the first one is using dp so in this also they have used the first method as taking all the 366 days 365 days and the method is using uh like they are considering only the top and like first n the number of travel days so if we see another solution so this is also taking 365 days and then here it is also taking the total number of like the maximum number of days and now here we have a solution that is like explained in detail so if we are not able to understand this question or from the solution also then we can read this post to get a better idea and then we have this python solution so if we are like if we try to do it in python and we are not able to do it then we can use this solution so that's all for this video and thank you for watching and do subscribe the channel for more videos and tomorrow i'll be uploading the interview experience for my people com for the people company that i gave last month and in the upcoming like days and weeks i'll be uploading more such videos and thank you for watching bye
|
Minimum Cost For Tickets
|
validate-stack-sequences
|
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000`
| null |
Array,Stack,Simulation
|
Medium
| null |
1,720 |
Loot Hello Friends Today in this video will discuss three easy problems from its state with me I will go through all problems from Band Safar problem is this trick to dog which is 800 to 1000 which country consists of number dialed in Delhi in the middle of is equal to A good care of plus number 2573 ok to inko dare re ki is dam special jogging at this time a tied chain is in this country The Original Form Very Important Information About The Effigy Of Being A B C Who Is Equal To C The Answer Is Equal To Bee And C Put Into Mix So That Can Transfer 360 OK Icon Transfer Dec 700 Vs Of Highways And Bb To DC Sibban C To DC Na Effigy of Baroda Sonth A Hair Defeat of 2ND Year Tax 15152 1000 500 and 1000 of Transfer 205 Village The Number Subscribe Number to Ruchika's Viewer No. 1 SMS Second Number 91 Third Number and Stuart Law Lift This problem wants even easier to solve just the first number and Georgette with the first number included here you will get from number subscribe to The Channel subscribe to The Amazing answer is the first number to the number said and pushed back To The Answer Is The Back Is The Last Leaf China Middle-aged Person That In Code Number Age Arogya Sonth Means Middle-aged Person That In Code Number Age Arogya Sonth Means Middle-aged Person That In Code Number Age Arogya Sonth Means The Answer Back Is The Latest Number This Front Part Of The Original And Rise Of The Code To The Number To The Recently Signed Numbers Are Included In the next to find the number of units problem react to split string in the balance now on the other side take left and right the two number from the bottom * maximum number of the balance remaining maximum * maximum number of the balance remaining maximum * maximum number of the balance remaining maximum sentence total number of a nine to the plated sections And All Seem To Be Taken To Find The Number No The Best Way To Solve This Problem As An Example Beldar Belur Subscribe And Like This Thank You Loot Jo Apni Profit And Clothing Knotted Clothing Baton 5459 Problem Solve A Step-by-Step And Tuition Hum Account Variable Step-by-Step And Tuition Hum Account Variable Step-by-Step And Tuition Hum Account Variable Ok User Account Variable Wherever Unbreakable Available Total Ok Enter Idea Of Information From Left To Right Way Never Find Out Host Total Posts 121 Incomplete 121 Aadhar Total Decrease Karo Hai Next Alarm Total Nigam CEO S Soon S A Total Vikram Zero It Is That Reduce Current Point Total Number Of And Lord Say Definitely Maximum Which Shoulder It's Best Valentine's Day Gifts For Transactions Can Increase Bible Points Decrease 100 Grams Withdrawal's Final Increase Wealth Decrease Pawan Decrease 12311 More 1820 Answer Is The Total Arm Pits Do That And Positive Window Answers Are Not Giving Frank And Honor For Every Single Moment Total By One Finds Out That Give Me The Total By One And 10.22 Begum 0 Answers Me The Total By One And 10.22 Begum 0 Answers Me The Total By One And 10.22 Begum 0 Answers Increment Launchers Phone Deficit And Just Dance Available For The Logical Third Skin Problems Doctors and Difficulties Are Well Thus They Can See Your Tears and Find Out How Make a
|
Decode XORed Array
|
crawler-log-folder
|
There is a **hidden** integer array `arr` that consists of `n` non-negative integers.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`.
You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`.
Return _the original array_ `arr`. It can be proved that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[1,2,3\], first = 1
**Output:** \[1,0,2,1\]
**Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\]
**Example 2:**
**Input:** encoded = \[6,2,7,3\], first = 4
**Output:** \[4,2,0,7,4\]
**Constraints:**
* `2 <= n <= 104`
* `encoded.length == n - 1`
* `0 <= encoded[i] <= 105`
* `0 <= first <= 105`
|
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
|
Array,String,Stack
|
Easy
|
682,874
|
322 |
what's up everybody today we're going to be talking about lead code problem 322 coin change so we'll start briefly with the problem description if you want to skip the problem description it will be in the description below um so we're given some set of denominational coins you know in this example we are given a one cent coin a two cent coin and a five cent coin and the total amount of change we need to make so in this case it's 11. write a function or you know write an algorithm to compute the fewest number of coins that you need to make up that amount and if it can't be numbered to negative one so let's go into the problem the first thing i want to start out with this problem is actually sort of analyzing what our current denomination is in the united states and going over why this problem is a little bit easier so how we make change right is we just take the largest possible coin we can at any given step for example if we need to make 66 cents and change that would be 25 plus 25 and then we can't take another 25 we can take a 10 so we'll take a 10 and then we can't take any of these three and we take our last penny and that's 66. sorry it's not 66 that's 61. so we would take a nickel and then a penny right so we would just go down the list and we would be choosing the largest possible coin we can at any given iteration this does not work in the general case given any coin denomination let's imagine this set of coins you know and uh let's say t equals 20. the best answer is clearly 10 plus 10 to 10 coins 10 cent coins but the greedy algorithm approach you know you would pick 17 and then three one cent coins and that would give you four coins so the greedy algorithm approach is not gonna work so let's think about this problem in a different way i want you to imagine that i have an oracle okay i can tell you the answer to any sort of target value except for the value you want to know for example if i told you tell me the number of coins needed to make let's say c of one thousand and let's say our coin set uh was three four five you can ask me the questions c from 0 to 999 or well and you can ask me you know any of these questions you can ask me an infinite number of questions okay infinity you can ask me all these questions if you wanted to you could ask me infinite number if you want could you determine the answer to c1000 given the questions you can ask here i would argue that you can and maybe let's look a little bit into why that is so what's the only way we can get to 1000 well we're at some number what's the only way we can get to any number well i give you a three cent coin or a four cent coin or a five cent coin right there's no other way given a coin with these denominations that you can get to a number it has to be from three four five so if you ask me the question c of uh 997 question mark c of 996 question mark and c of 995 question one could you tell me the answer then right well let's say this is three and this is a thousand and this is two thousand if i'm at 997 you could just give me a three cent coin boom you're done with four coins if you're at 996 you give me a four cent coin boom you're down to one thousand one coins and if you're at 99.99 or 995 and if you're at 99.99 or 995 and if you're at 99.99 or 995 you could give me back another coin a five cent coin and it'll be 2001. and clearly this solution is best so for c of 1000 we only needed to know the possible ways we could have got there given our coin set and that's going to be the algorithm basically if we have we're going to store it so this is dynamic programming this is a very classic dynamic program we're going to store some array and we're going to initialize zero cents to be zero coins and then we'll we will go through this array maybe we initialize it with all infinities or something like that but we'll go through this array and we'll be filling this out with numbers so let's say you know this is x1 this is x2 we don't know what it is it could be one coin two coin three and when we get to target right let's say our denominations are two and three we're just going to look at this is t minus one t minus two and t minus three we're gonna just look at t minus two and t minus three tell me what the answers are here and then i'll be able to tell you what the best solution for t is and boom we're done and you can kind of see that as you're going along you're filling out every single position so you know you've already computed t minus two and t minus three this is very similar to the stair climbing problem and this is very um sort of a general case of coin change so the code it will be in the comments below or in the description of the video below and hopefully this was helpful hope to see you in the next video
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
138 |
Hua Hai How To Play List With Random Powder And That Ali Short Length Name Is Governors That Is Not Contain Some Medicinal Random Points To Point To In Node In The List And Null Constructor DP Yadav List The Subscribe Nuvve David To Subscribe Notes For The End of the road to the co subscribe to a man of the pointer finger new list point to the nodes indore inlist this message played that note sax and violins original list wax doom this point to identify the corresponding to notes android co playlist x .com Point notes android co playlist x .com Point notes android co playlist x .com Point to the Copy List Liquid Food and Oily Not Represented a Player of Value and Values and Not Person 90 Point to Values and Not Person 90 Point to Values and Not Person 90 Point to 9 We Will Only Be Given to A For Storing Mapping From Original Include 2014 Beach Road Indore In His Twitter You With Some Time Set This Contest While Doing So Will Cater Mapping From Original Duplicate Note These Table Finally Travels Original And Duplicate Lands In A Which Bal Gautam Inlists And Furious 9 Tax Return New Notes By Bit Of Accidents To The Amazing Explain Least Transferred in Old Vigor School Mein A Vic and Usco P Ki A Hua Hai [ A Hua Hai A Lake Explain Radhe Maa Kar Do Ki A Hua Hai Hua Ki A Hua Hai Kar Do Ki A Do it, do it, stop it, Ki a ki a do hua ki a on do hua hai paint dwij ki this daal maa
|
Copy List with Random Pointer
|
copy-list-with-random-pointer
|
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list.
|
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
|
Hash Table,Linked List
|
Medium
|
133,1624,1634
|
34 |
hello everybody and welcome to another episode of your favorite algorithms channel my name is Ryan powers and today I'm gonna be taking you through leet code 34 find first and last position of element in sorted array now I must admit I am a little sick so hopefully I'm not going to be sniffling my way through this entire episode but we're gonna soldier on we're going to get through it and we're gonna put out this video anyway so without further ado let's introduce the problem so given an array of integers gnomes sort of in ascending order find the starting and ending position of a given target value your algorithms run time complexity must be in the order of log n so what does that tell us well that's big flashing light right we've got a sword array we need it login but what are we gonna do well we're gonna do binary search right we did just did that in the last I believe we just did that in the last video so that should be fresh in our minds so we already kind of know what our approach is going to be so let's look at our examples here okay so I guess I should cover this first if the toy is not found in the array we should return to y1 a negative one okay great so here's our input array and our target is eight so here are the ends of eight right we need to find the bookends where does it start and where does it begin or start where does eight start and where does it end well it starts on the third index and then it ends on the fourth index so we need to find those two indices and return them in an array and so what's this other example here well the target is six we don't find six doesn't exist so we turn negative one and negative one okay great so as always I suggest you try to solve the problem on your own first and if you get stuck or you just want to see how I solved it come check out the video otherwise if you're ready to get started go with me the white board on the screen here I have an array just to start it right I just wanted to do a quick little recap of binary search I know you could ninjas out there don't need this binary search recap so if you don't need this just kind of speed through the next three or four minutes but if you're kind of parachuting into this video series and you have no idea what binary search is well then stay here with and we're going to go through just kind of the strategy of binary search so what are the steps to binary search well the first thing we need to do is get our midpoint right so our midpoint is going to be represented by this pink circle here and the midpoint is just the point between our the ends of our array so this is this right here is our low pointer and then this right here is our high pointer and then this is our midpoint here and at every stage what we're going to do is check our values so we're looking for this search value of 8 we're gonna search this array for 8 we're gonna do it at a log in time using binary search so we're going to check is the midpoint equal to the target value which in this case is 8 and then if it doesn't equal the value then we're going to move our pointer so we're either going to move our high pointer or sorry a low pointer or a high pointer so if the value is less than the target the current value is less than the target well then that means if our raise in sorted order that our answer cannot possibly be in this half of the array so we can then move our low pointer up to be this value here and likewise if our value was greater than the target well then that would mean that we could eliminate all the values to our right so we could then take our PI pointer and move it to our midpoint and then we would just simply um we would just simply reassign our midpoint right and let me just keep doing that into a finer on target so we're eliminating half of our answers at every iteration so let's go through one around a doing binary search just to get a better idea of how it works so the first thing we're going to do is get our midpoint I midpoint is here at 5 and then we going to check our value so is 5 equal to 8 no it's not so we need to move our pointers so we can eliminate half our answers because 5 is less than 8 that means we want to move our low pointer and we'll reset our midpoint to be the midpoint between 9 & midpoint to be the midpoint between 9 & midpoint to be the midpoint between 9 & 4 which is if you sound 9 - 4 that's 13 4 which is if you sound 9 - 4 that's 13 4 which is if you sound 9 - 4 that's 13 divided by 2 is 6 and 1/2 well we're divided by 2 is 6 and 1/2 well we're divided by 2 is 6 and 1/2 well we're gonna use our floor here so we're gonna go to 6 and we're gonna check again so we're gonna check to see is this equal to our current value so 7 no it does not equal 8 so we need to move the pointer again and eliminate of our possible solutions well seven is less than eight so that means we can move our low pointer again and we'll find the midpoint again so what's the midpoint between six and nine so that's fifteen seven and a half math.floor okay fifteen seven and a half math.floor okay fifteen seven and a half math.floor okay seven great all right so now we're going to check again check our value is a equal take yes it is equal to a great so what we did there is we just eliminate a half for answers at every iteration checking our target value to finally come to our solution anyways this is the basic combining basics of binary search and this is the Strad you're going to use to solve this problem so if you're ready to move on then let's go to the next section on the screen here I have an array full of numbers in sorted order and we have our low pointer here and we have a high pointer over here and this pink circle here is representing our midpoint and what are we looking for well we're looking for our left edge of our target answer and we're looking for the right edge of our target answer so that's represented here that's 2 & 9 and our answer set and of that's 2 & 9 and our answer set and of that's 2 & 9 and our answer set and of course we're looking for this target value 4 so how are we going to solve this problem well we're going to use binary search to find this left edge and then we're going to use binary search to find this right edge so what's the runtime complexity of this overall problem going to be it's going to be a Big O of 2 log N and why is it too low again well we're doing binary search wants to find this edge and then we're doing binary search again to find this edge and of course when we do our complexity analysis we drop our constants so that's going to give us a run time of log n which is what we're looking for in this problem and you might be asking yourself hey Ryan um why don't we just find a 4 like this 4 right here and then just iterate to one edge and find that side and then just iterate to this other edge and find that edge well I would propose to you what if our array was full entirely of force we would have to iterate all the way to one edge and then all the way to the other edge effectively turning our log n search into a linear solution which is not what we want to do right we don't want to iterate we want to get rid of half of our answers at every iteration so I guess we do want to iterate but we want to iterate in a very specific way so we're going to do binary search to find this left edge and then we're going to do binary search to find this right edge so how are we going to do that well we need to identify so first let's start with this left edge here well what are we looking for well we're looking for a number that's equal to our target but the number to its left is not equal to the target right so that's kind of the that's the while condition we're looking for so let's construct our while condition so our while condition is going to be first of all if the current position does not equal the target then we want to keep loop we can want to keep looping so what's the other case well we just talked about it if the current position minus one if that equals the target well we also want to keep looping because if we're here at this position well if we look to our left we'll see that is before so we're not done yet we have not found the edge so we want to keep looping while anything inside of this expression is true and then what about our edge cases where we've terminated to one side of the array or the other well we'll take care of that as well so we'll have an and condition here that just says well high minus low is greater than one we also want to keep looping okay so we've taken care of a walk condition what about our pointer reassignment so what about our pointer condition well how do we know which pointer to move well if we're looking for this left side then anytime that the value is greater than or equal to the target we want to move our high pointer so if we're here in the middle then we would want to reassign our high pointer to be equal to two the current midpoint and we want to move our midpoint okay great so what does that look like well we're just going to check the position the current position if it's greater than equal to the target we'll do a ternary and we'll just say that B high is equal to the midpoint otherwise our low is equal to the midpoint okay great let's go through one round of finding the left bound then we'll go through around to finding the right bound before we cut out this problem so let's first get rid of this here okay awesome okay so first we're going to check if either of these statements here are true is our current position not equal to the target that's not true is our current position at M minus one which is that index six equal to the target it is so we need to keep looping so we'll do a pointer assignment our current position is greater than or equal to the target so we'll move our hi pointer and then we'll move our midpoint and we'll keep looping so we'll ask again is our current value not equal to the target well that's not true is our current value - at our current index current value - at our current index current value - at our current index minus 1 is that equal to the target well that is true so we need to keep looping so we'll do a reporting reassignment our current value is greater than or equal to the target so we'll move our high pointer and then we'll move our midpoint okay so let's look through again is our current value not equal to the target well that's true so we need to keep looping so let's do a reporting reassignment is our current value greater than equal to the target it's not so we'll move our load pointer and we'll move our midpoint and keep looping so we'll ask ourselves again is our current value not equal to the target well that's not true what about our current value our current index minus 1 is that equal to the target well that's not true either so we know that we have found so we're done looping so we know we've found our first index so we'll move that into our answer set and we will now find this right bound right so we'll reset this problem okay great and now we just need to talk about how you to modify our conditions here well what about our while condition well at first we were looking for this edge here so we were looking at M minus 1 to see if we need to keep well this time we don't want to look at em minus one we want to look at this position here so we want to look at em plus one so all we need to do here is just flip the sign from minus to a positive and now we're checking on that other edge and then what about our pointer reassignment well before when our current value is equal to the target we were moving our hi pointer well this time we want to move our low pointer so how can we modify this expression to achieve that well we can just get rid of this equals two right Oh the only time we want to move the high pointer is if the current is the current value is greater than the target okay great let's go through a round of finding our right bound before we code the problem okay great so we'll take a look at our current position and it is it does not equal the target right so or it does the current position not equal the target well that's not true what about the current position at n plus one does he equal the target well that is true so we need to keep looping so we'll do our point of reassignment our current value is not greater than the targets over a low planer and we will move our midpoint and we'll keep looping so ask yourselves again is our current position not equal to the target well that's true right so we need to keep looping we'll do our pointing reassignment is the current value greater than the target it is so we'll move our high pointer and when we're midpoint okay and we'll ask ourselves again is the current value not equal to the target well that's not true is our current value at the current index plus one equal to the target well that's not true either right because that is this position right here so we know that we have found our other index right so we're done looping so we found our other index and we can return that into our answers array so we have so we've found our answers so we know now that we can use binary search to solve both finding this left edge in this right edge here so now that we kind of know the strategy for solving this problem let's see how it looks in code on the screen here I have a bunch of helper functions so we're going to use a bunch of helper functions to code out this problem so on the top here we have these Const you know left function one left function to right function to okay so we want write function one right function one and right function to so these are going to be our helper functions for kind of defining our looping conditions and our pointer reassignment so we don't have to write two binary search functions so we're gonna write one binary search function and we're gonna call it with different conditional functions so that's us another helper function up here which is our binary search which takes in the arguments of the array the target and then the two functions that we're going to use inside of this binary search and we are going to be a default assigning our pointer to be the first index and then the length of the array for the high index and then here we're going to define all of our high-level logic to define all of our high-level logic to define all of our high-level logic for solving this search range problem inside of the function search range resource so I think a good place to start is right here so what do we want to return in our answer well we want to return in the right and what can we return in that array well we can return a call to a binary search where we pass in the array and we pass in the target so okay so it's actually nums right and then the target and then we want to pass in a call to left function 1 and then we also want to pass in so not a call too but we want to pass physically pass in the function in itself so we're gonna pass in left function 1 and then we're going to pass in left function 2 so that's going to give us our left side value of the target number via the left book end of our target number and then we can just basically copy this down and we can replace our calls here instead of calling left or left functions we'll call our right functions and that will give us the other end of our of the book end of our target value right so I'll give us an array and these two calls these functions will return a value that is going to be the index of the first tart first target number and then the last target number okay great so now we just need to code out some of these helper functions first so remember we talked about our wild condition so let's start there so what is the Left condition for our while the left condition for our while looping for how long we want to keep living well we want to keep looping well the array at the midpoint does not equal target or if you want to also keep looping if the array at the midpoint minus 1 equals triple equals the target apologize if my face is blocking that I'm not sure if it is or not um but this is just the array at the index n minus 1 triple equals the target T the variable T so what do we want to do for the left pointer reassignment well if we want to reassign the pointer to hi so we want to return true here well reassign the pointer to hi if the current index is greater than or equal to the target then we want to move the high pointer so we want to return true so we'll just return the expression that the array the current index is greater than or equal to the target ok so what we want to do for the right function number one which is going to be the wild condition well we want to do something very similar where we first want to keep looping while the current position does not equal the target or we also want to keep looping while the current position at the current index plus 1 equals the target right it equals the target then we want to keep moving ok so now let's take care of the binary search function so this is kind of the meat of the problem here we're going to we wanted to code this in a reusable way so we can use this binary search function to both the left and the right side we can do that just by feeding in a conditional argument for the looping and the assignment of the pointer so the first thing we need to do is assign a midpoint so we'll sign a midpoint and we'll set that equal to the floor of our fi plus our low by 2 so that will give us our midpoint and then we want to tillu so how long are we gonna live well this is the great part of this is we can just pass a call to our function in to this looping condition passing in the array at the midpoint in the target and we also want to make sure that we're taking care of that case where we've terminated on one end of the array so that's going to be well high minus low is greater than one that means we also if both of these things are true at both of these things return true well then we want to keep looping okay great so now we need to do our pointer assignment so that's going to be a call to our second function passing in the array the midpoint and the target and we can put this inside of a ternary and if this returns true then we know we want to reassign the hi pointer so hi is going to equal in it otherwise lo is going to equal mid and I just realized that I didn't fill out this right what's our pointer reassignment for our right pointer okay so and in this call here to the left function - this call here to the left function - this call here to the left function - which is going to be the pointy reassignment for our left side a target value well we want to move the high pointer if the current value is greater than or equal to the target well in this case we only want to move the high pointer when we're searching for that right side value when the array at that specific position is greater than the target right if it's less if it's equal to the target we want to move the low pointer right we want to push it in that direction okay so that takes care of the pointer reassignment and then of course we just need to read a sign to you midpoint two to four of our and then at the very end when we finish we just need to make sure that the current midpoint equals the target if it does then we'll return that midpoint that index for that midpoint otherwise we want to return negative one okay so let's just do a short bit of recap here so we're returning to call store binary search function inside of search range that just is going to return the index of that target value on the left side here and then on the right side here so we define these helper functions to help us decide our looping conditions so the first function left function one is the wild condition for our while condition for looping in our binary search which is just stating that if the rate that current position does not equal to target or the array at the current position minus one equals a target then we are not done we need to keep doing our work and then our pointer your assignment we want to reassign the high pointer if the array the current position is greater than equal to the target and then for the right side pointer we want to do the opposite right we want to keep looping while the current value does not equal the target but also while the value at that index plus 1 does equal the target and then here we want to reassign the high points are only in the case that current position is greater than the target okay and then our binary search we're defining a midpoint here and we're defining our looping condition which we took care of in these helper functions and then also read resetting our pointer which are also taking care inside of these helper functions and then we're reassigning our midpoint to be the floor again up high and low / - then we're just returning and low / - then we're just returning and low / - then we're just returning the midpoint only in the case that position that we end up on is equal to the target otherwise we're going to return negative one okay great let's see how we did okay looks like I have a little bit of a bug here did not get through this bug free okay so unexpected token line 19 okay so oh that's right I need to do a question mark here for our ternary let's try this again okay great 72 milliseconds so as always there's a conspiracy against me by Lee code to make me look like I'm a terrible program so what we're going to do like we always do for well since a couple videos ago is rip the very best solution from Lee code and test it against our code so let's try that okay so let's grab this one percenter here well it doesn't like a one percenter is like a ten more like a ten percenter okay copy this okay great animal tastes in unless you all right great 80 milliseconds they're not better than us nobody's better than us right I'm just kidding but anyways so we'd be crushing binarysearch lately I think you guys should all feel really comfortable with binary search um and I hope anytime you see a sorted array and someone's asking you for login around time and you're doing search I mean binary search it's a no-brainer I mean binary search it's a no-brainer I mean binary search it's a no-brainer right we can do this in our sleep now we've written binary search functions like four times in the last two videos so anyways I hope you enjoyed the video I hope you learned something and as always I hope to see you in the next problem
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
238 |
question 238 product of array except self given an integer array nums return an array answer such that answer i is equal to the product of all the elements of nums except nums at i the product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer is guaranteed to fit in a 32-bit integer is guaranteed to fit in a 32-bit integer you must write an algorithm that runs in o n time and without using the division operation so the product of array x itself here we have one so 24 is equal to the product of the nums except nums at i so it'll be 2 times 3 times 4 12 is equal to 1 times 3 times 4 8 is equal to 1 times 2 times 4 and 6 is equal to 1 times 2 times 3. so let's try and figure out how we're going to work this out so we need to do it in o and time complexity that means no nested for loops and we aren't allowed to include division so in order to do this without division and keep it at o n time complexity we could loop through this array once forwards and then once backwards and calculate the product at each index and then use those two arrays to computate the answer we could have something called a forward array and this will be equal to we'll start off with one we'll place one as a placeholder then the product of one here is one the product of one and two is two the product of one two and three six and then we have four values in there so we don't need to carry on now if we did it in reverse order we so we have rev array we add one as a placeholder at the end we start at four so the product of four itself is just four the product of four and three is equal to twelve the product of four three and two is equal to twenty four now can we use this and this to work out this well if you look at each value 1 and 24 down here we could times those together right we look at the next value 1 and 12 we times those together to get 12. if we look at the next values we've got 2 and 4. if we times those together we'll get eight and if we've got six and one we can times those give to give six in terms of time complexity here we have o2n because we're looping through the noms array twice but this here this two becomes irrelevant so it's simplified to on base complexity however is n plus m because we have two for we have two arrays here that are going to be stored and then we need to turn them into an output array so it's going to be o n plus m where n is the number of integers in the four array and m is number of integers in the rev array and if we look at the question one of the follow-ups is can you solve one of the follow-ups is can you solve one of the follow-ups is can you solve the problem in one extra space complexity so in order to do that we need to remove these two arrays and the output array does not count towards space complexity so what we could just simply say is we could say result is equal to this array and then we could just update this as we go through the process so we need a forward array we need a starting position as a kind of placeholder and we need to loop through norms so to begin with in here what we can do is we can push so to begin with in here we can push into the forward array start and then we need to update start to work out the product so we start times nums at i and then the next loop is going to go index one and then it's going to be one times one and i'll put that into the fourth array and then i'll move on to the next index which is two times one which is two and it'll push that into the fourth array and then we'll only go up to three so we won't include four in this loop so next is we could have a reverse array or we could just call it res here we need to have a start placeholder so we'll say that's equal to one and we need to loop through the array backwards so i is equal to numbers.length minus one i is equal to numbers.length minus one i is equal to numbers.length minus one i is greater than or equal to zero i minus now we need to add to the end so we need to unshift into res we need to pass in start two which is one at this moment in time times forward array at position i that's going to grab the integer for position at the index i and it's going to times that so we can get the product so we need to add to res at the end of its array so we unshift into res and we're going to have start 2 times forward r at i so that's going to grab 1 from here it's going to grab i from here and it's going to use the last value in forward array it's going to times them together to give us the result and then we need to update start 2 because as we did before we're updating the product okay and we can return res so let's just see if that's worked to submit it okay great the only issue is that we haven't utilized one space complexity because we have forward array here so the way around this is to just say let res equal an empty array and initialize that at the start instead of forward array we can remove this res then in our for loop we can push start into res instead of the fold array and then down here rather than res and shift we can just say reza i is equal to start two times res i and if we get rid of that run the code and there you have it
|
Product of Array Except Self
|
product-of-array-except-self
|
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
You must write an algorithm that runs in `O(n)` time and without using the division operation.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[24,12,8,6\]
**Example 2:**
**Input:** nums = \[-1,1,0,-3,3\]
**Output:** \[0,0,9,0,0\]
**Constraints:**
* `2 <= nums.length <= 105`
* `-30 <= nums[i] <= 30`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
**Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
| null |
Array,Prefix Sum
|
Medium
|
42,152,265,2267
|
309 |
hey hello there let's talk about today's liquidity challenge question best of time to buy and sell stock with cooldown say that we have closely monitored the daily stock price change for a single stock for a number days and now we've been presented with a chance to take a time travel machine and go back to when you all started and now with the knowledge about how the stock price will change in the future day by day we now have a chance to make a version but there is just the one side effect of the time travel there's a string attached to travel machines um time travel machines that is we can no longer trade like a normal trader there are especially a new set of rules applying to a house in terms of trading three things one at any given point we can only hold one share second any given day we can only do three things buy a share sell the share that we currently hold or do nothing every single day we can only perform one of three things lastly there is one day cooldown before between the sale event and the buy event so if we sold the stock yesterday we have to rest today do nothing and tomorrow we can choose either rest or buy one more stock so that's the three rules applying to us now with that rule even stringent as it is we still have to figure out a maximum a way to maximum the profit we can get because who would lose that chance if we really can travel back so that's the problem so let's talk about the broofer solution that's the solution that everyone can think of that is because we are looking at a end day sequence of actions every single day we can do three things buy sell and rest we can just generate all those possible sequences that's three to the power of n and among them are going to be a lot of invalid ones like a sell buy uh sell and buy with no resting in between uh or you know all sorts of crazy uh in unreasonable sequence can happen uh we can just filter those out and among all those possible uh valid sequence of actions for n days we can just evaluate in them one by one and return the maximum so that's going to be a guaranteed solution to the problem the time complexity is really bad it's 3 to the power of m multiplied by m that's the you know the possibility and the combinations multiplied by the time to invalidate and evaluate so that's the brew first solution it's bad because every single day whenever whatever what i choose to do what kind of a state i'm at if i'm holding one stock well if i just sold that stock for that day or i'm taking a rest for that day i have all those possible values because there are possible different ways to getting to that day to that state if the brute force solution is considering all of them but really at any given day if i know what kind of state i am if i'm holding a stock or buy or just sold at one stock or just rested for that day all i need to keep track of is the maximum profit for that day of that state so every single day i just need to keep track of three numbers the maximum profit if i still currently holding one the maximum profit if i just sold one stock for that day or the maximum profit if for that given day i'm just resting how i come over there what kind of paths that i leads me to that position or what kind of low ball profit that again that it can have for that day of that state those are relevant you're relevant for our uh optimizations purpose so that's one thing we can optimize the second thing is we can avoid to generate all those invalid sequence in the beginning to begin with uh so that leads us to have to think about uh the three states and uh how is transition into the next stage uh following the three actions we can take uh if we can avoid generating all those invalid sequences then it's going to you know remove the unnecessary part from the brute force solution so with those two points we can arrive to our optimal solution so let's talk about the three state every day and the three actions to transition from day to day uh the three actions are uh we talked about so many times now buy a single share sell a single share and rest for that day the three different state for the single day is i'm currently holding one share at the end of that day or i just sold my share at the end of the today or today i'm just rested so that the next day i can purchase so that's the only three state we have to keep track of everything their transition is depicted by this graphic if i'm currently holding i can do two things either to rest that brings me to still holding tomorrow right at the beginning of tomorrow if i choose to sell this currency as current share that i have then at the end of the day i will be moved to the just so today this state if i just saw the state if i the third state the only thing i can do by adhering the cooldown rule is to rest one day to move myself to the rest of the state if i'm currently at the rested state there are two actions one is to rest one more day so we stay here other thing is i choose to purchase my share so that will move me up to the float state so this graph shows the three difference data for the day and how they transition into each other if we choose to do one of the three options so with this we can only generate we can generate a sequence that's valid so we don't have to generate invalid the state combined with the fact that for any given day all i need to keep track of is the maximum profit at the three different states so we can use an array to hold this for any given day i can hold that we can keep track of the maximum profit at day i if i'm at one of the three possible states and combined with the transition we can use the prior day's maximum and the valid transition to figure out the next day's maximum so that's the transition function here so let's just briefly talk about that if at the end of day i mean the host state that could only be from the you know to pass that is yesterday i was ready to purchase and today i made a purchase that's this second turn in the maximum uh the first attempt is that um yesterday i'm i was holding on here and today i keep to i choose to do nothing i'm still holding that share so at the end of day i if i'm still holding one share my maximum profit would be the maximum between those two options if i sold one share a day i my maximum can only be looking at the prior day what's the maximum if i hold one share yesterday and i choose to sell it today so that's a single thing here there's no maximum no more options it's just one arrow from so to hold the zone uh if i want to figure out the maximum profit of the i if at the end of the i mean the rested estate that's going to be the maximum between two things uh i rested it today and i arrested yesterday and i rested today that's the one possible the other one is i sold one share yesterday and for the restriction i have to rest it today so two paths to end up with this rest of it so my maximum is going to be the maximum between those two so that's the transition function so with this rule and the diagram we can code up the solution just enumerating over day by day every day we update the three values and at the end of the day end of the whole end day period we just look at the very last entry for the three things and outputting the maximum from those so that would be a linear timing algorithm and if you choose to store the history then it's going to be a linear space solution if you choose to compress it a little bit because if you look at the formulation here to calculating today all you need is prior day we can reduce the space requirement to constant but the good thing about keeping track of the history maximum pass history is that we can trace the paths to get to the maximum profit so if the question not only asks the maximum profit but also ask for the uh the strategy the sequence of actions we do every day with this stored as arrays using linear space we can get that out very easily so that's the time and space analysis for this so with that i'm just going to code this instead of using three individual arrays i'm just going to use a single array with triplets on it's going to be hold the maximum profit for hold maximum profit for sold and maximum profit for rest and it's going to be end entries for that triplets in the in array to initialize this we're going to risk put the initial value for rest it's easy zero for hold and sell code and sold we can look at the transition function later and figure out what's the what are the proper appropriate initial value there so uh we're just gonna unpack the prior days hold sold and rested from the dp array and using the transition function up there to figure out the optimal for today so it's going to be the maximum between the last hold and what if that last yesterday i was resting and uh i'm making a buy action today for so it is the uh there's just one option from yesterday's fault plus the price for today i'm selling the stock that i'm currently holding whatever the past coming to yesterday i don't care as long as my status hold yesterday i'm just i just want that maximum and adding the price stock price for today that i can sell it so that's the sold rest is going to be the maximum between last arrest and last episode so with this i am just i should append this new day's information onto the dp in the end i just look at the very last entry and return the maximum among those three so uh to think about this uh to think about the initial value here for day one the maximum i can get for hold should be a because restless lost the rest in the beginning of zero this is negative price some negative volume so i think i should start with the minimum value as low as possible so it's uh we just do negative infinity and for sold we have the last the hold plus some price uh so it doesn't really matter what value we put there oh for the rest we have to take the maximum between last and rest and so we can just put a negative one it should be fine uh yeah so yeah only last hold has to be uh as small as possible but for so it could be anything that's smaller than zero that would be fine and after that it would just be updated according to the transition functions and with this compared to the buffers the improvements are one every single day or when we only keep the optimal for three different cases secondly for the next day we use the valid pass valid action to nexus state transition to calculating the max for the next day so it's guaranteed it's going to be a valid path and also we will we only consider the optimal day by day so that's this solution uh all right so if you wanted the uh pass to get to the uh final uh optimal profit we can really do a backtrack with this three piece of information here to restore that optimal sequence of actions yeah so that's this question today
|
Best Time to Buy and Sell Stock with Cooldown
|
best-time-to-buy-and-sell-stock-with-cooldown
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
121,122
|
1,311 |
hello so today you are doing this weekly contest 117 I'm going to do right now the third problem get watching videos by your friends and the problem essentially says that we have n people each person has a unique ID that is between 0 and n minus 1 and we get to erase the list of watchit videos for each person there is like the ideas the indexing of the watched video about that person and same thing an array friends where the idea is the list of friends of that person that has that ID and so that's essentially what this says now love we have not owned one of videos which are videos that are watched by your direct friends right and then lots of two videos are videos that are all watched videos by the friends of your friends so second-level friends the videos of the second-level friends the videos of the second-level friends the videos of the second-level friends and in general we second-level friends and in general we second-level friends and in general we have level K or videos that are all watching by people with the shortest path equal to K with you right people that have like shortest path from you to them you know as friends that is equal to K that's what they're watching videos are videos of local K and essentially the problem is we get an ID and the level of videos and we want to return the list of videos of that of for a person of ID i right there is just one way one distinction is that the ordering has to be done in a way where the frequency of the video the videos that have more frequency should be first and then those that have equal frequency should be ordered alphabetically it's in increasing order right so essentially the frequency is let's say you have friends to friends in some level okay that have like watching videos a B and then the other friend has BC so you can see B or care twice so B should be first in the interest of the result and then a and then C because those should be ordered alphabetically so if you look at an example here we have person at index zero has friends one in two so you can see here zero is connected to one in two person at index one has friends zero and three but you see here percent index one has friends zero in sorry person at index two so this one has zero and three and index three has one in two so the graph looks like this now the idea is zero and the level is one so we want the direct friends of Louisville Co of zero right and so those are one in two and they're watching videos RC + BC now you can see so yeah videos RC + BC now you can see so yeah videos RC + BC now you can see so yeah love for one it's one and two so it's this one in this one so their frequency increasing not decreasing so the ones that have the smallest frequency should be first and so you can see here that C + VC C okay twice so it should be last + VC C okay twice so it should be last + VC C okay twice so it should be last and then me first and then here similar things so the graph looks like this you can map trends to it and see that and then level two so it's second level so friends of zero are one in to the friends of one because we want the second level friends at one hour zero nine three zero it's the same one so we ignore it but two it's also zero and three so we have only three that's the one we are looking for and three has watched videos D so we just returned D so we get the idea so let's see how we can solve this problem okay so how can we solve this problem so first let's just make sure we do understand that very well so we have two things we have watched videos right which is an array right and then we have friends so this is basically the input and then we have the idea of the person right so we have the ID of the person and we have the level and essentially what we want from these two is to get videos of watched videos essentially of friends that have level K friendship I will call it and what level K friendship means is that so if level one that means just direct friends right and level two would be friends of friends and level three would be friends of friends so we get the idea that's how it's kind of a graph of friend and the first level is the direct neighbors the second level is the direct neighbors of the neighbors and you keep going like this right and so this is the idea of the person that will look for watching videos of their friends that can be level K and then we have these two arrays that tell us for each ID what are the watched videos and for each idea what are their friends right and so the first example that we had was like this we had the input of watching videos that was like something like this where we have a B we had C we had B C and D right so essentially if we map this so the idea 0 so these are the ideas here and then I D 1 2 3 and similar thing for friends where we would have 1 2 0 3 & 1 2 0 3 again and then 1 have 1 2 0 3 & 1 2 0 3 again and then 1 have 1 2 0 3 & 1 2 0 3 again and then 1 2 so essentially what this is the friends of the person of ID 0 R 1 2 / friends of the person of ID 0 R 1 2 / friends of the person of ID 0 R 1 2 / self-id 1 has friends 0 3 person of ID 2 self-id 1 has friends 0 3 person of ID 2 self-id 1 has friends 0 3 person of ID 2 same thing and 3 like this so if we draw the graph for this we would end up with something like this so we have position we have 0 right has friends 1 & 2 so who has friends one and two and then one has friends zero in three and two has friends zero in three also and three has friends one and two right and so now the question says gives us these two gives us ID equal to zero and gives us level one so direct friends and so level one of friends of zero are one and two right and then level so these are the friends and then they're watched videos are the watched videos of 1 which are C and the watched videos of 2 which are BC right so now if we map the frequency so the frequency of watching because the problem says we need to so this is we know the result now the problem says we need to sort it by like the by their frequency of watch right and in increasing order so the smallest the one that has been watched the smallest number of times should be first and then if there is a tie we should sort them alphabetically so here for C it has been washed two times for B 1 so that would mean the final result should make B first and then C so this should be the final result and so now you get the idea so you can see here we kind of have two parts to this problem the first part is finding level K friends right so this is part one of the solution right and then we have part two here which is get the watched videos and sort the right sort them by the frequency of watch and then alphabetically right so we have two parts so let's see first how we can solve the use the first part so part one which is get friends at level K right so you can see here this is a graph right and getting a friends at level K is exactly neighbors at level K right and this is something that using BFS on a graph can be us right away right and so we know that the first step we need to do is just get that now the second part which is once we got the levels at position K with BFS it would be just the content of the queue once the level K has been reached at right now part two which is get watching videos right and sod them and so to solve them we need a map that just a counter right that just says how many times each movie has been so map or a counter in Python to just count how many times it has occurred and then we can sort using that and then so we can sort if let's say we have this thing frequency is the map then we can just take the watch it movies was called plus suppose we put them in res you can just solve them in Python using the key where the function that well did the salt would be would use the frequency right first as the sort key and if the frequency is the same then we can just use the lighter itself or the move the video itself the video string itself right and that would be pretty much it okay so now let's just code this up and see how it would where it would look like so essentially the idea is this BFS and then the last to get the level the friends at the level K and then once we do that we will just do the map and then salt using guilt to get the count and then salt using that count right okay so now let's just code this up and see how it works to get friends at level K right friends of ID I plop okay right so we need for BFS who need a collage queue the DQ sir so for that we need to import collections and we need a visited set so that we don't visit notes twice and for the BFS we need to start at position ID I'll just call it I here and for the visited set we need to have to add the note W that we visited which is first I and now while level is bigger than zero so we will keep decrementing which means when it is equal to zero that would mean we are at level K right and so every time we do a level with the payment level right and then now we'll do a lot of dialogue right so we will go through queue right so this is the current level in the queue and so here let's say for maybe instead let's just get the size of the queue right and then here while for college in range of the queue so we know the size so now we can just say pop left to get the first element in the queue spot that J and then we will go get the friends of J and go through them so those would be friends at Louisville here of obj right so we get this and we'll check if we haven't visited them yet that means we can add up to the Kuna right so we depended and then we would add them to the visited set because we visited them and then now that we now when we get to here where which means that level is equal to zero at that point we can serve largest so here we get we are at the level at level K so Q here at this point contains basically friends at level K because we reached level zero starting from K right level was K and then keep decrementing until reaches zero and so here is where we have the friends at level K so here we can do part two all right so this is part one that we described it in the overview now we can do part two which is get watched movies of level K friends and solve them in the order that is asked from us and so first let's just have this array to contain them and then the frontal over K we all go through each of them and each of them will get the watching videos right so we will have will need to have a frequency thing that counts how many times video has been watched so let's just call it use this here so that it can default to the valley can default to 0 and here we would have watched videos of that specific front and then we'll check if we haven't yet added it to the result we don't want duplicates remember so we would add that watch it video right sorry first before doing that we'll just say that it has been watch it one more time right so at this point we will have the frequency of watch part right and then we'll add it to the result that will sort letter okay and now here actually so we need to do this here and then here only added ones one we don't have much time and now we can sort a result right so we can say rest sort by first the criteria is that by frequency so increasing order and then if the frequency is the same its lexicographical so the way we can do this with python is just having a key called lambda here with X and the first criteria for sorting is the frequency and the second one is just the video name itself so that I think is sorted Expo graphically and then pretty much after that we can just return rez and that's pretty much it so it's wrong here it's strange of em actually okay so that looks good there was another test case I was do that one so these are the watching videos and then friends id0 love to okay looks good to me submit okay so it passes the test cases so yeah that's pretty much it the solution for this problem just these two portion and then doing BFS level by level yeah so that's pretty much for this problem thanks for watching and see you next time
|
Get Watched Videos by Your Friends
|
largest-magic-square
|
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your friends, level **2** of videos are all watched videos by the friends of your friends and so on. In general, the level `k` of videos are all watched videos by people with the shortest path **exactly** equal to `k` with you. Given your `id` and the `level` of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.
**Example 1:**
**Input:** watchedVideos = \[\[ "A ", "B "\],\[ "C "\],\[ "B ", "C "\],\[ "D "\]\], friends = \[\[1,2\],\[0,3\],\[0,3\],\[1,2\]\], id = 0, level = 1
**Output:** \[ "B ", "C "\]
**Explanation:**
You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
Person with id = 1 -> watchedVideos = \[ "C "\]
Person with id = 2 -> watchedVideos = \[ "B ", "C "\]
The frequencies of watchedVideos by your friends are:
B -> 1
C -> 2
**Example 2:**
**Input:** watchedVideos = \[\[ "A ", "B "\],\[ "C "\],\[ "B ", "C "\],\[ "D "\]\], friends = \[\[1,2\],\[0,3\],\[0,3\],\[1,2\]\], id = 0, level = 2
**Output:** \[ "D "\]
**Explanation:**
You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
**Constraints:**
* `n == watchedVideos.length == friends.length`
* `2 <= n <= 100`
* `1 <= watchedVideos[i].length <= 100`
* `1 <= watchedVideos[i][j].length <= 8`
* `0 <= friends[i].length < n`
* `0 <= friends[i][j] < n`
* `0 <= id < n`
* `1 <= level < n`
* if `friends[i]` contains `j`, then `friends[j]` contains `i`
|
Check all squares in the matrix and find the largest one.
|
Array,Matrix,Prefix Sum
|
Medium
|
870
|
213 |
Tomorrow morning, friends, welcome to the new video of line 7548 and today's find our husband, ninth day of this, we are growing up and this is number two, we were number one, shot a second was difficult, this week ago, exact, a week ago, we did the house. Used to have problems and knowing this is very-very important. Back to and knowing this is very-very important. Back to and knowing this is very-very important. Back to understand that house of the two, I have opened 501 in front of you. Its explanation is in a small fold, so it is better to go to it to see its explanation and then you will understand. How important is it because I have just copied and pasted it, look at this chord from here and here, look at the chord that I have taken, look carefully, it is the same hall of the egg. Okay, I understand, so what is the question saying? The question is the same. Earlier it was but what is there in this? An arranged inner circle i.e. the what is there in this? An arranged inner circle i.e. the what is there in this? An arranged inner circle i.e. the first and second people who link each other will also be adjusted. The second year and the best ones, that means two and two will send messages to each other in the same way in a circle. 141 The last one will be called juice end of each other, then it will affect the output, that is the thing that you have to note down. Well, if you answer it from that problem, then you are trying to do it through Play Store and this because this is the same thing. Let's go a little further, do a little roasted give, I have taken it, now if you remember, House No One Knows, I told you HR One, I used to do something like this, I said that only the mill has to see two values. So that means R1 r2 Robin, I told you something by right two, so in the beginning, I will check this, then our curd will be mixed, okay, then I will check these two, then I will run, which of these is bigger, three are bigger, we will go together with this. PS2 works on balance. Now when I want to put in two chords, I will check whether the maximum is increased by both of them or whether they are same except three, the latest four will definitely be a chance. Time means how will I look at the best way list to see that these Should I give the answer to the one which was macrame out of the two or is it because the requester has not given it, leave three, add two to the previous two and then four answers have come, okay but our house is the road to you. It may seem a bit like two, three, two circles are being made here, now in the circle both of them are ours, right, you can't catch them like this, we will ultimately take only one, so three is big, so three will be the answer, one you, a little bit for a moment. Let me tell you the thing, what difference is it making to me here that I have so many big lists, two three four one, it is getting loose, where should I put a little, there is branding in the starting, I just add the distance of starting reduce circle to point two and starting and There will be adjustments regarding ads, right? What will you do to avoid this, we will use the same code that my previous friend was using in the police station i.e. the house building, we will use it using in the police station i.e. the house building, we will use it using in the police station i.e. the house building, we will use it twice, for so many people, dates from one to - And the second dates from one to - And the second dates from one to - And the second measurement is made from 1020 - and the second one, except the first one, measurement is made from 1020 - and the second one, except the first one, measurement is made from 1020 - and the second one, except the first one, means except the first limit, put a call on housewife exile in these and leave this in the second one, leave the last one and put it in these three. Sanaya makes the diagram again. That's why I am from Banaras, so we have something like this, open it, what did you do, what will I do in the post, that I will attend, not that I will put HR 18201 problem in all of these, I will leave the first one, it is okay that I will bring it to the first and last ones and then on these. I will put it and leave the last one, HR one problem, you tell me which one is it is ours - it tell me which one is it is ours - it tell me which one is it is ours - it is okay, whatever maxima remains among these two, get that maximum printed, otherwise it is okay, it is more than the method. If there is gravity, then let me tell you in the court, you have to sleep, so what to do in it, I took the diet exactly the previous one, it was four 1501, which gave it an accident, here and there is our own function, which is also made for this question. In that, I returned the maximum number of numbers starting from one till the end of the best i.e. test zero and the second best i.e. test zero and the second best i.e. test zero and the second number starting from zero till the end minus one i.e. slot the last one of these two. one i.e. slot the last one of these two. one i.e. slot the last one of these two. Maximum will also come, he will return ours. Now you have thought in your mind that why is this number 0, then imagine, you have such a case that today anyone has to see how one has only the name in it, there is only one list in it, element one of the camera. So according to this, it will be seen here that it will not consider the first zero and according to this, it will play both the live web series start and the last song in the computer for the last time, then it is better to have a null return than a null return, time answer. Two should be made according to that means if you have to steal then the name House of Birth will be useful on 087, the code is simple, I had run it, I had to make the video again, it was like this, please, etc. King, it is time being displaced, neither is it. You are working in the episode, leave it, well, that's all for today, see you in the next video, how will I look?
|
House Robber II
|
house-robber-ii
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[2,3,2\]
**Output:** 3
**Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
**Example 2:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000`
|
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
|
Array,Dynamic Programming
|
Medium
|
198,256,276,337,600,656
|
1,710 |
hey everybody this is larry this is day of the first day of july leeco dairy challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm so yeah i think my face is blocking this uh here-ish blocking this uh here-ish blocking this uh here-ish but i have an 821 day streak so if you're joining us for the first time you know starting the july uh attempt uh we'll be doing this all month and probably as long as we can you know as long as i can anyway 821 days trick is pretty long so anyway today's problem is maximum units on a truck oh yeah one more thing i would say is that uh join the discord if you can um uh it's free i don't know if this is obvious sometimes people think i you know just paid membership or something uh if you really want to pay for something you know donate your money to uh a good charity i have a list if you like um but yeah and i think a lot of people do get more from sharing their code and discussing you know maybe they did the code in a uh a different way or something like this so i think there's a lot of value in that and also just you know everyone doing it together so check that out um yeah anyway today's problem is going to be a yeezy not my interpretation it's just for the staple 1710 maximum units on a truck you're assigned to put some amount of boxes on the truck you're given a 2d box type number boxes number okay um okay number boxes of type i and i mean these variable names are actually kind of self-explanatory so i appreciate them of self-explanatory so i appreciate them of self-explanatory so i appreciate them being very explicit anyway to give them a truck size which is the maximum number of boxes you choose any number of box as long as the number box system okay i mean okay this is literally greedy to the max i mean i think this is a very silly problem um but there are components here that um i mean i think one thing that i would maybe try to do for a problem like this is that one well it's greedy you recognize it's greedy right and then two is see if you can understand the problem enough to sh to explain to a friend of yours or a colleague of yours why greedy works um not gonna lie even for me it's a little bit tricky because greedy problems are kind of the hardest thing for me and if you've seen my videos which i don't i am doing live so it's not just explanation it's about my thought process as you see it and as i think about it the explanation and the problem solving everything is live there's no editing no cutting and fortunately i think for the most part i don't need to use the bathroom in doing it so but in either case um so yeah so i think that will be the most important part but otherwise uh yeah otherwise this is pretty straightforward i think the idea is that okay let's say you know you can maybe do one induction or something like that right where okay let's say we have one no you know max box is one box right then what will you choose well it'll just buy maybe there's an actual form a mathematical name for this because i feel like you know there's always a mathematical name for everything but you know just a bigger number gives you the max number of units right so i think that's pretty self-explanatory and then that's pretty self-explanatory and then that's pretty self-explanatory and then you can build induction on that right so of course because now you have one box almost like a recursion type thing where you take one box you took the greeting and there is this like uh the sub this structure of uh optimality right and that's basically what a lot of greedy problems build on um so yeah okay so that said let's get started what does that mean right so now we ask we know what we want to do we want to get the max units per box so then why not just sort them right and sorting is a technique it's not i mean it's a technique it's an algorithm it's a thing that you do to process the data but of course the uh greedy is the big part of you know this problem you know there's sorting um and sorting is just a tool to get to allow you to greedy by imposing a structure on the problem okay so first let's sort uh let's sort by what are we sorting by uh let's see number of boxes number of units per box is what we want to sort by so that's b sub 1 and we want to get the maximum right and here i'm going to do a shorthand uh i mean and the second one actually doesn't even matter so we could even eliminate it but i can't put it here for emphasis um but the idea here is that and i say this every time so if you already heard it but um you know you're sorting by men or like sorting out by default is min so here we reverse it so that we sort it by the max unit per box in the beginning and i do that by negative of course you can also do like a dot reverse or something like that afterwards but uh doing it the other way but you know there are many ways to solve it's okay as long as the complexity is good complexity is gucci uh cool okay so then now we go for what is it number so let's just say num maybe and then unit in box types uh and then we what do we do maximum so total is equal to zero um let's say yeah let's just say left is equal to truck size um and now we could go okay so yeah let's just say using is a keyword probably right so used is equal to min of left or unit and then total we increment by the number we used plus oh wait no unit is not right oops i meant number of them yeah and then this is times unit and then left we subtract it by used um and that's pretty much it really i mean you can also terminate a little bit earlier if you already get zero but i think that should be gucci thankfully i didn't embarrass myself let's check um i'm just checking about the edge cases um so this is analog again that's why i didn't really look at the uh the constraints because when you have an analog again it's going to be fast enough for almost any reasonable ends um and of n space because we use the space i suppose but it's not x the value would say but yeah i mean i don't so we don't care about this uh and we don't care about this except for maybe to see if it overflows um so yeah so the number of boxes so we have a thousand boxes each with a thousand uh units and then we have a thousand uh box length that's going to be a thousand cube which is a billion or 10 to the nine which is going to fit an int i know that i'm in python so that's not technically necessary but it's just something that i want to make sure right um but that said um yeah i mean i think that's pretty much it right just so let's give it a quick submit because a lot uh i've been kind of sloppy lately so i just want to make sure watch i still kind of mixed it how did i make a mistake last time oh i hope i okay good you never know sometimes even when yeah so 822 two days of streak what is i think i kind of alluded to it complexity but this is n log n just a sorting and here is obviously linear times going up one at a time okay i'm just curious what the past larry did to deserve that one time hour did i just uh oh how did i that's just sloppy larry how do you not check that box type is greater than zero okay but in any case yeah um that's all i have i hope y'all join me for the rest of the month either on youtube or on discord or however you like or just at home and you know just follow along uh cool that's all i have stay good stay healthy take your mental health uh i'll see you later and take care bye
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
1,648 |
hey everybody this is larry this is me going with q3 of the reason weekly contest 214 self-diminishing while you'd call it self-diminishing while you'd call it self-diminishing while you'd call it boss uh so this one was i think the hardest problem in the contest let me do a quick refresh to see how many people solved it about 200 people solved it about an hour in uh definitely if you look at the high score um a lot of people took way more time on q3 than even q4 and myself included um so definitely a very tricky problem uh and we're going to go over it and yeah so this problem i think the there are a couple of things to do um thing is to understand right so it the core concept of this problem is greedy again so what does that mean right because as i mentioned maybe even other videos greedy means a lot of different things to different people and there are different ways to be greedy and sometimes you're right and sometimes you're wrong in this case the greedy that i chose to do is that giving looking at this example and for greedy problems very often you'll see is that in the problems they uh especially in examples they try to put it in a way that to you know disguise the greedy method because you know otherwise they would just you know people would just get the answer so it's something that problem solvers will try to kind of mix it up so it so if you as long as you get the right answer maybe it doesn't have to be in the right in the same explanation uh same way as the explanation and looking at the example one i think because so for this problem the amount that you get for a ball is equal to the number of balls already in your inventory that means that in this case if you use the fi you buy a ball from the five bucket you get five and so forth and then fourth and then three right so i think that the greedy is very intuitive here is that you always want to take the bucket from the max and then you know buy from the max right because it doesn't make sense to uh buy it from a cheaper bucket because uh to get the optimal cost so that's kind of observat uh the first observation and that should be pretty understandable um or it should be pretty intuitive though as usual sometimes intuition will fold you up why but yeah so then it becomes an implementation problem right so the thing that we look at after that is that you know what orders well inventory could be up to 10 to the nine which is a big number and also number of orders can be up to 10 to the nine so that is also definitely a big number because basically my first instinct looking at this is and what we said about greedy is that okay if we want to get the max every time you know there's a very natural data structure for it right is that we put everything in a heap and with a heap we can just take the max element every time and yeah and then subtract from it you know take one order off the top and then poo right um and then we could take that order of the top add it to the total co value and you keep on iterating it all those number of times however given that orders is equal to a billion uh it's going to be too slow right you can't run a billion heap operation is just definitely too slow and yeah and even inventory length is 10 to the fifth so that's going to be pretty rough in general right so the thing to notice in this problem though is that okay right for a bucket let's say you want to buy you know let's say you have a bucket of 10 or let's even say a hundred and you want to buy 10 balls from it right well the first thing you notice is that um okay so the first ball is going to be give you 100 bucks second is going 99 plus 98 plus 97 plus you know dot right uh when does it end well it's going to add a 91 because 10 balls you know you could count it out right so we have to do the math for this and it turns out that the math for this is just simply this is equal to uh one plus two plus three plus four plus dot plus 91 plus 92 plus 93 plus dot plus a hundred right uh minus one plus two plus three plus four plus five uh dot plus 90 okay maybe i should do the 90 here right so if you subtract this formula from this formula you will get this formula right and so and you know that this formula is equal to just a hundred times over one over two and this is just 90 times 91 over 2. so that's basically the math is that um you know and i should have done it as a helper function and also my implementation was a little bit weird because in python it is a min heap and i made a couple of mistakes uh that slowed my submission time down because i had the negative a couple of numbers that was very confusing i need to do a better thing about max heaps in python because my pattern is just keep on making me focus on stupid mistakes but anyway so now you know so given a bucket of a hundred and we want to buy 10 balls it is just z code two um yeah one over two minus ninety times ninety one over two right so that's the one key observation and then another second key kind so that's one compression you can do so that you can kind of make it faster right because now you don't have to do this instead of doing 10 heap operations you compress to one heap operation right but then now the second question is how do you do say let's say 100 and then 95 and you want 10 balls right well you know that eventually i mean we're gonna have to massage the math but that's another case um and let me make this a little bigger right but we know that the second state that we want to get to is 95.95 that we want to get to is 95.95 that we want to get to is 95.95 because at that point we want to sell the 95s together right so this will take with five balls left right so this is the reduction or we reduce this to this problem five more stuff plus you know plus uh equal 2 buy five bullets from this five votes left right um and that's kind of the math that you and so those are the two cases right the other case might be that like you know 100 and then you have a bucket of 50 um and you want 10 balls but you know that doesn't matter because you just buy 10 balls and it goes to this right so those are your cases um yeah and so then now we just have to handle the case of okay in this case right what does that mean so you just have to for me you just have to um you have to do them together and what i mean by that is that now i will compress this instead of kind of because you know like if you have um i don't know let's say you have a billion and you want to take also a billion bars i don't know if i have to write number of zeros that i do actually uh so you still cannot simulate this because then this would take a billion heap operations right so what i do is that i actually compress this to say let's just get rid of that uh i compress this to a 95 to two tuple with five boards left so that we can do it together and then now the math is similar to this thing and you have to do a lot of case-by-case analysis but it's just of case-by-case analysis but it's just of case-by-case analysis but it's just simple math in that now well five bullets left that means that we want to buy there are two buckets to buy from so five balls we want to buy um wanna buy two from each bucket first so that's the reduction so now it goes to 93 2 with one ball left and then now you could just pick one of them because nine of the bucket matters right buy one from either bucket so that's kind of the logic that i'm trying to implement into my code and this is the explanation of how i got there uh and then now we're gonna go over the code and of course you have to remember the mod otherwise you can have a sad day because um but yeah so that's how i'm going to think about it and that's how i implement this i end up taking a long time uh almost 20 minutes because as i said i implement stuff with min heap uh where i want to max heap so uh just carelessness but yeah so basically i heap i start over here by pushing to the heap and this is the negative extra that i could get the max heap but basically i pushed the x on top with a bucket size of one and then while we have orders while we have heap we take the top element we invert it just to that because we know that this is inverted and we pop the top and then we also do this thing to compress and what i mean by that is that this basically operation goes from uh if your heap looks like 95.2 95.2 95.2 oh sorry 951 not 95 one it just compresses to 95 too so it just compresses the buckets uh it gets the next number this gets the next thing on the top of the list so that basically for example if our case is uh 95 say 2 and then the next number the k about is 80 we want to uh and five of them doesn't or maybe one of them because i guess they all should have only one um right then we take the delta meaning that after buying 15 times two balls from the 95 bucket we have to look at more items so that's what the next one more buckets so that's what we have to that's what my next top does here and then i you know just and then all this is just math i could i'm gonna go over briefly but if you have trouble understanding this part uh maybe rewind a little bit because i do explain it here uh fully i hope so if not just let me know ask me questions but basically this is the case where orders is very big so you know let's say we have uh in this case let's say we have 100 orders so we can buy them or and right so that's just top to the next top and again this is the math and we have to multiply by the account because that's the number of count that has that bucket we subtract it from orders we add it to the total we make sure we mod um and that's kind of this logic otherwise then this is the case where i talked about this is this case right here where well okay we only have five balls left from this from uh up two buckets of 95 so we do the math how many orders do we you know how many um how many per bucket are we buying from that's the number so then we get the fake next top this way uh because then we go from 95 to 93 and then we subtract it again this formula we explained earlier and then we just count um add the number of buckets and then we also have we multiply by the number of buckets that is in the current bucket and then we add it to the total we subtract from the count and then the leftovers is just in this case you have one ball left because and this ball will always be mod um the count because if because that's the definition of this part right uh is whatever's left over from there um i could have used diff mod actually and then we just kind of look time just by the next top because we know that um leftover is less than count by the definitions modded by count so basically we always take the most expensive buckets and you know and that's basically the math um and then at the very end we push it back into the heap meaning that for example we have this case after we process it we want to push this to 80 to 2 and then it gets compressed later on by this earlier step uh and that's basically it uh that's all i have for this problem it's definitely tricky it took me 20 minutes people have gotten it uh you know even really good people took a long time so i would not feel that bad if you took a while on this one um and there's a lot of potential by off by one so it actually hm not that many wrong answers on this one but as i might have expected but yeah um let me know what you think and yeah you could salvage it in the uh you could watch me approach this prom during the contest next uh i have a lot of like i said there i think my just analyzing myself things like i've done better just be more careful about min hebrew versus max heap that's a python thing and then the second thing is just um i think i spent too much time in the beginning just trying to think with just another way to do it instead of like just solving it even though this way is annoying and hard um i just needed to do it um that's all i have for this one yeah watch me stop it in the contest let me know about you how you did it did you find this farm hard was the math okay uh was it you know did you have 12 degree let me know uh i will see you afterwards uh hey so actually uh before i jumped into the solving i just realized that i forgot to explain the complexity so yeah let's go over the complexity real quick is that you know for each element in the list we push it to heap so that's going to be at least n log n um yeah and n is equal to 10 to the fifth and the question is how many times do we pop this off how many iterations does this do right well that's where we try to figure out an invariant to this problem and in variant is that for every iteration we are always going to get rid of at least one uh the for every iteration the heap always shrinks by one element and the reason why you can see that is that you know for every let's say you know you have two elements for example that's here let me make this bigger oops uh you know my computer is a little slow my apologies but let's say you have you know this is the heap well this is this heap is going to turn into uh from 95 to 80 oops the next elevation is always going to um go to the next number right um and the reason why that is the case is because we literally look at the next number to uh to put back in the heap right so we're always going to um so this is always going to be a function of the next number and of course we have this thing here that compresses it so that means that for every iteration the size of the heap shrinks by one so that means that given uh the heap of initial size n it's going to take n iterations and in each of these iterations there are a couple of log n operations uh on actually only yeah a couple on hip-hop hip-hop hip-hop and hip-hop and he push and hip-hop and he push and hip-hop and he push so there are a couple of uh log n operations so it's gonna be just analog and it's the entire complexity and in terms of space we only need the heap for the space so uh and you know an extra variable so it's going to be linear time and log at oh sorry linear space and log in time and that's how uh i would analyze q three in terms of complexity yeah watch me stop this during the contest next thank you for watching and all that stuff once basically now you want to keep it apply that much hmm oh this is an annoying one let me still use a heap okay fine um okay so pee this so now we push it back on top oh this that's not right okay maybe right well that's why for this case oh right oh i had to do orders this is annoying as hell this should be 12 so my map is a little bit well let's fix that first my what is that small right two you else what do we do hope it can always be can we simulate whatever unfortunately i have a 10 minute penalty so what is silly watched it kind of slowed down so i'm okay just focus on getting it right um hmm so that means that dr times count is less than orders so for every count do that first next step is you come to top minus number doesn't now there's a orders mod count next top hmm this makes sense that this has smaller fewer bores so let's fix that hmm this is already well this because this is this and then hips and max heaps mixes me up it's not good okay let's see well this is what's gonna happen oh more right answers it's still one this one i think right on this one though i'm all in this one why buy off by one it's good five one two nine is a five and a four two so it should be uh this math is wrong that's i good this number all right so we're going to did two four numbers and stuff that's good number is two we do one two iteration of this so that means that we next top should be one right why is it tilting now so high five because it should be three times three is six oh is that right no this is count 1999 i mean this is why for the test examples i'm not confident about this one okay thanks for watching everybody remember to hit the like button hit the subscribe and join me on discord and we'll chat about stuff later bye
|
Sell Diminishing-Valued Colored Balls
|
minimum-insertions-to-balance-a-parentheses-string
|
You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the customer would pay `6` for the first yellow ball. After the transaction, there are only `5` yellow balls left, so the next yellow ball is then valued at `5` (i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, `inventory`, where `inventory[i]` represents the number of balls of the `ith` color that you initially own. You are also given an integer `orders`, which represents the total number of balls that the customer wants. You can sell the balls **in any order**.
Return _the **maximum** total value that you can attain after selling_ `orders` _colored balls_. As the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** inventory = \[2,5\], orders = 4
**Output:** 14
**Explanation:** Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
**Example 2:**
**Input:** inventory = \[3,5\], orders = 6
**Output:** 19
**Explanation:** Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
**Constraints:**
* `1 <= inventory.length <= 105`
* `1 <= inventory[i] <= 109`
* `1 <= orders <= min(sum(inventory[i]), 109)`
|
Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer.
|
String,Stack,Greedy
|
Medium
|
2095
|
901 |
Hey everyone, today we are going to start a new playlist of ours. Stack is okay, it is a very popular topic too, many questions come on it in interviews. Okay, I have an interview in the phase in which star related questions came. Okay, and I will let you know about the track. It's all about Pushpa and top right. So let's see which question is today. Question number 91 is a medium level question. The name of the question is Online Stock Span. Okay and this is a very popular question. The question is good and there are similar questions too. I will tell you which questions you have, so these are the questions, those are the questions, Easi is a category, isn't it, these types of questions come, okay, now the companies who have asked are Microsoft, Flipkart, Amazon, Samsung, so look at us, don't stop. The span of any stock has to be determined. Okay, so all these are given, they are giving you the price. These prices are yours. Okay, the stock has given the price of any stock. So, on any particular day, if you buy a stock. If you want to get the span of stock, like man, this is the day, okay, one, two, three, fourth day, this is the fourth day, if you have to get the span of the stock, then how is it, I will tell you, like, what is the value on the fourth day, it is 70, so it is on this day. Okay, go first and till the price of this stock is equal to or less than 70, if you got one eighty, if it is bigger than that, then stop here. Okay, so how many total should we get, one or two, okay, this means on the fourth day. Look at the stock span of 75, it is ok, brother, it is equal to 75 or smaller than that, you have to find the stand price in the previous day, it is ok, first, this is 75 itself, first, 60 is a little smaller than that, second, it is smaller than 70-20. The 60 is a little smaller than that, second, it is smaller than 70-20. The 60 is a little smaller than that, second, it is smaller than 70-20. The third one is 60, less than 20. It is small, 70 is also small, 60 is also small, 1 2 3 4 5 6 So look at the answer, ours is six, right, simple, not much, two, and if I take it, let's see its, if I take it is okay, then one, it is itself. 100 A was given in the day before this, which is bigger than this, so brother, we cannot include him, so there will be only one answer, its ok, what is the condition of the one before me, 70 should know. Neither did he have the condition, it is fine, so now we will have to store the information of this pass, now you are standing at 60, you should know about 7060, that means the days before 60, only then you are able to find the answer, right? Then you can apply the same brute force method that row at 60 i = you can apply the same brute force method that row at 60 i = you can apply the same brute force method that row at 60 i = index 60, after that what you are doing is you are going backward. Okay, put a for loop and then see how much row is there, then you will come here and then you will go backward. You are applying foda loop, so friend, this is the same now, it has become the root four method, because look at the example here, like man, if you do it from back then it will be 70, then it will be 60, then you repeat the thing again and again. You are doing this is a beautiful way, this will also solve the problem of n², this will be a very easy solution, but this is our answer which is correct and yes, remember one thing that I told you that When we are on the index eye, we are coming out of it, then when we come here, then we will come out of it in brat force manner, then come here again, then see some parts are getting repeated again and again. Questions of General S General Stack. No, if you look, it follows a similar pattern. Okay, and in broad force, stack helps you. Generally, if you want information about the past, then look at that question. So first let's see how start will help us here. Okay. Hey, let's start, then look, first of all, I came to the hundred, okay, now the hundred, the stack is empty, so brother, if you don't want to do anything, then I will say that brother, whatever is 100, his PAN is still there, so I have stored it in the beginning. I have done it, why am I taking note here because the numbers that will come next will know that they are direct, they will know by looking from the top of the start, what is it brother, do I have an account of my past or not? We need a calculation, it's okay, so in the answer, we have given a team of vans which come on my current, okay, so 80 is the first good, 100 is bigger than me, so brother, if you can't do anything, then your friend will come here quietly and say. That my spawn is only 1 because he is 100 bigger than me so his spawn is 1 A in the answer. Now coming to 60, okay, it will look sexy. 80 is at the top of the stack, so it is bigger than me, which means I can't go ahead, so the one who is 60 will be happy in the van. 60's van is the answer, isn't it, because it is a little smaller than sexy. It is bigger than sexy, we need small elements around us, we need small elements neither 60 small or equal. Now when I came to 70 saw that ok this is 60, 70 has its own place, how much van, now 70 has taken the stack. Looked at the top and said here, okay, it is smaller than me, so I add its span too, so it had a span, did n't it, I added the van, okay, so it is 60, we have done 60, now it is 80, so it is saying 70. It is not good, 80 is bigger than me, so brother, whatever I am, you are my span, it means neither are you nor this, I have written 70, how much is the span of 70, if you came, then I have stored this, if I have stored this, then later which. It will help the elements that will come in the future, okay, now I am coming to 60, okay, now let's see, I looked at the top and said, okay, 70 is bigger than me, so brother, I can't go further, so what was the square of 60, mine is 75, okay. So it is at 75 looked good. On the top of the stack, first let's write here. What will be the span of 75? Right? Pen of 75, I have my own van. Now on the top of the stack, he saw it is good. It is 60. This is smaller than me. If it is there, I will add its span also. Okay, I have done that. Okay, now start and look at the top. Again, it is 70. This is also smaller than 75 and its span is also yours. So, I have added its span. Pop this also. Sorry, it is bigger than 75, so we cannot go beyond this, so how much is our span? OnePlus One Plus is 75 and we have added 75 and its span is written as 4. Okay, now it is 75. This is smaller than 85, so its span is fine, let's add plus four. Okay, so you see, 85 has already found out from 75 how many fans, that means, what was the span of 75, this and this, look at its four. It is like this, we have directly added 85, right here, now we will look directly at 80, we did not need to see them again, 75 told us directly, look at 85, brother, it is my span four, so now yours too. By the way, it will be four, okay, you add yours to it is okay, that is, I have done it to 75, now it will say 85, okay, it is smaller than me, so I can take it in this pan, so I have taken the plus van, okay, I have popped it. Then what are we left with, if it is bigger than 100-25 then we what are we left with, if it is bigger than 100-25 then we what are we left with, if it is bigger than 100-25 then we cannot convert it to that, then how much total span has been calculated, 4 5 6 has come, so let us write here that brother, the span of 85 is six and here we have returned six. Gave the answer and we went out with our 'Hey, that's all, okay, look at our output, the with our 'Hey, that's all, okay, look at our output, the with our 'Hey, that's all, okay, look at our output, the correct output has also come. In storing the information of the punch, 75 directly said, 85 must be there, brother, there are four small elements behind me, I mean. I'm sorry, my spawn is 35. Well, 75 is smaller than me, so 75 has a span, so it can be my spawn too, because 75 is smaller than me, that's why we have added four here. Is 75 a span, or 80? But we went to the van whose van we had added and this van itself was of 85, so we got a total of six. The stack is helping us so well. Okay, so there will be a very simple code for this, first of all PAN. There will be a starting van, there is only a van in the starting, what will we check after that, brother, unless there is a strike, this check will have to be done and end and every now and then we are moving forward, when we pop and when we do it, when the stack is done. The price which is on top of the stack is smaller than the current price i.e. the price which is on top of the stack is smaller than the current price i.e. the first element is on the top of the stack. What is the price of the first element? Is it less or equal? This is my current price. No, if it equal? This is my current price. No, if it equal? This is my current price. No, if it is so, then we will keep doing span plus plan, it is equal, you are doing span plus, let's just tell the story, okay, let's return the span also and we have done something in the stack, okay, what a simple kurta. There is a code of five to six lines and look, okay, this one must have been simple for you to understand, what I told you is that it is based on this concept with many questions which is very similar, now you go and make this first, okay now. You go and open the lead code number 739. Okay, the name of the question is Daily Temperature. Okay, now go and solve it yourself, it will be solved on its own. Have you understood this, neither have you understood this concept, nor have you understood this will also become. And this is done, it means that you have understood the concept. If more questions will come based on this concept, then you will be able to make it. Okay, and let me tell you one very good thing. You must have seen the nature of my stack, the stack was always in ascending order from bottom to top, okay. So what we have done is that we are wrapping it. Okay, then we are placing the smaller element A here and we are adding its span. You must have noticed the nature of the stack, that it is ascending order. It was happening every time, such a stack is called a monotonic tag. Okay, it is a monastonic stack, that is, moral story tag is also a concept which you should know, there are many questions on monotonic type, it is also like this, isn't it? There are a lot of questions based on questions, so the liquid that you will prepare in 7:30 is also that you will prepare in 7:30 is also that you will prepare in 7:30 is also on the monotonic track, it has the same questions, just the wordings are different, go and solve that one too, it's okay, first solve this one, okay, let's code it. If we do it, then let's see the question, it is exactly what I explained to you, this is the example I told you, okay, whose output was this, okay, and the input will come to you in this form, the compiler will call it again and again. -It's okay, so and again. -It's okay, so and again. -It's okay, so every time the input will come one by one, 100, then 80, then 60, so you have to keep returning the span one by one every time. Okay, so let's solve it in exactly the same way as told. What did I say that we will keep a sorry stack, okay what will we keep in the stack, what will be the leg, I have it, okay, start, okay, what is the leg off, this leg off will be the price, and what is the price span of that, okay? Okay, what did I say here, when the span has to be removed, then first of all, brother, currently pan of rice, it has its own van, right, in the beginning, each price has its own span van, after that we check it in the beginning. So till the time it becomes empty give less or equal tu hai which is my current price so remember what I was saying that we will add to span = span = span = span plus the scan of the element which is in the top, right because right now the current The price which is there is either bigger than it or it is equal to it, right? We will add its span and then we will keep popping its status, it has been popped, okay, after that we will push the same in the last which is the current element and call it, just to understand. I was giving it, so let's run it and see, create is accepted, after submitting, I noticed that I had last solved this question in 2021 and I saw the then approach and I saw the current approach, there is a lot of difference in both. There is a difference and collect what I tried last time in 2021, so what I want to tell you is that if you keep practicing like this, then you will keep improving like this, your approaches, your way of writing code. The method of solving problems and becoming efficient will become smart and clean. Okay, I am also not a big quarterer. It's just that the more you practice, the better you will become. Okay, and look, I told you that this is a very similar question to Daily Temperature, right? Go and solve the late question yourself, it is very easy, isn't it? If you have become that, then this will also become okay, I hope you see you, next video thank you.
|
Online Stock Span
|
advantage-shuffle
|
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`.
| null |
Array,Greedy,Sorting
|
Medium
| null |
1,446 |
hey everybody this is larry this is day three of the november elite code daddy challenge hit the like button hit the subscribe button join me on discord make sure you go well if you're american and let's get i started on today's prom consecutive characters give the string s the power of the string is the max length of a non-empty substring that length of a non-empty substring that length of a non-empty substring that contains only one unique character we turn the power of the string uh okay that can so basically i mean this is a really way of phrasing just consecutive characters which is in the title already so this should be straight forward um i mean you just have some for loops i don't think there's anything tricky about it and then just keep track of consecutive characters right uh there are a couple of ways to do it uh i think you can you know like i said you could i'm gonna play around with a couple of ways i don't know if there's any uh tricky things i'm gonna go over uh you know it's an implementation problem right so i'm gonna go over some various ways of doing it just because i feel like it's fun uh maybe but uh but basically for example one way to do is just like you know let's just say your last character is equal to none right which is never going to be true so for x is in s first over each character in s if c is equal to last then count increment by one max is equal to max of count and max uh and then else last is equal to c and then count is equal to one right um also max is equal to and that's pretty much it really i mean i've just set some variables sure but right so that's pretty much it there are a couple of fun ways to doing it as well and that's part of the beauty of lead code is that you know you get all these testing for free um and i don't know if i recommend this uh on you know interviews per se but these are some other ways that i would write it just to uh like how i would write in a contest or something right because yeah this is going to be right i mean maybe i might find one but i think this is mostly right and you saw myself in like a minute um and then another way to do it is more of a competitive python trick which is to use zip so then you use you start with i so yeah for account as you go to see well so you keep the same but instead of looking at just the last countdown then keep on shifting it you use a zip of zip and sip of one thingy uh and then now you could look at consecutive characters so a and b say if a is not equal to b then count is equal to uh one and max i guess we could actually just do it this way x is equal to count else count increment by one and just to kind of kick it off you could set it to some uh number to prefix right uh so this way that the first character will always kick off so this is another way it also is right make sure just make sure that i press the button it seems like i did that because you know so yeah another so again i did it another minute uh so that's another way of doing it in one minute uh and then another way that i would maybe do it is just uh so this is kind of cool and it comes in maybe handy but another way of doing it is actually um using group by so you can actually just go straight by goodbye oops goodbye of s so for um i forget how the x thing goes m and uh g maybe i don't remember the good notation for it but basically this is the character that's matched and then this is the list of the characters technically you could be grouping by with a function so that's why they returned out of things but basically you just have a max zero max is equal to the max of the max or the list or the length of the list of g because g is an iterator so then now you could do that um hopefully that's right and yeah that looks good so that's the other way and of course if you really pay attention you can actually notice that you can actually reduce this to a one-liner so you can reduce this to a one-liner so you can reduce this to a one-liner so you can just do this uh sound effect for fun uh yeah so i solved it in like a couple of ways uh similar things i hope i don't mess up because that'll be funny if that i do all these ways and then it just happens to be wrong answer uh but yeah but most of the ways that i showed obviously does it in the near time and you should do in linear time otherwise it's a little bit too slow you know n is only 500 so you could do something n squared you really wanted to i don't even know how that would work but uh let me start the left and the right and see if everything in the between is the same but why would you need to um but yeah uh so let me know what you think let me know which way you did it i once again i know that i did really quickly but i think you should be able to figure out how to do in each way but this is why um sometimes i get asked questions you know larry you know in code fours or other competitive things like in top code i used to use in c sharp in code first i did do it in c plus uh why did i use the code in python uh or python and lead code well it's because i could do really short code like this and you know i could get in like 20 to 30 seconds or something like that and then you know move on to the next problem in competitive especially when i need code it's just really fast right like people solve it and feel yourself in thai contest in like 10 15 minutes so i don't have like a minute to type up just reading the input which i do on code for us and it's okay anyway that's all i have uh let me know what you think go out and vote hit the like button also vote for me i guess by hitting the like button and the subscribe button and i will see y'all tomorrow bye
|
Consecutive Characters
|
angle-between-hands-of-a-clock
|
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string `s`, return _the **power** of_ `s`.
**Example 1:**
**Input:** s = "leetcode "
**Output:** 2
**Explanation:** The substring "ee " is of length 2 with the character 'e' only.
**Example 2:**
**Input:** s = "abbcccddddeeeeedcba "
**Output:** 5
**Explanation:** The substring "eeeee " is of length 5 with the character 'e' only.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters.
|
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
|
Math
|
Medium
| null |
1,263 |
leet code problem memo moves to move a box is about pushing a box in a grid we're even the description of a grid with some cells being once forbidden and some are empty also there is some starting position of a player human that is in that grid box and the target location every move is pushing a box one cell to one four directions but a player must be next to a box if player is on the right from a box they can move it one cell to the left we need to find the minimum number of pushes it doesn't matter how much the human works for a grid if he is on the right from that box and wants to move all the way to the left of the box in order to push box to the right they can do it and we don't count those moves only pushes of the box count if we could move the box however we like to for directions without a human then this will be a standard BFS problem where you need to find the shortest path from one cell to the other and what you're given is a graph this grid can be represented as a graph and two neighboring cells or sons of that grid are vertices that are connected well if both those cells are empty allowed to move around then box can be moved to the neighboring salt and to the neighboring cell and so on till the target cell but we have a human this is additional twist in this problem let's analyze one of the given sample tests human is here there's bugs there's target location human can go up then push box to the left by one this is first move then again to the left by one this is second move then this drawing shows the current situation human can walk all the way to the bottom of a box and then push it up this is the third move so the answer in this case is free this is optimal number of moves the answer would also be free if we could just move a box to a neighboring cell as we can see in top left drawing it's just free but human must do some extra walking and we don't count it but it is important we're a human is and let's see an example here's a more complicated example we are given this grid every red cell is a wall we cannot water if we start here and the box is just on the left from us don't think we can do first is push it to the left even though box is just next to the target it would be nice to just make one push but it's impossible in that case we can push box to the left then unfortunately we need to keep pushing to the left we cannot we could also go here below the box but then we cannot push it up because there's a wall instead we need to keep pushing left then push left one more time the situation will be boxes here we are here then we can move all the way here and start pushing it to the right eventually box will be just below the target again but we are here we can go below the box and push it up instead of just one move one push the answer will be several here 1 2 3 4 and back I guess 8 plus the 9th move up BFS and the Dykstra are algorithms that are able to find a shortest path in the graph but this graph can have vertices that represent whatever we wish they represent for example in chess we can say that the whole situation the whole thing that happens on the board where every piece is one vertex of a graph and we have some starting vertex that is just arranging all the pieces in first two rounds and last two rows and every move will move you from one state to the other vertex doesn't have to be just a single position of a single item or fake there is some initial state in our grid problem let's say that box is at five toe and player is at six - from that we toe and player is at six - from that we toe and player is at six - from that we can move to several other states may be zero but if it's a neighboring cell then we can sometimes push and that would be of cost one because we want to minimize that number of pushes this is what is interesting for us and then we will have some state but also a player can move to a neighboring cell maybe we've cost zero we don't count those as a move because zero we can move maybe 2 5 2 & 7 2 maybe zero we can move maybe 2 5 2 & 7 2 maybe zero we can move maybe 2 5 2 & 7 2 maybe also 2 5 2 & 6 free this is other also 2 5 2 & 6 free this is other also 2 5 2 & 6 free this is other neighboring cell and some 4 possible move I think that every time we'll have at most 4 moves because a player can move in four directions maybe one of those moves will be a push to a box that one will have cost one so here we have cost 1 coz zero cost zero and I guessed cost zero and that's it we have some big graph the number of vertices in our graph is at most size of grid square because or we could also say that this is up to say that this is height then H times this is up to W times the number of possibilities for this number is H times W and this is the complexity then not complexity this is the number of vertices in our graphs every vertex S at most far outgoing edges so also this will be complexity for the number of edges and two if we can apply BFS maybe Dijkstra will be necessary but if we apply BFS then this is the final complexity of our solution standard BFS has a starting cell and a queue where we just push new vertices I has neighbors be that F then we take the next vertex on the in this queue B has neighbors new neighbors G and H then we consider that has a new number J and so on every time there are some already some vertices that are already in the queue and we process vertices in the order of adding them to the queue so now that will add a new vertex J then F will add C and this is it for this graph BFS assumes that every Edge has just cost one turns out that it's also possible to give cost 0 to some vertices but we should think about Q in slightly different way instead of just one Q I will say that there is a vertex at the distance 0 from the starting vertex I and it's a then a has some neighbors and those will be a distance 1 from the start be that F then B has some neighbors G and H so I will put them at distance 2 there is G and H then that will give me a new neighbor so vertex a distance 2 from the start this is J and so on and I will this way keep multiple queues and every time when I'm at some vertex that's a queue of number 2 I will push to the next one the queue number 3 the complexity doesn't change the number of those skills will be at most of n the number of vertices because this is limited for the distance from starting vertex to some new vertex and we can for example think about it as an array of n qs still every vertex will be considered by us at most once just once where we insert its neighbors to the next queue and that's it the complexity doesn't change the advantage of this implementation of BFS is that it can handle lengths of edges that are different than 1 for example 0 & 1 & 1 & 1 what is also possible is to have lengths bigger than 1 then complexity is increased the complexity will be off max distance so this can grow very big if lengths of edges are up to 1 billion but if lengths are up to say 5 this is still a better approach than Dijkstra here we have distances not this here we have lengths 0 & 1 so this maximum distance lengths 0 & 1 so this maximum distance lengths 0 & 1 so this maximum distance will still be just and but because we have also edges the complexities and plus M number of vertices plus number of edges how would our BFS work for lengths 0 & 1 we start with starting vertex a 0 & 1 we start with starting vertex a 0 & 1 we start with starting vertex a and consider all its neighbors B is that an F and every time when we have edge of length one we put that neighbor to the next queue because we have distance euro so that neighbor will have distance one I will put here B then I also put here that but F has length 0 from me so it has the same distance from the starting vertex I will put F here when I'm in this when I'm consider this vertex then I will consider vertex F just the next one in the same queue as I'm in right now and from F I see a neighbor C to that vertex I have length 1 so I will put it to the next Q B that C then I go one by one for vertices of the next Q and so on for B I see neighbors G and H in the graph Dre is has a new distance 2 from the start but H is at length 0 from me so the same distance from the start I will put it to the same Q so for B I had two neighbors H and G and one of them had length 0 from me so it's the same distance from the start and here distance 1 from me so distance me plus 1 from the start if from b2j from B to G there will be distance v then I would put it here Q that is my number plus 5 this graph doesn't have to be a tree it can have some extra edges so it's just any graph and then we need to be careful if we want to multiple times insert the same vertex in one of Q's so the thing just like with other implementations of BFS or DFS is to check if we are a distance X from the start and we have an edge of length L then we need to compare if this is smaller that the current distance of my neighbor if this is smaller then it means that my neighbor is in this queue right now of this number but I want to insert it to this one so I'm inserting to this one and later when I consider this queue where it's also inserted it would be a situation similar to the fact that maybe here we have h on the right but also we would have h here in the second queue when I consider H here for the first time I go for each day through its neighbors I don't want to repeat that so the next time when I see a vertex in some queue I check if I already processed this vertex if it's marked as processed which means I already went for its neighbors then I don't do it again because that would increase the complexity assuming that for every vertex only once I consider its neighbors the complexity is linear let's implement our algorithm I already created a variable for height and width of a grid and a function available that we will track if cell wrong call row and column it is inside the grid and not about this will mean a cell that is available that I can move to I need to find starting cell also starting sum of a box and then run BFS with multiple queues iterate cells of a great roll call if grid of roll call is character B then this is box start box will be roll call and if this is as I think as starting position of a player then start me is roll call and it won't hurt me to already remember position of target I will say if call is T then target is local maybe this could be implemented with some follow-up over implemented with some follow-up over implemented with some follow-up over free characters but I want to have meaningful names then this is fine maybe it isn't that but at least start knock start me and target each of those will be a pair of coordinates to simplify my code a little bit I will type uppercase P instead of pair int or int either this and now I will say that starting position vertex in our graph is I start is make part of start box and start me this will be coordinates of a box and of player that human in a grid either this or maybe even better is to create a struct for that P like position let's just use position where I have box and me what I could use is this array of vectors of size max dist where this is some limit form distance for the answer and we could try to figure this out maybe it will be H times W size of the initial grid maybe it will be this times two because maybe we go back and forth some sure limit is H times W times H times W because it is size of the new graph every vertex is pair of position of player and position of a box instead of that I will just use a vector of vectors and I will add a new cube if I need it well I use a vector instead of cube because I'm not really going to remove elements I don't need to you don't need to do it in BFS I find it easier to implement that with a vector initially the first q or vector will just have the starting position and then for distance up to Q size this will stop when we are out of this Q for every element of that vector of positions now I eater eight vertices in the graph that are at this distance from the starting vertex you of this dot size we have stayed cubed east of I if processed then continued and processed should be a set or hash set of positions in order to make this work I need to hear create unfortunately as separate say comparator it doesn't really matter much but it needs to be implemented in order to make this set work or if you want to use a heart set in C++ you need to here heart set in C++ you need to here heart set in C++ you need to here implement a hash operator of hash function so that some hash would be computed in Python it's easier because it just works by default a dictionary just works by default for tuples now iterate over for neighbors of myself because I can move there I will say what new row let's call it new row is state dot me dot first which is my Rho plus Delta Rho of deer new cow is state miss second plus Delta cow of deer and what is this Delta R and Delta call something that is plus and minus one that it will tell me what if I go in this direction should I increase my row number or not should I decrease my column number or not Delta Rho of 4 is minus 1 0 Delta call 4 is 0 minus 1 and 1 for example for deer equal to 1 what I will get is a pair minus 1 0 this is a vector by which I will move math vector by which I will move from sl55 I would move to 4 5 this is one of my four neighbors it's very convenient if you want to implement BFS or DFS in anger it if I created a function for that available of neuro and new cow then I cuz they're moving to dust State new state of state Dartford nut box comma a pair maybe I just created two new things new box position is state box possibly this will be pushed by one new me is just per neuro and new cone and if new me entered cell with a box this means I push the new box first plus equal Delta Rho of dear we move it if we moved like by one to the right then we want to move by additional one to the right new box second plus equal delta call of dear and if not available of new box first new box second maybe there is a welder or this is not agreed anymore and continue we computed new box position and new me position this is a new state new position if distance of new state is greater than distance of my previous state which is state plus length L then we do something we say list of new state update and I will create a variable for this to its list of state to plus L here it is this - this - is that distance to my this - this - is that distance to my this - this - is that distance to my current state plus length of edge I need to figure out this length of edge in a moment I will say that by default this is 0 but if this is the case l + + if is 0 but if this is the case l + + if is 0 but if this is the case l + + if I'm pushing a box this means I'm pushing a box and Q of this to push back new state what is dist I think that this is a map from position to distance and list of that initial start is zero what I was doing it here I'm pushing to Q of number dist - but maybe that one doesn't yet dist - but maybe that one doesn't yet dist - but maybe that one doesn't yet exist I will say maybe while this - exist I will say maybe while this - exist I will say maybe while this - greater equal Q dot size Q push back empty vector now by default I have a single queue with one vertex in it when I try to push something to kill number 5 then I want that cute oh it exists so I mean I might want to add a new empty queue and by Q I mean the vector because this is how I implement this thing and this happens before I push back otherwise I'll get runtime error because this doesn't yet exist this is a general way that works for any distances any lengths of edges not just 0 and 1 it's just that it would be slower if lengths were bigger if lengths are really big or weights of edges and then you should use Dijkstra here I wanted to avoid that extra longer it factor because I know length of address are up to one so total distance is up to number of vertices in a graph everything could be linear maybe in some case I want to finish the whole program and I will stay here if state dot box is equal target so if box go to the target location then I can just return distance I don't need to save it in some way because I know this is the first occurrence and BFS considers vertices in increasing distance order so I just returned the current distance if this far loop gets done I return minus one let's now resolve any compilation errors first and then logical errors semicolon after struct definition I called this start box and start me not box and me run code again line 67 list of state I reused a variable name my map will be called map dist because or maybe better here this is current distance which is an int and here I have a map distance this current deist will just be here and in return I can also say assert just to make sure that my cut is reasonable distance of state should be current distance just to track if I'm updating everything correctly and that me reminds me of here I compare two things but by default if new state doesn't exist and this will be zero so I will say if this count new state is zero or that this checks if maybe new state doesn't exist in the map also what worked for a set my previous count wouldn't work and we got wrong answer output minus one expected free what can I do I can at least print which positions I do consider and I will here say maybe how do I insert to processed by the way processed no I do not I should multiple mistakes but this doesn't explain minus one it would I think just worse than the time we will here say print state box first State box second this will allow me to understand if I consider more than one cell at all for this sample test I'm confused now should I say anything printed or maybe I didn't even once got to this part maybe okay so I'm not maybe I should print with she out a CR b see our should be better because in some problems we printed the answer and then see our doesn't collide with that printed answer ok CD out I see but not City they are kind and I should change see our to see out my but I didn't I don't know a little to that well I'm considering sales positions two three four and then two three something is clearly all around because instead of moving to a neighboring cell I moved it looks like a player moved immediately to a salvage box it shouldn't be that way what I'm pushing here new state what is new state box and new box this obviously is incorrect it should be new box come new me I'm happy that I got some mistakes by the way it's also a part of learning for you that you can see how I approach mistakes I printed something now I understood that how that second line is clearly lorrog and possibly I can't create a new state correct works for the first sample test this doesn't mean that much but let's submit maybe I will need to remove this see out because it might slow the program down I'm going to exceed it yeah let's try that it is possible that my debug because it uses a nd L that flashes the output that is very slow that it slowed the whole program down that everything else is faster and indeed this is accepted I got accepted but not really with a great time I'm faster than 5% of C++ time I'm faster than 5% of C++ time I'm faster than 5% of C++ submissions and that's bad but I think the complexity is enough and I know how to solve this problem in a faster way that wouldn't create so many states and that is to describe a state as position of a box and where a player is right up left or down from a box just to consider those states where we are just next to a box and then from that either push a box or run a separate internal BFS to check if I can move from right from a box to up a box but again we have H times W States and each of them we run BFS so the complexity is the same is HW square size of grid square maybe in practice faster because we don't create that many vertices memory will be better for sure there is here some memory usage less than 200% of C++ submissions I less than 200% of C++ submissions I less than 200% of C++ submissions I doubt that this is correct but you should focus usually on complexity don't I said that many times don't worry too much about those statistics Inlet code I think they reward squeezing your solution and using something slightly different because then your time will be x 2 or half of that well it isn't really a better solution that is cipher it's easier to implement and it has better complexity so don't worry too much about that at least I don't do it and in a real coding interview your interviewer also will not care that much because you likely implement something on the whiteboard I hope you enjoyed this harder problem today and feel free to give me some suggestions of other little code problems to solve on this channel bye
|
Minimum Moves to Move a Box to Their Target Location
|
number-of-dice-rolls-with-target-sum
|
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an `m x n` grid of characters `grid` where each element is a wall, floor, or box.
Your task is to move the box `'B'` to the target position `'T'` under the following rules:
* The character `'S'` represents the player. The player can move up, down, left, right in `grid` if it is a floor (empty cell).
* The character `'.'` represents the floor which means a free cell to walk.
* The character `'#'` represents the wall which means an obstacle (impossible to walk there).
* There is only one box `'B'` and one target cell `'T'` in the `grid`.
* The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a **push**.
* The player cannot walk through the box.
Return _the minimum number of **pushes** to move the box to the target_. If there is no way to reach the target, return `-1`.
**Example 1:**
**Input:** grid = \[\[ "# ", "# ", "# ", "# ", "# ", "# "\],
\[ "# ", "T ", "# ", "# ", "# ", "# "\],
\[ "# ", ". ", ". ", "B ", ". ", "# "\],
\[ "# ", ". ", "# ", "# ", ". ", "# "\],
\[ "# ", ". ", ". ", ". ", "S ", "# "\],
\[ "# ", "# ", "# ", "# ", "# ", "# "\]\]
**Output:** 3
**Explanation:** We return only the number of times the box is pushed.
**Example 2:**
**Input:** grid = \[\[ "# ", "# ", "# ", "# ", "# ", "# "\],
\[ "# ", "T ", "# ", "# ", "# ", "# "\],
\[ "# ", ". ", ". ", "B ", ". ", "# "\],
\[ "# ", "# ", "# ", "# ", ". ", "# "\],
\[ "# ", ". ", ". ", ". ", "S ", "# "\],
\[ "# ", "# ", "# ", "# ", "# ", "# "\]\]
**Output:** -1
**Example 3:**
**Input:** grid = \[\[ "# ", "# ", "# ", "# ", "# ", "# "\],
\[ "# ", "T ", ". ", ". ", "# ", "# "\],
\[ "# ", ". ", "# ", "B ", ". ", "# "\],
\[ "# ", ". ", ". ", ". ", ". ", "# "\],
\[ "# ", ". ", ". ", ". ", "S ", "# "\],
\[ "# ", "# ", "# ", "# ", "# ", "# "\]\]
**Output:** 5
**Explanation:** push the box down, left, left, up and up.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 20`
* `grid` contains only characters `'.'`, `'#'`, `'S'`, `'T'`, or `'B'`.
* There is only one character `'S'`, `'B'`, and `'T'` in the `grid`.
|
Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far.
|
Dynamic Programming
|
Medium
|
1901,2155
|
1,489 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem find critical and pseudo-critical edges in a minimum and pseudo-critical edges in a minimum and pseudo-critical edges in a minimum spanning tree this problem is definitely a hard one and that's because it involves quite a few algorithms but it also requires being a little bit clever so we're given a weighted undirected graph with n vertices and it's important to note that this graph is connected so that pretty much guarantees that we will be able to find some spanning tree therefore we'll be able to find some minimum spanning tree so that's pretty much guaranteed and of course every Edge is going to have two nodes that are connecting the edge but also it's going to have a weight that's kind of the whole point behind a minimum spanning tree because in case you don't remember an MST is basically a subset of edges in this graph which connects all of the nodes together so for example one spanning tree could look like this where you can see all of the node are connected now we have five nodes how many edges did it take to connect all of them it took exactly four and that's always going to be the case if we have n nodes it's going to take n minus 1 edges to connect all of them and of course a minimum spanning tree is the spanning tree such that the sum of the weights of all of these edges is minimized so believe it or not that's actually the easy part there are a couple algorithms that can help you find a minimum spanning tree one's called prims it's similar to dixtra's algorithm and another one is kruskull's algorithm this algorithm intuitively is a lot more simple so this is the one I'm going to be using in this problem but it's not as easy as just applying this algorithm to this problem if it was this would probably be a medium problem but this is a hard problem for a reason and by the way if you're not familiar with these algorithms I definitely have some videos on them you can also check out my Advanced algorithms course where I cover these in depth but we'll kind of review crescold's algorithm in this video but I will mention that kresco's algorithm also requires Union find which is why it's kind of a pain to code up but conceptually kruskulls is pretty easy it's a greedy algorithm we'll be talking about it in a bit but first let's finish reading this problem our goal is not just to find a minimum spanning tree but our goal is to find all of the critical edges of the spanning tree what is a critical Edge well in this case it's defined as being an edge such that if we removed this Edge like we're not allowed to use this Edge in our MST then we try to find an MST without that edge and what we find is our new MST has a weight that is actually greater than the original weight of the MS T and just to make it a bit more concrete let me just give you an example let's say this is our graph we have three nodes one two three we have three edges this one has a weight of one this has a weight of three this has a weight of four so what's the minimum spanning tree well it's probably these two edges and how we would know that is using kruskull's algorithm we would take all of these edges put them in a list sort them by the weight of each Edge in ascending order because we want to be greedy we want to choose the edge with the smallest weight first so we would first pick this Edge and what we would find is by adding this Edge we are introducing two nodes to our current tree and now we would add another Edge and we among these two which one do you think we should pick well crust goals is going to tell us to pick the one with the smaller weight and again we find that we're introducing a new node to our tree now if hypothetically there are going to be cases where we have an edge but it actually does not introduce a new node and those edges we would skip that's not really the case in this simplified example but it could be the case and that's why I would recommend really understanding kruskel's algorithm before getting into this problem but so far we found this is our minimum spanning tree now if we try to add this Edge even though we have three nodes and we have two edges at that point we pretty much know that we're done finding our minimum spanning tree but hypothetically if we try to add this Edge what we find is that it doesn't introduce any new nodes to our tree like we already have these two nodes as a part of the connected component that forms our minimum spanning tree so we found that these two edges add up to a weight of four that's the weight of the minimum spanning tree of this graph now what if I took this Edge and told you're not allowed to use it I removed this Edge well then the new minimum spanning tree is going to look like this and the weight of it is going to be seven so that is what makes this Edge a critical Edge because now we can't create the same minimum spanning tree with the same original weight so algorithmically how can we find if an edge is critical well it's actually pretty simple with kruskal's algorithm and it pretty much is The Brute Force way so actually there's not a lot of cleverness involved in finding the critical edges what we're going to do is basically run kruskel's algorithm once on this graph just like I did we're going to find the weight of the minimum spanning tree is four okay then we're gonna try one by one let's try finding the MST without this Edge and in this case we got a weight of seven therefore we know this is critical okay now let's try finding the MST without this Edge and once again we're going to have a minimum spanning tree that looks like this now and the weight is going to be five so once again it's greater than the original MST weight of four so once again this Edge is critical so we found two critical edges so far now let's try it with this one well now we can still form the original MST so therefore this Edge actually is not critical so it's pretty easy to find the critical edges but what about the pseudo critical edges well let's first read the definition for these an edge is pseudo-critical if it these an edge is pseudo-critical if it these an edge is pseudo-critical if it appears in some minimum spanning trees but not all of them so kind of by definition if an edge is critical there's no way it's going to be pseudo critical right because a critical Edge has to appear in all of the minimum spanning trees because as we know a graph can have multiple minimum spanning trees not in this example actually but let me kind of make another really simplified example like this one let's suppose that all of the edges have a weight of two then well this is kind of a minimum spanning tree this is one valid minimum spanning tree and also this is a minimum spanning tree as well there's potentially many minimum spanning trees for a single graph now in this example that's not the case but it definitely could be the case in other graphs so that's just to help you understand the definition of a pseudo-critical edge it could appear in pseudo-critical edge it could appear in pseudo-critical edge it could appear in some minimum spanning trees but not all of them a naive way to find pseudo-critical edges would be well just pseudo-critical edges would be well just pseudo-critical edges would be well just take all of the edges all of them and then remove the critical edges isn't it just that easy can't we just take every non-critical Edge and then say it's non-critical Edge and then say it's non-critical Edge and then say it's pseudo-critical unfortunately we can't pseudo-critical unfortunately we can't pseudo-critical unfortunately we can't do it's not that simple because it's actually possible that some nodes are or some edges like this one actually never appear in any of the minimum spanning trees because in this case there's only one valid minimum spanning tree and that's this one this guy never appears in the minimum spanning tree therefore this is not a critical Edge and it's also not a pseudo-critical edge so then also not a pseudo-critical edge so then also not a pseudo-critical edge so then how do we find the pseudo critical edges well like I said we know that our critical Edge can never be a pseudo-critical edge so as We're looping pseudo-critical edge so as We're looping pseudo-critical edge so as We're looping and as we're checking is this Edge critical if we find that yes it is critical then we continue but if we found that this Edge is not critical then we would want to test well is this node pseudo-critical well how can we node pseudo-critical well how can we node pseudo-critical well how can we test that how do we know if this is a pseudo-critical edge once we've pseudo-critical edge once we've pseudo-critical edge once we've confirmed it's not a critical Edge well it would be by taking this Edge and including it in the tree we're definitely including this Edge we're forcing ourselves to include this Edge and now we're checking is it possible for us to find a minimum spanning tree with the same weight as the original again this example is not the best for this one because we know that this was a critical Edge but that's the idea if we find that by forcibly including an edge we can create a minimum spanning tree that must mean that edge was pseudo-critical so that's kind of the pseudo-critical so that's kind of the pseudo-critical so that's kind of the intuition behind this problem I could spend all day dry running it but I'd rather just code it up because it'll probably make a lot more sense and we'll also touch on the time complexity that n as well so now let's code it up and the way this problem is written we're returning a list of the critical edges and pseudo-critical edges but the way and pseudo-critical edges but the way and pseudo-critical edges but the way we're defining those is by using the original index of each Edge so even though we're going to be sorting the edges for kruskull's algorithm we also want to preserve the original index so the easiest way to do that in my opinion is just to iterate over each Edge and in Python you can do that with enumerate so enumerating the edges we get the index but also the edge at the same time and the reason that's helpful is because for each Edge Let's just append the index to it because we know that originally each Edge was the vertex one that's what I mean by V1 and vertex 2 or node two and after that it was the weight so the edge is connecting these two vertices and it has a weight of this and now we're adding the original index to that as well and we're doing that because now we're going to take the edges and we're going to sort them but which of these four keys are we going to use to sort well in Python we can specify the key and I'm going to pass in an inline function AKA a Lambda function which is going to take a parameter I'm going to call it X I could call it v i could call it e let's just call it e because it's more descriptive so for each Edge we're sorting it by the weight so when we take the index we're going to take the value at index 2. and this uh I is actually the original index so let's keep track of that so now's the part where we want to find that minimum spanning tree so that we can get the minimum spanning tree weight but to do that we need Union find as I mentioned earlier now for me it's pretty easy to implement Union find I can do it in like three minutes probably just because I've done it so many times I don't even think about it I just kind of do it based off of memory but if you're new to Union find I definitely have some videos on it and it's also a part of the advanced algorithms course on neetcode.io Union algorithms course on neetcode.io Union algorithms course on neetcode.io Union find will allow us to determine if two nodes are a part of the same connected component and in our Constructor we're going to pass the number of components we have n aka the number of nodes and for each node we want to keep track of its parent originally we'll say the parent for each node is just going to be itself so I'm going to say for I in range n this is list comprehension in Python we're basically creating an array from 0 to n minus 1 and also for each node we want the rank of it aka the size and initially we'll say that is going to be one for each of them so 1 times n here is going to create an array of size n filled with ones and there's two main methods you want in your union fine and that is fined and the other one is called Union so find is going to be given a node or a Vertex so V1 in this case and it's going to find the parent or the root parent of V1 and I'm I do that usually with a loop a lot of people do it recursively it doesn't really make a huge difference I think but while V1 is not equal to the parent of V1 because we know that a root is going to have no parent or the parent is going to be itself that's kind of how we initialize the parents but if that's not the case then we continue traversing up the parent chain and we could just say V1 is going to be equal to its parent but there's another small little optimization you can make with Union fine it's called path compression where we basically take the parent of the current vertex and set it equal to its parent so this probably is isn't necessary to pass this problem but it's a small little optimization you can make and once we do reach the root parent we can just return that and that will be stored in V1 now second is Union where we take two vertexes V1 and V2 and we try to combine them into a single connected component in Union find we do that by getting the root parent of each vertex because that will allow us to know if they're already a part of the same connected component so we take we call find on each of these and find their root parents now if their root parents are equal that means they're already a part of the same connected component so what we're going to do is return false because we want to know whether this Union was successful or not that's going to be important for us later on but if that's not the case we're going to end up returning true but before we return true let's check which one has a larger rank because an optimization you can make in Union is Union by rank we want to take the one that has a larger rank so we can figure that out like this so if P1 has a larger rank then we take P2 and set it as the child of P1 AKA we take P2 and say its parent is going to be equal to P1 and then we also update the rank so in this case since P1 became the parent it's still the root and then we can take its Rank and add the rank of P2 to this one I know this is kind of confusing if you don't know anything about Union fine it's not something you're just going to come up with and it's definitely something I would recommend understanding before you try to tackle this problem I have a lot of resources on this now if the opposite is the case maybe this one had a larger rank we're just going to add an else here and this is the part where I just turned my brain off I just copy and paste this and just swap the variables around whoops and then take this is P1 this is going to be P2 and this is going to be P1 okay cool we have our Union find done I'm not really going to be talking much about this anymore but one thing I'll quickly say is how would we know if we took all of these vertices or nodes and connected them into a single connected component well the easiest way to know would be if one of the ranks of these like one of these ranks is equal to n because that means one of the components has all of the nodes a part of it and we're actually going to be using that fact later on down here because that's how we're kind of going to know if we found a minimum spanning tree or not at least for one of the cases for the basic case here now we can actually construct a union fine component I'm going to call the union fine Constructor passing an N because that's how many nodes we have and now I'm going to just start iterating through our edges that we sorted up above so we're going to unpack the vertices and the weight and the index by iterating over the edges like this and we're gonna call Union on these two vertices V1 and V2 and if this returns true that means the union was successful and in that case we can take our minimum spanning tree weight and increment it by AI the weight of this Edge that we whoops that we are currently iterating through right now so by the end of this Loop you might be thinking how do we know for sure that we actually formed a minimum spanning tree like I mentioned how do we know that all of the nodes are now a part of a single component well first of all we know for sure that the given graph is a connected graph so by the time we reach the end of this we know for sure the graph is going to be connected and we also know it's going to be a minimum spanning tree because our Union operation is not going to execute every single time if we have two vertices that are already a part of the same component this is just not going to execute therefore it's not going to return true is what I meant to say and therefore the weight is not going to be updated it's not going to be incremented so that's why we don't have to do any special check here by the time this is done this will be the a minimum spanning tree wait this is the true minimum spanning tree right now our job is to find the critical and pseudo-critical edges and we're going to pseudo-critical edges and we're going to pseudo-critical edges and we're going to store those in two lists and this is the part where I'm kind of just gonna Brute Force this I'm gonna go through every single edge and I'm gonna do that with uh unpacking just like we kind of did up above N1 and two that's going to be vertices one vertices two pretty much and the edge weight and the index in edges and the reason I'm getting this index from the edges and I'm not just saying for I in range like length of edges because that would not give us the original index remember we did that work up above for a reason we wanted to preserve the original index because we need that when we're building the output when we're building these two lists what we're going to add to them is the original index of each Edge so that's very important I actually didn't do that when I first solved this problem and I was wondering where did I go wrong but now we're going to do two things we're gonna try to find the minimum spanning tree without the current Edge just like I mentioned earlier because if we can't create the minimum spanning tree without this Edge that means this Edge is a critical Edge so let's do that and we're actually going to do something very similar to what we did up here so I'm literally going to copy and paste this code and before I copy and paste it I'm going to say the way currently of the MST that we're trying to build I'm going to create the same Union find with the same name you can do that in Python because now I'm constructing a new object because we're never going to need this one ever again but if I wanted to I could rename this to something else it's not a huge deal but as we iterate through each Edge we want to skip the current Edge how do we do that here well the easiest way is just to say if I which is the index of the current Edge is not equal to the index of the edge that we're iterating through right now which is also I that's a problem I'm actually going to change it to J so here we're checking if I is not equal to J and the union find operation is successful then update the weight not the MST weight just the weight that we declared up here okay we're getting close to the end of the problem so just bear with me I know this is definitely a long one that's why it's a hard but now we want to know did we form an MST or not one thing to check would be is the weight greater than the MST weight because if this is the case that means this Edge was critical that means without this Edge we were not able to get the original MST weight and if that's the case what we're going to do is to our critical edges we're going to append the index I of this Edge but this is actually not enough perhaps without this Edge we weren't able to actually create a tree like at all maybe we were just not able to connect all of the nodes how would we know that's the case well we would check in our Union find dot rank array what is the max value in the rank array it should be equal to n but if it's not equal to n and it's probably less than n then we did not find rmst so if either of these two is true either we don't have enough nodes to create like a connected graph or our weight was too large then we did not find the MST therefore this Edge is a critical one and we're gonna add it here now I'm also going to add a continue statement if that was the case because we don't want to execute this part if we found a critical Edge because now we're going to try with the current Edge we're forcing the current Edge in the MST in our like connected component and we're doing that the reason we have a continue here is because remember a critical Edge is definitely not going to be a pseudo-critical edge but here we're be a pseudo-critical edge but here we're be a pseudo-critical edge but here we're going to do pretty much the same thing up above if here we create an MST that has the same weight as the original MST that means this Edge is a pseudo-critical edge because it's a part pseudo-critical edge because it's a part pseudo-critical edge because it's a part of some msts but it's not a part of every MST like the critical Edge so here we're going to be forcing this node in so first I'm going to create a union find component a union fine instance just like this us I'm going to set the weight here actually equal to this way e weight because we're forcibly including this Edge so we can initialize the weight as the same thing and we should probably also call Union fine dot Union on these two vertices because we're forcing them into our minimum spanning tree now I'm actually just going to copy and paste this up above as well because we're going to be iterating through all the edges we don't need this part of the code actually because if we tried to take this Union and call it again here it just wouldn't execute it would just return false remember because if we try to add two nodes that are already a part of the same connected component it's going to return false therefore this wouldn't execute so we don't even need to check the indexes like that now by the end of this unioning part like at the end of this cross school's algorithm how do we know if our minimum spanning tree has the same weight as the original minimum spinning tree well that's pretty easy to check if we just check if weight is equal to MST weight then we can take sudo and append to it index I you might think shouldn't we also check that the rank is the same you might think shouldn't we also check that we were able to create a connected component well we know for sure we're able to create a minimum spanning tree like that's guaranteed and down here we actually didn't have any restrictions all we said was we're forcibly including this Edge it's not like we're not allowed to include any of the other edges therefore we're guaranteed to be able to form a minimum spanning tree the only thing we need to check is does the weight match the original and if it does then we append like this now after every thing is said and done what we actually return out here is going to be an array with two sub arrays the critical edges and the pseudo-critical edges so that's and the pseudo-critical edges so that's and the pseudo-critical edges so that's the entire code it's definitely quite a lot of code and it doesn't even fit on one screen but now let me run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatco.io thanks for watching and out neatco.io thanks for watching and out neatco.io thanks for watching and I'll see you soon
|
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
|
pizza-with-3n-slices
|
Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**.
|
By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it.
|
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
|
Hard
| null |
458 |
hi guys welcome to our new video where we will be discussing about one of the problem from leap code and the problem statements name is poor pegs the difficulty level for this question is hard now let's first understand the question and the problem constraints given to us then we'll try to develop an intuition and slowly and gradually reach to a point that gives us the best optimized solution for this now the problem statement over here states that you have been given a fixed number of buckets and there is exactly one bucket which contains poison so there is only one bucket which will contain poison in it now to figure out which one is poisonous you have to feed it to some pigs because you cannot do a human testing definitely for a poison dead so uh yeah so we'll choose pigs to feed this liquid too and we can figure out which pig dies and according to which we will understand which bucket has the poison in it now to feed pigs we have few conditions or we have few steps how to feed pigs so you can choose any number of pigs okay now for each pig that you choose to feed it can consume any number of buckets at a single point in time so that means you can ask a pig to consume even 100 bucket of liquid and it will take no time so let's uh ignore the point that it will take some time to consume the liquid as well so you can also ask the pigs to consume more than one bucket of liquid now you have to wait for certain minutes for that poison to start showing its reaction now you have total in all a fixed amount of time to test all the buckets that are available to you cannot keep testing it with one pig or let's say very less number of pigs and do it for a long duration but you have been given a set time in which you have to finish the testing and come up with the result and the poison takes a certain amount to show its response that is that means that the pig will die in certain amount of time so you have to figure out now you have to figure out that what is the number of minimum number of pigs that are required to find the bucket that is poisonous okay now when you have uh when you ask a pig to consume a liquid you cannot ask another pig to consume a bucket you have to wait for some time for that particular minimum time to die so that at least you know that if this bucket was poisonous or not okay so that's the whole question now the constraint that have been given to you is stating that the number of buckets can vary from one to thousand you can have maximum thousand buckets from uh one so minimum is one maximum is thousand and the time to die would be lesser than the time to test definitely because if let's say you have 10 minutes of the time to die that means 10 minutes it will take to show the reaction and you can only give the result you have only five minutes to test this theory you cannot do it because at least for one pick to consume and uh show result it will take minimum of 10 minutes so that's why the time to die will be always less than the time to test and that can be ranging from 1 to 100 now this is the question now the first solution that comes to my mind is let's say i have uh 60 minutes to test and the poison takes 10 minutes to show its reaction that means i can do six tests in the given time i can just do six tests and if i want to test one thousand bucket that means six divided by one thousand is the number of peaks that are required but that is a huge number of peaks that you would require right and if it is a live scenario it will cost you something right and it would be a huge risk to gather all those pigs and do the testing so you want to minimize the number of pigs and come up with an approach where you have let's say one two three or let's say less than ten pigs for testing let's say thousand buckets so how can you come up with that approach now let's first understand the brute force approach that we just discussed and then slowly gradually come up with the intuition and start understanding how we can reduce the number of pigs that would be used in the testing so let's discuss the brute force approach we have been given three parameters as input first one is number of buckets second is the minutes to die and the third one is minutes to test now let's shorten the names first uh i'll refer the number of buckets as b the minutes to die as die and the minutes to test as test just for simplicity and easier for the writing purposes so the first intuition that clicks my mind is let's find out how many tests i can do in uh the time to test so how many tests i can perform so the number of tests that i can perform in the given time limit is uh sorry this would be test divided by die so let's say uh for example right now we have been given five buckets and the time to die is 15 minutes and the time to test is 60. so this means i can do four tests in the given time frame so but my bucket is more than four that means this will give me an intuition that let's get two picks so the first pick will uh let's say i have four tests so i have these four tests uh over here and the fifth bucket over here so i'll ask the first pick to stand in line one second pick to stand in line two and the first picks drinks this bucket second pigs pig would drink this bucket and we'll wait for 15 minutes if nothing happens the first pig will move to this bucket and for 15 minutes we'll wait then again to third bucket and then to fourth bucket but we can also do one thing let's reduce one pick and take that fifth bucket in the same line so what happens if i have this fifth bucket in the same line so let's say this one pig has drank this liquid and for 15 min nothing happens to him so nothing happened over here he come up to the second bucket drinks the second bucket nothing happens to him okay he comes to the third bucket nothing happens to him for the 15 minutes now i have already taken 45 minutes of my given time from 65 60 minutes now the sheep or the pig comes to the fourth bucket and nothing happens for next 15 minutes that means 60 minutes have passed that means that the fifth bucket because we have exactly one bucket that is poisonous so if all these four bucket did not do anything to the pig that means the fifth bucket is the bucket that contains the poison and my task was not to uh kill the pig my task was to find out if which bucket contains the poison so now i surely know my fifth bucket would contain poison so we reduced uh from two to one pig now what happens if my number of bucket increases to 15. now i can do a five test per pig that means so for uh if i take one pig can perform five tests right in that 60 minutes of duration so that means i will require how many peaks three peaks because for 15 buckets i need uh at least three lines of these and that's why i would need three picks for that but do you really need three picks can we reduce the number of pigs to uh at least two let's say is it possible let's think it through so let's say if i ask this first pig to drink all the five buckets at once and if i wait for 15 minutes and this pig does not die that means that clearly states that my first row does not contain the poisonous bucket now i'll ask this peak to again move to the row 2 and it will drink all the liquid from the second row if the pig dies that means i am very sure that the poisonous liquid lies in this second row either of these five buckets right now i at least have figured out from the 15 buckets i have a limited range of five buckets i and now i can ask my second pig so this is my pig one okay now i can ask my second pick to start drinking water from this column so from this column at least i am sure that this bucket will do nothing to no harm this will do no harm because my second row contains the poisonous bucket so even if the pig drinks these this these two buckets or not that will not have any impact and the time is also zero because time to consume the liquid is also zero so there is no harm for the pig to consume the complete row so now i'll wait for 15 minutes now if i wait for 15 minutes that means and if the pig does not die that means the poison was not there in the first bucket of the second row even now if i ask the same pig the second pick to drink all the liquid from this second row and wait for 15 minutes nothing happens so that means i my second bucket from the second row also does not contain and simultaneously will keep moving and even if till this fourth bucket the pig does not die the second peak does not die that means definitely this is my poisonous liquid because i know that the first pig died drinking the water from the second row so and my second picked it did not die drinking the water till the fourth column that means the fifth column of the second row contains the poisonous liquid so now from three picks i have reduced to two pigs now let's increase the number of bucket now let's increase the number of buckets from 15 to 20 now why i am moving in the fashion of five only because we can perform five tests per cycle right because this division was resulting in four that means five tests can be done so that's why i'm moving ahead with multiple of five but you can also take this as 19 or 16 anything after 15 so that won't uh impact the logic so now let's take another row so this is my fourth row which contains again five buckets now again with the sheep one i would ask to drink from the first row wait for 15 minutes and simultaneously my second sheep is also drinking from the columns so the sheep second is has drank the column one uh at the same time and we are waiting for 15 minutes and we are just uh hoping that they either die or they don't die if they die we will be sure that uh this is my poisonous liquid but if they don't die we'll continue our test for another set so let's say uh i had 20 buckets and uh the sheep one died drinking the water from the row three so that means my poison is in row three and the second sheep dies drinking the water from the column 3 so that means this is my poisonous liquid so we need only two sheeps even if we have 20 buckets now even if i have 25 buckets i'll require again same number of sheeps so if my bucket is less than 25 i would and greater than 5 i would require only two sheeps but if it was less than five definitely one ship was required to test five buckets now this is the intuition that i was talking about now what intuition i have got is that i have a test set of time to test divide by time to die this whole plus one this would be my test set and the powers of this test set is the number of sheeps that would be a number of pigs that would be required over here we had this as 5 right so if the number was in a range of 5 to the power 2. that means we need two sheeps if the number of buckets is in the range of 5 to the power 1 that means we didn't require one sheep so that means any number of bucket ranging from uh sorry ranging from one to five we require only one chip if the bucket ranges from 6 to 25 anything from 6 to 25 we need two sheeps if my number of bucket ranges from 26 to 125 i would require three sheeps how we come up with this that we require only three sheeps for now so what i would say is let's arrange this 125 let's say you have 120 or 125 let's take the upper limit let's arrange these 125 buckets in three dimension so this is my three dimension so i will have five as the length so five buckets in the length five buckets in the height and five buckets in the depth so on x axis i have five buckets on y axis i have five buckets and on z axis again i have five buckets so i've arranged the liquid uh buckets in the three-dimensional the three-dimensional the three-dimensional space and each sheep is responsible to figure out uh the row or uh or yeah actually the row which is culprit for it dying right so if it is three dimension if sheep one fine let us find the row on the y-axis row on the y-axis row on the y-axis which row would kill the sheep we know at least on which y-axis and correspondingly sheep 2 will y-axis and correspondingly sheep 2 will y-axis and correspondingly sheep 2 will figure out which column on the x-axis column on the x-axis column on the x-axis kills it and uh the third one is pig which the third pig would help us finding out the z so it would give us a coordinate of x y and z so that's why we need three picks to figure out the poisonous bucket for range of 26 to 125 now for 126 to 625 we only require four sheeps that means this is again going to fourth dimension so we would arrange this buckets in four dimension let's say so this is the intuition and this is the code so this is the basic logic so what we say is we have to figure out the uh power of 5 which is just less than number of buckets so let's say you have 1000 buckets so for 1000 buckets how many sheeps do you how many pigs do you require so for 1000 it would be just five pigs that you would be require required because the range would come up with this 626 up to 3000 something so it would be 3000 so it is less than 3000 is less than uh thousand oh sorry 3000 is greater than thousand but greater than 626 that means we require five sheeps for this so that's the solution that's the algorithm that we have introduced and that's the complete algorithm behind this problem now let's see this uh algorithm in uh the code and let's try to understand and debug this algorithm in code so if you like the explanation till now please do not forget to like share and subscribe to our youtube channel and also comment down below on any questions that you want us to solve for you guys now this is the code that i have written in golan but if you understand the logic well you can write this code in any language of your choice whether java javascript any language java javascript any language java javascript any language that you like so this is totally language independent but i have written it in go because that's my favorite language of choice so now let's understand the algorithm with which we just discussed so over here i am trying to find the number of our tests that can be performed in one cycle so this would be minutes to test divide by minutes to die plus one so if you remember it was 16 60 minutes i had and uh 15 minutes was time to die that was giving us 4 so 4 plus 1 was my number of tests that i can perform in the given time frame so that is the number of tests that i can perform now let's say i have 0 peaks initially now i'll keep finding a power of this t and that power is the number of peaks so i'll keep increasing the number of peak and i'll see if that power is less than the number of buckets if that's less than number of buckets my answer is done for example i have let's say 1000 pigs uh sorry 1000 buckets and for 1000 buckets i have uh i have to uh i have like time to die is 15 minutes and 60 is the total time to test now this i want to figure out a power of 5 which is less than 1000 so power of 5 power 1 is 5 power 2 is 25 similarly 5 power 3 is 125 5 power 4 is 620 5 and if i increment it plus 1 that is 5 power 5 that will be around let's say 3 000 something uh let's not get into the exact value but that's definitely greater than 1000 right so at this point in time my condition will fail right that means my number of pig big count has gone to five and this condition went to false that's when the for condition breaks so this is the number of pigs now this could have been solved with a log also so we could have found the log of the number of bucket to the base uh to base five definitely and this would have resulted in four point something and we would have used math dot seal function to push it to the upper part so that means push it to five so that could have solved in uh practically order of one and but this is the basic algorithm which we just discussed and you can further optimize it by using the logarithmic functions that is up to you but i just wrote the algorithm as code so that it is easier for you guys to understand so over here you see math dot power uh 5 to the power 0 then 1 then 2 and i keep doing it so this is how i found it uh and this is how the solution is finding this number of pigs so that's it for this video today and in case you liked the video and it was helpful for you please do not forget to like share and subscribe to our youtube channel also comment down below in case you want any particular question from lead code or geeks for geeks to be solved by us on golan or any other topics that you want us to cover for you guys using golan so go ahead and comment down below as much as you want any topic on go land using golan we appreciate you guys to do that
|
Poor Pigs
|
poor-pigs
|
There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
1. Choose some live pigs to feed.
2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time.
4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
5. Repeat this process until you run out of time.
Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time_.
**Example 1:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 15
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
At time 15, there are 4 possible outcomes:
- If only the first pig dies, then bucket 1 must be poisonous.
- If only the second pig dies, then bucket 3 must be poisonous.
- If both pigs die, then bucket 2 must be poisonous.
- If neither pig dies, then bucket 4 must be poisonous.
**Example 2:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 30
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
At time 15, there are 2 possible outcomes:
- If either pig dies, then the poisonous bucket is the one it was fed.
- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
**Constraints:**
* `1 <= buckets <= 1000`
* `1 <= minutesToDie <= minutesToTest <= 100`
|
What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test. How many states can we generate with x pigs and T tests? Find minimum x such that (T+1)^x >= N
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
20 |
hi everybody i hope you all are doing really well thank you so much for dropping by my channel today if you directly want to dive into today's topic i will leave the time stamp somewhere on the screen here but if you want to know a little bit about me my name is pratik shabacrola i am a software engineer and have been working in the it industry for more than 10 years and my intention with this channel is to share what i know and hopefully it helps somebody with that being said um i am new to this whole youtube thing talking to the camera filming editing um lighting all of these things are new so if you have any suggestion or any feedback for me on how i can do this better please leave it in the comments for me so that i can improve on my next video anyway now let's dive into today's topic leak code 20 so our input string will contain only these characters um and we need to determine if the string is valid or not if the string is valid then we will return true if the string is invalid then we will return false we can determine if the string is valid based on one open brackets are closed by the same type of bracket and two open brackets are closed in the correct order now first two examples are pretty obvious for the third example the open bracket is not closed with the same type of closing bracket and that's why the answer is false now we're going to use stack to address this problem if you don't already know i'm going to give you a 30 second quick intro on what a stack is a linear data structure and it follows lifo meaning last in first out this is an empty stack now if you want to add an element a into your stack then your stack will look like this now the index of the stack is top which is equal to zero which means it has one element now and the stack of zero is equal to a okay now if you want to add another element b to your existing stack which already has a you will add another element b in here okay now your top will become one and your stack of 1 which is equal to a now like i said it's a last in first out so if you want to remove an element from the stack you cannot directly remove a you have to remove b so if you remove one element from the stack which is this one now your stack will look like this a now your top is again back to zero and your stack of 0 which is equal to a so it's the last in first out if you are following type yes in the comments below so we are going to read the input string and if the character that we are reading is an opening bracket then we add it to stack if closing bracket then we will check if stack not empty and the stack top as similar open bracket if these two condition meets then we will remove the top element from stack now at the end the stack should be empty if it's an empty stack then the string is valid and we can return true otherwise we will return false okay so now let's see how this logic will work with an example so we will read the first character of the string and if it's an opening bracket we will simply add it to our stack now the next character is a closing bracket so we will check if the stack is empty if the stack is not empty then we will check the top element of the stack if that matches or if that is a similar type of opening bracket then we will simply remove that from the stack so now we still have an empty stack now we read the next element it is an opening bracket was so we simply add it to our stack next character is also an opening bracket so we simply add it to our stack the next character is a closing bracket so we will check if the stack is empty or not if the stack is not empty then we will read the first element and see if that element is a similar type of opening bracket or not if it's a similar type of opening bracket for this then we simply remove it from the stack so now this is what our stack looks like now we read the next character and if it's also an opening bracket we simply add it to our stack now read the next character if it's a closing bracket we check again if the stack is empty if the stack is not empty then we read the first top element of the stack and see if it's the similar type of opening bracket if it is a similar type of opening bracket to this then we simply remove that element from the stack so this is what our stack looks like and we have no more characters to read from the string at the end of the string if your stack is empty in that case your string is valid but in our case our stack is not empty so the string is not valid and we will return false so first we will create a stack and then we will use a for loop to iterate through every character of the input string if the character at i is any kind of opening bracket then we will simply add it to the stack if it's not an opening bracket then it has to be a closing bracket so we will check that the stack is not empty and what type of closing bracket we encountered in the string and if that matches what we have on the top of the stack if these three conditions are satisfied then we will simply remove the top element of the stack now we will do the exact same thing for curly brackets and square brackets at the end if there are any remaining elements in the stack then we will return false otherwise we will return true now let's run our code
|
Valid Parentheses
|
valid-parentheses
|
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`.
|
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
|
String,Stack
|
Easy
|
22,32,301,1045,2221
|
1,685 |
hello guys and welcome back to lead Logics this is the sum of absolute differences in a sorted array problem and it is a lead code medium and the number for this is 1685 so in this problem you are given with an integer array nums which is already in a sorted order in a non- decreasing sorted order in a non- decreasing sorted order in a non- decreasing sorted order so we have to build and return an integer ARR result with the same length as the nums are but such that result of I is equal to the summation of absolute difference between the nums of I and all the other elements in the array so in so let's consider example suppose we have nums equal to 235 so here you suppose if nums of I is 2 so you have to do the absolute difference of two with all the other elements that is here we have three and five so two's absolute difference with three is actually one and with five it is three so absolute difference done summation is done so it becomes four now four is the result so four is stored at the a index because nums of I here I was zero so four is stored at zero at index similarly three is absolute difference done with 2 and five so it becomes 1 and two and the sum becomes three and for five it is done with two and three so the sum becomes five because three and two are the absolute differences so the main objective of to calculate the sum of absolute differen between the each element and the each other elements in the array so the key observation here what we can efficiently compute the result for each element by considering the differences between consecutive elements so we can use the differences between consecutive elements to efficiently calculate the absolute differences and how we are going to do this so I'm going to tell you the approach now so first we have to calculate the total sum of the array and this sum is actually calculated because we are going to use two pointers left and right to store the sum of the array so this sum will be used to store the right part of the array basically used to compute the right part of the absolute difference and then we'll initialize the pointer as I told you left and the right left to the start of the array right to the end of the array and we are going to iterate through the array for each element nums of I and then calculate the absolute Difference by a formula and in the formula we are going to use the left that represent the sum of elements to the left of nums of I and right that represent the sum of elements to the right of nums of I and the uh actual formula what we are going to use is that n into I minus left plus right - n into I minus left plus right - n into I minus left plus right - n into nums do length minus I -1 so n into I nums do length minus I -1 so n into I nums do length minus I -1 so n into I minus left plus right minus nus n into nums do length minus 1 - I so using this formula we are minus 1 - I so using this formula we are minus 1 - I so using this formula we are going to calculate the result and uh this is how uh we get the result and we finally store the result in the array and return so this is the approach what we are going to follow now let's come to the code section so first of all we'll Define the sum and we will calculate the sum as well so in equal to Su plus equal to n so int left equal to zero in right equal to sum we have fixed the poter then we will declare the result array then we are going to iterate through the nums areay n is set to nums of I the actual in the formula it was we have written n so that was nums of I and right we are going to calc calate by subtracting the right from the nums of uh and subtracting the N from the right we are going to calculate the sum of the elements at the right part of the array so after this we finally going to use the formula so the formula was n into I minus left plus right - n into nums do length -1 - nums do length -1 - nums do length -1 - I it is actually minus IUS 1 otherwise you'll get confused and uh here only you have to do a left plus equal to n and return n sorry r so let's try to submit it for the sample test cases seems fine now let's submit it for the hidden test cases as well yeah it passes the hidden test case as well with the good time complexity and space complexity it's beat 99% in and space complexity it's beat 99% in and space complexity it's beat 99% in the time 85% in the space so let's talk the time 85% in the space so let's talk the time 85% in the space so let's talk about the time complexity and the space complexity as well of the solution so the time complexity is O of n because we iterate through the array once actually twice but uh o of 2 N is also equal to O of n because we do not consider the constants and the space complexity is also often because we are using an output array but we have to use that so uh space complexity is also often I hope you like the video if you want the solution in a different language C++ python or JavaScript you can go to C++ python or JavaScript you can go to C++ python or JavaScript you can go to the solutions panel here you can see my solution this one go here and Below you have the first you have the Java code then C++ code then Python and then C++ code then Python and then C++ code then Python and then JavaScript also you can uport my solution and uh if you like the video please do subscribe to the channel and like the video as well and my thank you for watching the video have a nice day
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
352 |
Hello friends welcome back to my channel the number of interval problem is 352 it comes in hand category but I think it is of medium level not so much Bihar so the problem tells that given are data stream input of non negative wait from a till n Summary D number of scene so far he is on the list of this short interval so here we have 3 method given summary range is constructed and one will be end number and one will be end get interval summary range what do we have in this What has to be done is that we will have to release these empty streams, then we will do OK, what we have to do here is that we have to add the list of this joint interval from star till this answer should be started OK by start time, so now what does it mean that we are a If we understand through the example, here is the example given to us, we have done an empty swing, we have taken the empty stream inside, what to do now, we have to enter the add number, what to do with the add number, then what will we say about the second add number, just go ahead and do one. We will add the number to the Kush team and we do not have to do anything else, we just have to add it, so where does the value of the add correspond to the van? We will go here and add the van here. So look, here we have to write the starting and ending point. This will be out and this will be put. We will understand completely with the example. Don't be afraid, ours is done. Now what is this next command and number? How many numbers did we have before? Van was and one more has to be added. Let's say OK. Now we have finished the command. Look, where will it start from the van and where will it end from, here you are not there, so we can call it considered van, you are three, here because here you are 2 medium, you are mixing, I am gone, hence you are missing. What is missing here, so we will say and he will take a break at 2 o'clock and will start again at 3 o'clock and will also end at 3 o'clock because here he is not doing 2:00. because here he is not doing 2:00. because here he is not doing 2:00. Here, what is the only interval, we have one and three, so what will we say, will it start, otherwise the flock will do something like Gautam and will start at three o'clock and will end at three o'clock only. This is what came, do we have the answer? This is the answer. Do we have Han or Par? Look at this answer, you must have understood what to do now and one, now one more command appears, so now we have done one command b, now and one's main, what is the end number, so now what is the number to do with. It is written here that now we will write together at 1:00, we will reduce it at 3:00 write together, we will write together at 1:00, we will reduce it at 3:00 write together, we will write together at 1:00, we will reduce it at 3:00 and we will reduce it at 7 o'clock, here also we will close separately, OK, we took a break at 2:00, so close separately, OK, we took a break at 2:00, so close separately, OK, we took a break at 2:00, so what about now, when and when, Will start at 3:00 pm, will start at some what about now, when and when, Will start at 3:00 pm, will start at some what about now, when and when, Will start at 3:00 pm, will start at some time now, will finish at 3:00 pm, will time now, will finish at 3:00 pm, will time now, will finish at 3:00 pm, will someone take a step, and on four, five, six, he has taken a break, then later, when will he start again at 7:00 pm, write it along here. But 7:00 pm, write it along here. But 7:00 pm, write it along here. But write seven, how much have we got, we have got three values, one you and three values, we have also got, so what have we finished, this also comment, we have finished, OK till now we have finished or till now we have finished till now We have finished now again what is one more command and what is the command we have one more command here now you have to add what is written here what will we do 123 and seven more A will be changed to become A so now what We will do this also, we don't need it, we have modified it. From where is he reducing it, he is reducing it from van, we can say that a guy is reducing it till 3 o'clock for a reason, then we can say it in short form. This banda is reducing from 1:00 to 3:00 and the reducing from 1:00 to 3:00 and the reducing from 1:00 to 3:00 and the father took a break, when did he reduce the benefit to 60, from 7:00 to 7:00, 7:00 to 7:00, 7:00 to 7:00, we can say this in short form that he is a Because of this, he got upset and finished it at 3:00 pm and here he started it at finished it at 3:00 pm and here he started it at finished it at 3:00 pm and here he started it at 7:00 am and did it in gautamb at 7:00 am and did it in gautamb at 7:00 am and did it in gautamb at 7:00. The commission understood, 7:00. The commission understood, 7:00. The commission understood, ok, what is the command and number, we have mine, what did I say, 123 and 7, what now? What do we have to add again? We have to add six again. What will we do now? We will do this. We will put six and add it. Starting from van reduces van and till 3:00 it will reduce at 6:00. And when will it reduce, by 7:00 6:00. And when will it reduce, by 7:00 6:00. And when will it reduce, by 7:00 we will get the last one, so what is this 1 3 6 7 and in this van earn three seven earn 7 how to do the commission ok now we will code it we will take it here its Han only then what will we do Which sectors will do that and give it simple and what have to be done till now, simply what to do in the first method, we have to put an empty stream inside, so we will simply say tree dot new, finished OK added the value and some No, we just took the value and gave the team. Now we will be here, we will minute the real madam here, what we have done till now, we have done one, we have done this interval, we have to do this, we will ask her the first question, here we are here. But it is very easy to do, don't worry, it is very easy and in this we will say hint and we will say interval, we deleted the new rate list, we said OK, what did we interview, we created an interval, see what to do now, what was our starting point in this, we What was the starting point of a group and what was the ending point? So what will we say here? Now tell us, the starting point will be first. If I am the first element, then give it the name 'Start'. We will take the first element here and will also give it the name 'Start'. give it the name 'Start'. We will take the first element here and will also give it the name 'Start'. give it the name 'Start'. We will take the first element here and will also give it the name 'Start'. What will we do first? Okay, we have given the team, what have to be done to the first, now we have to put the end, what will we do to the n also, we will put van, we will put cute, look here, in this case we will get van less van and in this case we will earn van. Van man, its also three common three, so it will be from both of them, after this, which value will we change, if we have interval, like this, here we got 123, here we got these, only then we will change the end good to three, okay, what will we do first? We will first give it a team, here we will take van, earn 2 3 6, we have taken it, what to do now, we will have to see all this, so here we will say, tree will be a method, three dot, we do not want the starting number, first plus van. When will he do it, but we don't have to do that, we have to start from tu, so we will call it starting from plus van, I hope you have understood here, okay, what do we have to check now we have to see if value - and equal tu. Van, - and equal tu. Van, - and equal tu. Van, what to do now, what to do to the end, change the end to give the team here, I understand the value, what am I doing, look here, we have a van here, you are three, six, and seven are here. But where is the beginning coming from? Start or is happening from the van and where is the end coming from? Have we done the first step? What will we do now? Commission has been made social. Kiss will do 6 in 3 months now, then how much will we get? Six will do 3 - 6. If we get three, if it is there Six will do 3 - 6. If we get three, if it is there Six will do 3 - 6. If we get three, if it is there then what will we do? Now, whatever start and end we got, you put it in an interval. We will have to put in that interval, I hope you understand. If we don't get that, if equal tu van is not there, then what will we do here? But what will we do here, we will create a brick, we will create an indirect one here and its new brick will be your value and here we will put the first and here we will put look at the end, if it is not there then we will give the start and end which we just got. OK, what to do now, we will have to reset it again, we will reset the start and end, what reaction will we do, now in this case, if we got a six, then what will we do, we will reset both of them only, OK, here we have What have we done now, we will check again if the van is made, then we will have to reset a co and co, we will have to go here and reset the start to start, what will we do for this, now what will we do by leaving this type and this re here. But we will say, here we did not do one here, after doing both of these, we had to add here, neither here, after doing these two, we had to add in the answer, nor here, so what will we do here, what did we get van Kama 3 Till now we have not gone to six come 7 till these double, I have just done six come 7 here, what to do now, we will have to enter six come seven also, so we will copy it, then what will we do, will we present any answer here? It will be done that the integer interval which will be increased from the last pit will also be added. I hope you have understood till now Abhilash what to do, we will have to return the interval, what will we do to convert the interval to new, convert it to size. Will we do interval dot size or not? If dot is found then please comment. We will definitely help you. If you like this video then please like, subscribe and comment. Our channel will keep coming. Let's bye.
|
Data Stream as Disjoint Intervals
|
data-stream-as-disjoint-intervals
|
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* `void addNum(int value)` Adds the integer `value` to the stream.
* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`.
**Example 1:**
**Input**
\[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]
**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3); // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7); // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]
**Constraints:**
* `0 <= value <= 104`
* At most `3 * 104` calls will be made to `addNum` and `getIntervals`.
* At most `102` calls will be made to `getIntervals`.
**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
| null |
Binary Search,Design,Ordered Set
|
Hard
|
228,436,715
|
11 |
well i'll be covering question 11 container was must water in this question we want to return the maximum amount of water a container can store so what is a container if we randomly pick any um wireless i'm gonna pick this guy in the sky so container is right here right it's how much water we can fill and what is the equation of a container right so area i'm gonna call it area right so area equals to minimum of either you know um let's call it i here and j right so v of i or v of j times right here distance this is the equation to get every array so question is can we find maximum area using any container so um how we're gonna solve it is we're gonna use that two pointers so my pointer i'm gonna call it i'm gonna call this guy so let's um get started um initially we have a pointers here and here so um area is well it's two times one distance two times because two is minimum right five or two and the distance is five minus zero which is five right so i get ten right and okay we see we're getting area of ten but like how do we update pointers right so we know um this height is defining the minimum height right so we should be moving um smaller one reason is so if i move this guy right here my minimum going to be one but if i move this i to here right now i'm getting three and we are still at five right so our minimum because became three so um our update constraint is we only move pointer that has a minimum height so in this case um 2 is less than 5 right i'm going to move i to right here so now i'm getting three or five of minimum and times distance as well five minus one is four so i'm getting twelve uh we have ten but hey we're getting twelve cool right now which one is smaller three is smaller right so we're going to move i to here and we have six and five min of six of five one times our distance is five minus two which is three so we are getting fifteen so we're gonna upgrade to fifteen and now um which one is uh smaller right so five is smaller so we're gonna move j to right here right and distance is two and we are getting two and hey one is smaller so i'm gonna move this guy here's and we have a six or two and distance is one so we're getting two and we move here then hey i and j i think it's zero and we even keeping a track of uh our area and 15 is the largest
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
1,252 |
Jai Hind in this video Gyan Question Number Protein Vijay Sales with Old Values in Protein Vijay Sales with Old Values in Protein Vijay Sales with Old Values in Matrix So Let's Move to the Questions on Pure Question Sharing Eminem Mintu and Matric Zinc Slice 200 Resources Where is India Is It Is Equal to Arry Co Murder Equal Thickness Represents Intellect to perform some improvement operations at do subscribe my channel subscribe to apint answer is equal to new cent soldier giver name is the number of fruit and the number of columns show across common number of columns and naval make another wearable k where is stored in Length of this kind is so let's see how to increase the answer Something like this so let's get intimate on that all items presented in pictures through an answer matrix so let's increment come 10 Vikram once was the one that and would n't come for her a special that Increment All Items In The First Governor Of Fundamental Research Increment Kill This Lineage Was 180 Degrees But Similar Nau Let's Make A Final Increment So After The Final Increment And The Matrix Look Something Like This Let's Make An Appointment A Victim Her Tits Date Instrument All Items Presented in the First Foreign Dance Committee Member First Tarf An Answer Matrix Let's Increment Everything Comes in a Specific Terms I One Should Bison Also Comes from Now 150 Comes to You O Ka Rate K Paisa Ki Bottom Hi I'm Dam Mistake Momentum So Let's increment all of us again Him Everything Oo Ki Stree Land Atin C 13131 Research Tubelight Do This Question So Let's Code This Question Mode Superstar Oil Follow Us On Ajay Ko Loot Ki Girl Everything Ki Kya Explain New This Just Let Me Complete Scientific Jhaal Ka Loot Zindagi Hai Loot Hote Suspect Let's See What is Happening in Hindi Part-5 Record 0 Part-5 Record 0 Part-5 Record 0 ASaint That I Requested to ISRO K 100 Vented This Point Look r80 in Italy and Were Introduced for Lucknow Surajkund 204 That RJ ISRO and Ne Which Suzy Roadways Date Answer West Indies Is Icon More School Pickup The Phone That Nor Will Also Change 8000 That A Noble Increment This With Me Too Ajay Ko Ek To So Let's Increment Answer 100 Comes When Know I Will Welcome One And Sorry I Will remember 01 ok so revolt against i20 and you have 0 to 210 answer 2014 that zero and first column so let's increment is 139 vijay vikram do how to that thank you loot so let's increment now answer 8012 sona ujjain will be completed but this condition Will spoil sure zoom out of this point look on a kid will get inside that for lokpm chords to allu jericho 120 and wave answer 80 to mind is this video to death so answer 800000 first ingredient this is that love dj vikram 1a jhal a super Student Pass Column Increment Is A Knowable Welcome To Ki And This Condition Will Be Falls For This Point To Will Break Sushila Available First Ingredient 2100 Bhed Finally Bigg Boss Is So I Will Welcome PM One Day Ki And James Ko 20 Jhaal Ajay Ko Mein Ruke Super Nice One In Digest 120 Flats Peeth Strengthen Youth This One Should You Will Be Given And James 2000 Ultimate Answer 821 More In This That Lalu Jail Earthquake One India Seth 120 Which Is This Cream And Want And Views 154 Hai So Increment This Answer Ajwain Ko Mobile Par Ka Music Album Do Ko Increment Answer And Want To Meet Oo O 139 Desh Ko Follow Will And Will Move Inside This For Look Suji 100 Ki Ko Murder Case Is I Coma 151 Schezwan Ko Mobile Phone Ko Mohan Sood Vivaan A ok increment and decrement answer 80 ka muhurat 2012 139 job will welcome one to increment answer advance kamo one capsule vitamin free ki aapke date gel bcom 2nd is condition 1508 spoil uppal end and now and waste is equal to your friend i will be coming two more Sunao to so sudesh hole of tank follow-up and sushil after final follow-up and sushil after final follow-up and sushil after final increment brigade this something like this 13131 131 00016 so main part should now let's complete the code finding day old values in district one finding day old values in district one finding day old values in district one is so let's define account on student account record 207 dallas Twitter account hai ki so let's hydrate through each and every es index optometrics a loot hair MB the number of roses the matrix hai jhal ki and when is the number of columns jhal then answer 8i ko mar dijiye the motive lattu is not equal to 0tweet will increment account plus I am on your show but this party swing get going into every Indians and taking away the native on oct episode and account will be implemented and servant not been created to be done with according to that let's check okay so let's make this which
|
Cells with Odd Values in a Matrix
|
break-a-palindrome
|
There is an `m x n` matrix that is initialized to all `0`'s. There is also a 2D array `indices` where each `indices[i] = [ri, ci]` represents a **0-indexed location** to perform some increment operations on the matrix.
For each location `indices[i]`, do **both** of the following:
1. Increment **all** the cells on row `ri`.
2. Increment **all** the cells on column `ci`.
Given `m`, `n`, and `indices`, return _the **number of odd-valued cells** in the matrix after applying the increment to all locations in_ `indices`.
**Example 1:**
**Input:** m = 2, n = 3, indices = \[\[0,1\],\[1,1\]\]
**Output:** 6
**Explanation:** Initial matrix = \[\[0,0,0\],\[0,0,0\]\].
After applying first increment it becomes \[\[1,2,1\],\[0,1,0\]\].
The final matrix is \[\[1,3,1\],\[1,3,1\]\], which contains 6 odd numbers.
**Example 2:**
**Input:** m = 2, n = 2, indices = \[\[1,1\],\[0,0\]\]
**Output:** 0
**Explanation:** Final matrix = \[\[2,2\],\[2,2\]\]. There are no odd numbers in the final matrix.
**Constraints:**
* `1 <= m, n <= 50`
* `1 <= indices.length <= 100`
* `0 <= ri < m`
* `0 <= ci < n`
**Follow up:** Could you solve this in `O(n + m + indices.length)` time with only `O(n + m)` extra space?
|
How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.
|
String,Greedy
|
Medium
| null |
137 |
hey everyone so let's do this problem from scratch this is a bit more manipulation problem single number two and we are going to do it in C plus as it has perfect uh integer storage in 32-bit actually if you do the same logic in Python it might get different answer because this is kind of python has huge capacity of integer right so without wasting time let's start the topic single number two where the question simply says that you have three numbers repeating and one single number that is unique in the array that means if any number is present and it is repeated then it must be present three times and there is one unique single number and you have to Output the single number right so what is the approach I search over YouTube already about this topic and I saw very long lengthy tutorial for this question so let's understand it in ready easy way like I have a pen tool so as you already checked that if any number is present let's suppose I have four that is uh okay let me write small for 40 the handwriting is not going well let's just understand the logic so I have 3 4 and 4 bit representation is 100 so what's the catch we are going to start with a Tracker that is our bit variable it is initially started with zero so we are going to track every single bit from unit place to 32. that means maximum 0 to 31 right and what that makes sense that if any number is repeatedly present in the array for three times that means the bid value when we just incrementing the set bit let me clarify more like if we check unit bit is set or not this beep I say it or not if it is set we are just incrementing the beat right and if it is not set we are not doing anything so now the catch is if the beat is hit that means it is multiple of 3. always present in multiple of three but if our unique number has let me pause the recording yeah now let's start again uh so if we if our unique number has these bits hit that means the beat is increment one more time at it is not the multiple of 3 this time right so let me clarify in code where just initially start with a loop I is going to be 431 and I plus and we are keeping a track for in bit equals zero right and now we are just iterating over the array and we are checking if the beat is hit or not right is less than nums dot size and J plus okay great and now we are just checking if Norms of J and that bit that means I he said then we are just doing with plus right and at the end of the first Loop that means we are done with the first bit checking right if it is set or not and we are both the same for the 32 bits maximum and if beat person 3 is not equal 0 then we keep track of another variable answer is equals zero 18 transition obviously we do not that answer is equal answer or we are just doing this bit set right and at the end we just return the answer now let's start this book okay let's check it out yeah as you can check runtime zero milliseconds so let's run the code and as you can check it successfully compile and plan so this is the logic all about and it's pretty simple hope you understand everything I have mentioned in this video and if you have still any doubt you please make sure tell me in the comment section and I will definitely try to help you thanks for watching and make sure you subscribe till then take care
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
1,475 |
this late code question is called Final prices with a special discount in a shop so we are given an integer array called prices where the E element of prices is the price of the E item in a shop so there is a special discount for items in the shop so if you buy the I item then you will receive a discount equivalent to the jth element of prices where J is the minimum index such that J is greater than I and the prices of the jth item is less than or equal to the price of the E item otherwise you will not receive any discount at all so we want to return an integer array called answer where the eth element of answer is the final price that we will pay for the eighth item of the shop considering this special discount so here's an example of some input that we could get the prices array so a Brute Force approach that you may have already thought of is to just iterate through each element once and just for each element checking the um subsequent elements to see if they're less than or equal to the current element and if they are just minusing the subsequent element from the current element and that's giving you a new array now that does give us a correct solution a correct answer the only problem is it's a bit inefficient we're iterating over the same prices multiple times and the time complexity of this approach actually Al together is unfortunately Big O of n^ 2 which I mean unfortunately Big O of n^ 2 which I mean unfortunately Big O of n^ 2 which I mean for this question this problem um is accepted by leak code however it's not quite the optimal solution that you should be happy with so there's actually a solution which works with a Time complexity of big of n so a linear time solution that actually uses a stack to efficiently find discounts and apply them to each element so this stack is just a stack of indices of items which are possible candidates for receiving a discount from subsequent items so all we do is we just want to iterate over prices and for each price encountered during the iteration all we want to do is check if there are any previously encountered prices in this stack here that could possibly qualify for a discount all it does is compare the current price so the price we're currently iterating on with the prices at the indices stored in the stack so if a discount is found as in if there's a price lower than the current price we can apply the discount to the appropriate price which all we do is just subtract the discount from the price in the list and then after applying this discount we just want to update the stack so as the stack just contains indices of items which may qualify for a discount if we've actually applied a discount to one of these items we can just pop that one off the stack as obviously it's no longer a candidate as items can only be discounted once in either case if a discount was found or not with the current index we also just want to push the current index onto the stack as well as the price for the current index can also be elgible possibly for a discount using future items so the algorithm continues this process until all prices have been considered and so by the end of the iteration each price in the list will either have received a discount or will remain unchanged if no discounts were possible for that item and then all you want to do is just return that modified list of prices so if we just go through this example step by step I'll show you how this works in more detail so I'll just write out the indices of each item just so it's a bit easier to follow so we've got I equals 0 one two three and four so we just iterate over prices we start with the eight here and what we want to do is check if this eight can be used to perform a discount on any item that's contained within indices so as we can see however indices is empty so obviously this eight cannot be used to Discount any previous items so what we do in this case is we just push the index of this current item onto to the indices stack so the current index run is zero so we just want to push on that zero so now we just want to move on to the next element which is the element at index one where the price is four so now what we do is we just want to check the indices stack to see if there's any prices we may be able to Discount using the current item we see that there's a possible candidate for a discount which is the item at index zero so what we want to do is just check the Top Value in the indices stack which is this zero here which is the zeroth item of prices so now we just want to check if the current element's price is less than or equal to the price of the top of the indices Stacks that index's price in the prices array which in this case the index is zero so the price is eight so we're just checking is for less than equal to 8 we see that it is so what that means is we can actually perform a discount on the zeroth item here so all we do is we get the price at the zeroth item and we just subtract the price of the current items price which is so that would turn into 8 - 4 and then once would turn into 8 - 4 and then once would turn into 8 - 4 and then once we've done that as we've applied a discount to the zeroth item in prices that means we you can also pop it off of indexes as it's no longer eligible for another discount so we just pop that one off so now after doing that the item at the first index of prices is now a potential candidate for a discount down the line so we just want to push the current index onto the indices stack so that would just be able to push that one now we move on and we want to move on to the next element so on IAL 2 so once again we just want to check if there's anything in the indices stack which means is there any element that we may be able to use the six on to perform a discount we see that at the top of the stack is one which means the element at index one in prices is a possible candidate for a discount so now what we want to do is just check if the price of the current element is less than or equal to the price of the item um in the indices stack so we want to check is the price six less than or equal to the price of the first indexed element in prices which is four unfortunately it is not so that means we cannot provide a discount using this value on the four value so that means we don't touch the price of the first element in prices we also leave that index in the indices stack as well and so all we do is just push the current element index onto the indices stack as well so we just add that two there and now we just move on to the next element so now for this element when I equals 3 once again we just want to check the indices stack for any possible candidates for a discount we just want to start at the top of the stack and work our way down if we can so now we're checking the element at index 2 in the prices array we just want to check so if the price of the current element which is two is less than the second index at prices which is that six so we're just checking is 2 less than six well it is which is good so what we can do is actually minus the two from the six so that's just minusing the price of the current item with the price of the item at the top of the stack so that's just becomes 6 - 2 so after that after we've becomes 6 - 2 so after that after we've becomes 6 - 2 so after that after we've applied a discount on the item where IAL 2 it's no longer eligible for another discount so all we do is pop off that value from the stack so we just pop off that two so now what we do is we just want to check this stack again if there's any more items where a discount may be um applied so now we just want to check if the current element two again is less than or equal to the price of the element at the top of indices so the item where I equal 1 which the price is four we can see once again that is true so what we can do is minus the two from that price as well and then as we've applied a discount to that item we can also pop it off the indices stack as well as it's now no longer eligible for any further discounts after that we can just push the index of the current element onto the stack as well as it may be eligible for a discount down the line so we just push on that three so now we move on to the final item where I equal 4 and then price equals 3 once again we just check this indices stack to see if there's any element that may be available for a discount we can see that there is index 3 so we just want to check if the price of the current element is less than or equal to the price at that position so we just check is three less than or equal to the item at IAL 3's price which is two unfortunately it's not so we cannot apply a discount to the two so we don't pop the that three off of the stack and what we actually do push the index of the current element onto the stack as well as if this prices array was longer if it was extended by a few elements we could continue this process again just in case 2 and three will be available for a further discount okay so after that process we'll have our final updated prices array which I will just come down and make a final copy just so we can see what the Final prices should be so that a is min - 4 so it becomes a be so that a is min - 4 so it becomes a be so that a is min - 4 so it becomes a four the two the four is min - 2 so it four the two the four is min - 2 so it four the two the four is min - 2 so it becomes a two the 6 is- two so it becomes a two the 6 is- two so it becomes a two the 6 is- two so it becomes F4 and the two and the three remain untouched so we will just return this aray this is the result so let's just move on to Elite code and I'll show you how we can code this solution up so first what we want to do is just initialize our stack to keep track of indices of potential discounted prices and we'll also just initialize a very variable to keep track of the size of prices so now what we want to do is just iterate over each element of prices we then want to check the Indy stack to see if there's any possible items that we can apply a discount to using the current element and as we may be able to do this to multiple items we'll use a while loop here just so that we can continue performing discounts if we can so it's well indices is not empty and also it's while the price of the current element is less than or equal to the price at the top of the indices stack as well so in the case that both of these conditions are true that means we can perform a discount on the top element of the prices stack using the price of the current item so that means what we want to do is just update the price of the item at the top of the St stack in the prices Vector so we will just access that item and we will just minus the price of the current item that we're on and then as we've performed a discount on that item at the top of prices it's been processed it we can't do any more discounts on it so we just pop it off the top of the stack and what this W Loop means is that after popping that item off of the stack if the next item on top of the stack is also able to be discounted using the price of the current index or the current item I should say then we can do that again and as well anyway after all items that can be discounted using the current item are or if maybe the indices stack is empty we just push onto the stack the index of the current item as it may be available to be discounted down the line and then all we do after that is just return our prices array so to recap we've just got our stack here um we just use this variable to help us iterate through prices we just iterate through each element of prices and for each element if there's an element in the stack that is greater than or equal to the price of the current element that means that we can use the current element to perform a discount on the item specified at the top of the indices stack if we can do that then we just perform that discount we minus the value of the current items price from the price of the item at the top of the index and then this should say pop and then we just pop off the Top Value from the indices stack as we have processed that item and then after that if no matter if any discounts were applied or not we also want to push the current index onto this stack as well as it may be legible for some further discounts down the line and so after this whole iteration has been completed then our prices array should all be updated and all the prices that can be discounted will be discounted and we should have our correct result so if we just submit that we can see how we did we can see that this solution unfortunately it only beats 50% of users unfortunately it only beats 50% of users unfortunately it only beats 50% of users apparently I suspect this is because the constraints of the inputs are quite low the size is only between 1 and 500 so the ASM totic time complexity Improvement may only be seen when the input values are fair bit larger however it's still much better to provide this algorithm in an interview as it's asymptotically much better than the Brute Force solution and it's much more impressive you can also talk about some memory tradeoffs though this solution uses big of n space complexity just to use the stack The Brute Force uses constant space which you can discuss that in some cases may actually be beneficial and may be favorable but it's always good to discuss the trade-offs always good to discuss the trade-offs always good to discuss the trade-offs with all your algorithms in an interview I hope you enjoyed this video if you did be sure to leave a like And subscribe and I'll be sure to continue making these if you have any questions feel free to leave them in the comments below and I'll be sure to get back to you as soon as possible thank you for watching
|
Final Prices With a Special Discount in a Shop
|
maximum-sum-bst-in-binary-tree
|
You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop.
There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Otherwise, you will not receive any discount at all.
Return an integer array `answer` where `answer[i]` is the final price you will pay for the `ith` item of the shop, considering the special discount.
**Example 1:**
**Input:** prices = \[8,4,6,2,3\]
**Output:** \[4,2,4,2,3\]
**Explanation:**
For item 0 with price\[0\]=8 you will receive a discount equivalent to prices\[1\]=4, therefore, the final price you will pay is 8 - 4 = 4.
For item 1 with price\[1\]=4 you will receive a discount equivalent to prices\[3\]=2, therefore, the final price you will pay is 4 - 2 = 2.
For item 2 with price\[2\]=6 you will receive a discount equivalent to prices\[3\]=2, therefore, the final price you will pay is 6 - 2 = 4.
For items 3 and 4 you will not receive any discount at all.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** \[1,2,3,4,5\]
**Explanation:** In this case, for all items, you will not receive any discount at all.
**Example 3:**
**Input:** prices = \[10,1,1,6\]
**Output:** \[9,0,1,6\]
**Constraints:**
* `1 <= prices.length <= 500`
* `1 <= prices[i] <= 1000`
The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.
|
Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minLeft). In each node compute theses parameters, following the conditions of a Binary Search Tree.
|
Dynamic Programming,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Hard
| null |
43 |
I will come back and number 43 multiply strings we were given two strings which were integer numbers and output product and we are not allowed to use those big integers are great I'm not even know that anyway we have to do the old-fashioned way to do the old-fashioned way to do the old-fashioned way to do multiplication so we need a product or a which Elance is going to be sum of two strings to numbers lens I because that's the worst case if we have a number nine and another number nine that's going to be the product is going to be anyone that's to another example if we have two digital numbers multiplication like 9999 also you're going to be four digits so we need two integer less round to string then the products and loops rule the first string and the inside group even and then doing another four do because we have to modify all numbers one by one and then we do the multiplication course this way kind of translate character into integer and then we'll put it into the products position and then we do the conversion product to a stream or integer we go through the products and so we have the carrier and to be mode the position of the number item because it is a stem calculation then divide the career in divide by T and get a carrier so we still get the number on the model by team to the collisional and the product they're going to be template so last step is convert the array to string again so we using a string builder and append each number from the product and then if our computer lenses not equal to 0 and stability chocolatier is not zero and the return string that is doing awesome and not bad int and complicity as well I think that tooks I would say Big O and squat heart there are two fathers
|
Multiply Strings
|
multiply-strings
|
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string.
**Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly.
**Example 1:**
**Input:** num1 = "2", num2 = "3"
**Output:** "6"
**Example 2:**
**Input:** num1 = "123", num2 = "456"
**Output:** "56088"
**Constraints:**
* `1 <= num1.length, num2.length <= 200`
* `num1` and `num2` consist of digits only.
* Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
| null |
Math,String,Simulation
|
Medium
|
2,66,67,415
|
476 |
Hello hello guys welcome back to years and this video will see the number complement problem system digit code for the match challenge so let's look at the problem statement in this problem giver number and you need to find the element of December and this problem number indicates that You Need To Lips Se Withra 080221 Problem Very Simple Specific Se Person December End Tours Subscribed Number Digit They Are And Main Ka Number Which We Are Given In The Function Of Later See How Can We Process So What We Will Do It Is Waste Processing From the rate of but is from the president will be I am masking just asking all the subscribe definitely 2000 number one is equal to zero this is the liquid 90 update and result with oo will just amazed me if support sources this is the first morning Hai 18204 I Lashes Wear Processing Zero Number Flirts With This Number 100 Number Of Times Daily Will Be Equal To One Because If You Want To Get A Job Motherboard Did n't Be So You Will See Later You Will Be Able To Understand This Will Be The Result Will Be Updated Subscribe My New Number 1000000 Subscribe To Busy Roadways Asli This Don't Know Any Process Okay This Is The Best Number Which You Are Processing Is Number One Day When You Will Be Shifted To Avoid Eating Food Processing Number 90 To 100 Subscribe to The Amazing 0091900 Komodo Bhi 102 You Take It Well And With One Shiv Will Give You Results 1020 You Need To Know How To Use This Is Third Idli Equals Two To And Subscribe 2018 Phone Number Date Is The Best VR Processing Software Shift Times Daily 12424 Result Already Told That One Plus One Will Be The Result Will Be Updated To Know You Will Have To Write This Way You Will Be Left With Only Doing So Will Update You Are You Will See You Know The Current Deposit Asset 200 Number Result Result Result Straight Number N Is Gone Because Observed In Cost And So When All The Best Clear Crosses Danger Water Stored In Result Will Be Final And You Can See That you have number 0001 to 9999 Veer Vipin number 90 number one after doing so will be the meat scholar is equal to zero that means the con is on set so they need to set soth avoid you will have to live with number of times bluetooth off The number to the current result doing so will result in subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page and solution different languages please like share and subscribe
|
Number Complement
|
number-complement
|
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `num`, return _its complement_.
**Example 1:**
**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
**Example 2:**
**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
**Constraints:**
* `1 <= num < 231`
**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
| null |
Bit Manipulation
|
Easy
| null |
149 |
hello friends so today in this video we're gonna discuss another problem from lead what the problem name is maximum point on a line so this problem is actually suggested by one of my subscribers so if you also have some problems you can mention on a convox i will try to solve them as soon as possible so the problem is not too difficult uh but you just have to understand that first always try to read the constraints also so that you can also get that what is the maximum time complexity you can use for the problem because it's up to 200 you can use of n cube also so the problem is actually asking you that you are given different points on a 2d grid and you have to actually find out that if you like what is the maximum number of points that lies on the same straight line if you form a straight line then what are the maximum number of points which will lie on the straight same straight line okay so now that's a problem as you can see that these are the different points if you draw any random like this straight line four points will lie on the straight line so now like the basic uh intuition of basic knowledge you have to know to solve this problem is slope what like how can you define a slope of a line so for finding out the slope of any line what you can what you actually have to do is you have to find out like so if this is x 1 y 1 and x 2 y 2 the slope of this line is like y 2 minus y 1 upon x2 minus x1 this is the slope of the line and to find out whether any point lie on the particular line like if you have any line and you could find to find that whether this point lies on this line like whether this point which is like x3 y3 lie on this line how you can find out because if you form a straight line using these two points and if you form a straight line using these two points like these two points and these two points the slope of both the lines should be same and the slope should be unique because as you can see two lines if they have the same inclination if you take out two points on the same line the slope will be same and that's the concept you can use so if this is the point you want to check that whether it lies on this line what you can do is this is the slope of the line using these two points and then you can again find a slope using these two point which is like y 3 minus y 1 upon x 3 minus x 1 and that's a logic now so what you can do is because the constraints are very small in this problem you can take any two points because you can form a line using any two points so take any two points and take that okay i want to pass a line using these two points only and then check that how many points lie on the line which is passing through the particular two points you have chosen so you have to choose every two possible points because to form a line you have to choose at least two points and if you have chosen two points you have known that this is a particular line then check that how many total number of points lie on this particular and then you have to just maximize the total number of points because taking any random line is not beneficial taking a line which is consisting of some points it is valid okay so that's the whole like logic of this problem to make a straight line using any two like every two points and then find out how many points lie on that line so the first thing is if there are only two or one point so the answer is only like both of them will lie on the same line so if there is only one point so obviously i can draw any line and it will lie on that point so the answer is one if there are two points so obviously i can draw a line passing though like through those two points and the answer is will be two else for like three four for more uh for four more points then what you can do the maximum is two because the maximum you can get maximum not maximum the minimum you can get is two points okay because if you have like three four like any points more than three then you can always draw a line passing through two points okay then what you can do is take every two points so make a like uh two for loop that is nested for loops one going from zero to n and other going from i plus one to n okay now because you have taken two points to form a straight line these two points are already taken so i and j are already taken so the total number of points which will lie on this portal line is two till now because i have taken these two points now i will iterate over the whole number of points again except these two points because i've already taken these two points i and j i have taken two points i have a vector of different points let's assume i will pass a line passing through this point and this point so i've taken these two points and i will pass a line through this now i will again iterate over hold the whole array and find out what other points except these two points because i've already taken these two points as a line so accept these two points what all other points lie on this particular line so i will again do a for loop so that it is n cubed now and accept the i and j point i will check that what are the two points which are having the same slope now as you can see if i do this thing if i find out so i have the highest point which is like this point this jth point i have this point and i'm iterating what all the k points which are lying over this line now if you use this formula which is like finding out y 2 minus 5 and x 2 minus x 1 and like if you divide them then it can become in some decimal points so and then if you divide this can also become in some decimal points and it can get this little bit hazy buzzy to find out uh like what is the particular answer it can happen that they do not match out so in such type problems what you can do is just do a cross multiplication so instead of like dividing them out multiply them out so what you can do here is if y2 minus y1 multiplied by x3 minus x1 if that is equal to y3 minus y1 into x2 minus x1 if they are same because in this we are multiplying and multiplying can be easy instead of dividing in dividing we can like lead to decimal position so in all this such type of equation when you find out this type of problem in which you have to divide them out always try to cross multiply and that will make your life very simple so if you just have to find out that whether this combination is same so what you can see here is i just write down the same thing here if so i have three points i j and k which i have told is i j you can write down this like this minus thing multiplied with this point is equal to this point and this that's what i've written here if they are same so i will increment my total so my total will increment so which means that okay this particular point is also lying on the particular line which i'm seeing which i've made by joining i and j point and then i have to get over the whole array uh and find out that this is the total number of points with the lining which are lying on this particular line so i will just maximize my total answer because over all the possible lines find out the total number of like find a line which has the maximum number of points lying on it and then just return the maximum points or the maximums i hope you understand the logical code part for this problem if you have any doubts you can mention now i will see you next month thank you coding and bye
|
Max Points on a Line
|
max-points-on-a-line
|
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**.
| null |
Array,Hash Table,Math,Geometry
|
Hard
|
356,2287
|
127 |
today's problem is word letter which is a hard problem in lead code basically you have to go the whole description the whole uh description states that you have to go from the word hit tell cop using the words given in the word list array and each transformation costs us one generator one unit basically the first you will go from hit till hot or then dot and then cop which is five foot long hit one and then two then three then four and basically the other five the uh the you can say uh you can say the you can see the criteria of going from word one word till the next word is basically if they are differentiated from uh from the next word by one single letter for example the hit and hot there is a difference of single letter h and d remain constant and i and t are different and same is the case the missing is the case with hot and dot hot the o and t remain constant h and d are basically the variable every one of the transformations this is stated here basically you have to return the shortest transformation sequence basically if you have already solved some of the problems you can easily identify this as a graph problem because there is nothing special and this there is no trick or you can say this is straightforward graph problem is you have already solved some of the medium you can say problems on lead code regarding graph and really regarding it regarding bfs the question is here the question here is basically you use dfs and bfs the uh i'll just i just uh i'll just it's state something very important regarding the graph graphic reversal techniques if you want to get the shortest something a minimum to do something medium minimum number of steps you have to already you have to always use a bfs because bfs visits the visiting nodes of the graph in inspection manner one by one first you can say the first letter that the first order then the second order and the third order you are currently you are granted you are always going if you visit the notes in a bfs in the bfs manner you are always directed that the note the shorter in the shortest possible time i'll just place something here number of words in the shortest transformation sequence indicates pfs and node dfs because dfs you can say uh vfdf first explore explores the single branch till the end see the leaf or leaf of the you can see till the end of the recursive branch and then all the basically a single recursive branch and then you can say backtracks and explosion another branch but df but bfs explores all the or all the you can say neighbors uh all the neighbors sequentially bfs give the shortest pass every because it will visit the known special matter level should be you can say a basic understanding of how the pfs works and basically how you can uh basic code of bfs i'll you or you will be wondering how what will be the neighbors of the current node this is there this is a root node this is and this the backend what is the root node basically the root not the root node basically starting out and what is that you can say uh final stage of our sequence the neighbors of hate are all those words which differ by will differ by a single character for example hit to hot only o differs all the words like gate or and all only o differs and the remaining h and t remain constant all the words like get on here for example uh all they will get but in gate only i h and g are different in hip only uh only p and p are different would be neighbors of the if they are present in the word list all the variations of the current word if all the of the current word if they are present in this array it would be basically the neighbors of the current node and each changing character would no matter the place would cost us one zone for example uh the hit the head gate and hip both would cost us a single unit of time if we if it is if during the transformation sequence all you can find plenty of videos on the internet that describe the simple bfs approach but i thought i would be i would write the basically i would write the code using the bi-directional write the code using the bi-directional write the code using the bi-directional bfs first i would describe some something like uh from something the basics of by direction bffs so you can get along with me uh you can use all you can always use a bi-directional bfs when both start and bi-directional bfs when both start and bi-directional bfs when both start and end states are given in this case uh the begin the beginner is the height is the start word and cog is the final stage so if this indicates we can use a bi-directional dfs we can use a bi-directional dfs we can use a bi-directional dfs and by that it is not a must for coding interviews but it is a good thing to know and you can say this is a quite you can it is a quite advanced topic the problem on lead code this problem uh open the log it is basically the almost as the same as this problem but it is a medium problem directional bfs approach and the in using just using something like something this uh on the uh simultaneously something like this do bfs from the sources forward direction and target in backward direction if this is the start node and which are which is the beginning word we will do a forward switch from this side and a backwards search from uh backwards from this side they will meet something some for example they will meet somewhere in the middle and this will save us uh basically quite a lot of time every iteration we choose a smaller queue for an excitation i'll just explain during this during the course uh the theory behind using a bi-directional dfs or bfs rather than a bi-directional dfs or bfs rather than a bi-directional dfs or bfs rather than a single direction in a single directional bfs is basically this as you go deeper the cost of exploring a scene across a single layer increases exponentially so instead of doing a single pfx and exploring all the areas we basically do two half df and the half depth bfs which basically which in this tape saves a lot of time interesting intersection point somewhere in the middle for example here and here this h could it could be the intersection point and this would save us a lot of time rather than if we started if we have scooter started from a and would be which we could we must have we must go to the o to basically reach the end state and in this case we will uh we will meet somebody in the middle to you using the pi direction vfs time complexity for you can say by default bfs is this and the time of the complexity for you can say this is a single bfs uh you can say that the classical bfs is this but we basically this is the pc for the single bfs but before simultaneously one from back one from the forward direction and they meet they may be made somewhere in the middle so we are not exploring all the layers this is why time complexity is uh which is far less than this i'll just cut and paste this we will need uh you can say three sets uh i'll doing it using hash sets we will need a begin uh you can save a forward set you can say forward set which will be which you will need you do basically uh for the forward direction and then we are backward backwards set and then we will also need a scene set the forward set would contain the bigger the begin word and the backwards contain the end word and the scene would also contain the scene would also be the beginning because this is we this is the starting point of our uh you can say bfs maybe we will do all we will also convert the word list it was set for you can say better access times and something like this okay now we will now will basically uh we will know now we will basically start a while loop till the both forward set and backward set are present something like this now i'll just uh them there's something else to do in this case i'll just i just said every patient will choose a smaller queue for next generation smaller or smaller key or smaller set same thing habitation because we will choose between the forward set of a backward set if the forward set has a if the forward set has less number of elements we will basically swap the both these sets uh so we can still be so we could go with a smaller number of elements and basically improving efficiency uh improving the efficiency of our code something like this if this element is greater than this if the length of the forward is greater than the backward we will simply swap the you can say sets in python set something like this okay now we have the node swap for us we will always be going through the will always be swapping and you're starting with the know we start with the set with a smaller number of tools from two with improvement efficiency now we need another set name we can see we can set this would contain the you can say basically all the transformations of all the transformations now we can simply go for example like this for word in the this no i did something wrong this would be this the you have to basically uh set the backward set to set the backward set here something like this if length of forward set is better than backward set the backward set to for as the forward set backward would be forward will be backward huh now it's correct for forward we will be replacing all the words in the forward set and something is like this for word set and for x uh x in range of uh for x in range of you can say word there are now there are multiple well multiple ways for pre-processing but i multiple ways for pre-processing but i multiple ways for pre-processing but i would why would be going the simple with the simplest approach uh for life or something like this for character in we have to basically there are multiple ways to generate all the numbers of the current node as i actually explained earlier all the words which have a single character difference from the current word the and we would try basically all the you can say uh characters in the correct we would be all we would be traversing all the characters in the alphabet all the although all of all the efforts in english language for example a b c and c a and then for the we can say second and then h would remain constant and h jt then h bt something like this i hope you understood me okay i'll just simply now we know we're creating all the words of the current uh current the using by something using a slicing something slicing start this means start from start we will we would be slicing till x and then we would be appending the current character then would be slicing till we using the slicing will be you can see x plus 1 till the end of the string this would go this would give us a hit all the neighbors of frequency with the single letter difference if tmp is equal to you can say if tmp in you can save tmp in the end set backward set so basically we will simply return distance plus one okay or else simply this is a problem with the indentation if this is what is in the backward side for example we have started we start from we started searching and we found this we found our end area one end state we would simply return the distance else if tmp in word list basically tmp in word list and tmp not dn temporary very temporary definitive word not in scene we would uh we would scene dot add tmp and something like uh we will also add this word in our current set of current set dmp okay and for if our while loop ends and we found nothing we will constantly return zero and one more thing and we will also need basically if to check basically this is the invalid you can see invalid input so we will be this is about this is the boundary condition northern word list return zero if n were not in one people this is this would basically swap this would basically square the number of you can send this we will also we would always go with a smaller number of facet and in the end we will need to increment our distress variable and also assign this set as a new is a as a new as our new forward set as a new forward set this plus one and begin i hope it should work i just i'll just run code and if it's properly done so then explain the code once again distance for people initializing the distance variable with one it's running properly okay the code is submitted like successfully i know i'll explain the approach once again you need two sets one forward set one backward set the forward side will contain the if the initial stage the backward set the backward the you can say backwards would contain the uh you can say final stage also need a scene also you also need a scene you can going through all the words you have basically previously travels which people previously seen and this would contain us this foot container basically the in initial stage the we have converted this set the word list into a this was previously set previously array we have committed this to set for bit that better access time and we have better access times and this is the distance variable we will for the use will return returning here this is the bound this is basically the boundary condition we will basically boundary conditions for checking if the enterprise is not in voltage we don't need all this processing basically we're using a while loop with bfs using the smaller number of root note that would basically increase our efficiency uh efficiency because it would all be going them you know we will always explaining less number of you can say nodes and it's and basically next number of branches this is the set for you can say exploding the current transformation and for each wording for in this we will going over the going over each basically place hit then h for inhibit we first h then i then t and we will be replacing h with all the characters in the alphabet in all the alphabets in english language which are 26 we would form basically you can say typically temporary word if the temporary word is in backward set that means we have reached the final state which we should initialize here we would return distance plus one and if the temporary variable is in wordless basically it's a valid neighbor and it is and it has not been previously seen then would then be we would add a scene set and also begin set we will be able to assign the begin set in the next rotation we will assign a begin set to our forward set any consequence also implementer you can also increment our distance also increment distance variable with plus one
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
208 |
hello hi everyone welcome back to the series so in this video lecture we'll be learning to implement this dry data structure which is the prefix tree so this problem Implement try contains the implementation of the dry data structure so it contains we have to implement a class try which contains a Constructor try which will initialize an object of this type try then we'll have a function insert which word as an argument it inserts this word into the try then we have a function search it returns a Boolean variable true or false depending upon whether this word exists in the try or not then finally we have this function starts with which checks if we have a word which starts with this prefix which we have here if we have such word then we return true from this function otherwise we return false so how we can solve this problem how we can implement the try let's see that so here we have our dictionary which I want to insert into the try so we can imagine that let's say I'm start I start inserting this word try so corresponding to this try I must have a pointer which points to the next node which contains this r so to do to implement this type of functionality I create an array corresponding to each node of try which can store a pointer to all of these characters which are present in these words so let's say in these words the range of the characters is from small a to small Z and we have 26 characters in this range so for every node we create an array we must have an array of pointers of size 26 where every position like the first position stands for a second is for B third is for C and so on let's say we want to insert T so I want to insert T so let's say we have t here now inserting t means at this point T points to some other node which contains this r that's what this means now that node also contains a corresponding array to which this T points and in that array we must have R somewhere and this R Points to next node which contains this y and we can Traverse from one node to another so we can start with T we can move to this node then we can move to this node finally so that's the type of node structure which I want to do so also I also want to mark that y is an ending character so for every character we must know whether it is an ending character or not like here in this case T is not the ending character R is not the ending character but Y is the ending character so after we have stored a point corresponding to Y which points to some next node we must have another variable let's call it is and variable and this is and variable must be marked to true so we choose a Boolean variable for every node while here in these cases is and is marked false it is mocked false for this node as well now let's say I also have a word TR in this try if we have this word as well then that means this Boolean variable corresponding to this R is now is MOG is marked as true so that we can simply check whether a given character is the ending character for any word or not fine so let's just see the typical structure so we'll use struct node let's call it node and this node contains two elements the first is an array of pointers so an array of struct node pointers let's call it children of size 26 this stores pointers to the corresponding nodes and a variable is end so this is a Boolean variable is and so this is the typical node structure which we'll be using for implementing try so let's see how they are actually implemented so let's try to insert try into this try okay so we have this typical character so we have this so since I want to insert this try t r y I will start with T so I will initialize n object I will initialize a node corresponding to this tree so in this node we'll have a array of pointers so an array of 26 pointers we will have t somewhere and we'll have a Boolean variable is and which is marked as false now this is the node corresponding to the first character Now we move to the second character here this T must points to the node corresponding to the character R so we have we must have a node corresponding to the character R so here we again have an array of size 26 and we have R somewhere now this R Points to another node corresponding to the third character which is character y and here is and is again marked false now here we again have a array of size 26 and corresponding to this character y will again have a pointer which points to some next node and here this is and variable is marked as true because this y this character y marks the end of this word fine so we simply started with the root node we created another node pointer to which I stored at this location corresponding to the character T and I moved to this node and I repeated the process for this character as well until I arrived at the last character where I simply marked the is and variable to True here because this is the ending character so this is how I store a word into the try so let's say I want to now the in the next try I want to insert TR this is also a word how would I insert I will start with this root node now this is the root node basically and I will simply check if T is there or not so because I want to check for T I can see that t is present here T points to the next node so I move to this next node now I check if this next node contains this r or not you can see that this contains r that means this node or the character corresponding to this node marks the end of this word and just to insert this word I simply mark this is and variable to true I turn it to true now I also have TR into the try let's say I want to insert t r y t r i e I want to insert this so I will start with the very first character which is T and I will start from the root now this root contains this tree I can see that it contains this T points to the next node I move to the next node here in this node I can see that I also have r now with this R Points to the next node now in this node we have do we have I no we do not have I that means I create another pointer from here from R which so I create another pointer from this point like here we may have somewhere we have I somewhere and this I points to another node like this I create another pointer corresponding to the character I so this pointer points to another node corresponding to this character e so I is stored here and here we created a node corresponding to the character e now in this node we again have an array of size 26 we again have is and variable now here we can see that e is the last word of this e is the last character of this word now again we create a pointer we create another node to which this pointer plays at position E points and we mark this node as the ending node so we mark it as true because e is the ending character fine so in this way a word is inserted in the try so let's jump to the code implementation part so this is the try class so let's create a node here so here we will create a no struct node let's call it try node and here I will have two things the first is a pointer of type struct try node children which will be of size 26 and a Boolean variable let's call it is and we also declare a root node here so try node of this type we create a root node here now this root node is accessible in all of these functions and Constructors so here this is a try Constructor so in this Constructor we simply initialize a try so we create a try new try and we initialize this try node to this root node which I created here fine in this case we initialize this root to a new try node okay so we created try node here of this type and we initialize our root with this new node now this root node will simply contain the First characters of the words which you want to insert so let's we will we are here to implement the insert functions let's implement it so to insert a word here given we first create a pointer to the try node so let's call it P initialize it with the root iterate over the word check if the current character is there or not if the current character is null that means it points to none of the node then we store this character into the try so C minus a we simply call it new try node because the current character points to the next node of the drive and we move to the next node which we have created and finally when we have we are done with traversing this word we simply Mark the ending variable to be true because the last character marks the ending of this word which we are trying to insert fine so in this way we insert our word into the dry data structure so let's implement the next functionality that is search so let's see how we can search a word into the try so this is the try which we have builded and this try contains two words three words try t-r-y t-r-i-e and t r so three words try t-r-y t-r-i-e and t r so three words try t-r-y t-r-i-e and t r so let's say I want to search for try I want to search for t r y I start with the root node I check the pointer corresponding to the very first character which is T here so here this root must contain a pointer to T so it do contains a pointer Now we move to the next node to which it points which is this one and here we are expecting a pointer corresponding to R so we again have a pointer corresponding to R Now we move to the node to which this pointer is pointing and here we expect a pointer corresponding to Y again we have a pointer corresponding to Y which points to another node and we also expect that here the is and variable is marked true and we are and indeed it is marked true that means TR y exists in the try so we return true from here that's all we have to do if this does not marks the end or probably let's say I want to search for t r y e like this now from y from the node corresponding to this y I can see that there is no pointer which points to disk character e we do not have any such pointer because here we can see that here in this node the pointer corresponding to e will be null that's why for this type of word we return false okay and because here this is and the is and for this is marked as false fine so let's jump to the code implementation part so here we want to search for this word into the try so let's create a try node let's call it P initialize it to root now iterate over the word just check if a particular correct on which we are standing do not exist in the try if it contains a null that means we return false from here otherwise if it contains a pointer to the next character we move to that next node and at the end we check if this is and is marked true or not we return that like P Dot fine so that's all let's jump to the next function which is starts with function now this function basically expects us to like Implement a functionality whether a given we are given a prefix let's say we are given t r i we're given t r i and we want to check if there is a word which contains Tri as the prefix so you want to check for it let's see how we can do that we Traverse this word we start with the very first character which is T we go to the root node and we ask whether there is a pointer corresponding to the character T here in the array and yes we have it now we move to the node to which this pointer points which is this one and now we also move to the next character which is R now here we are expecting if we have a pointer corresponding to the character or yes we have so we move to the next node to which this pointer points and here finally we are at this node we are expecting if we have a point corresponding to the node I to the character I yes we have a pointer corresponding to the character I here so we move to the node to which this I points and finally here I want to check if this is and if the is and that means we have found all of three characters of this world that means there must be at least one word which contains this try which contains this prefix Tri so we return a true from here fine so that's all let's just jump to the code implementation part so this is the starts with function so let's take a try node let's call it P initialize it with root iterate over the prefix so I check if the current character is present in the prefix or not if it is present if this if we have a pointer corresponding to the current character then that means we simply move to that one so if we do not have a pointer so if we have null for any character then we return false right from there otherwise we move to the pointer to which this character points and at the end we return true because we have found the prefix in the given try fine so that's how we implement this functionality let's submit it okay compile error okay we are not removed we have to do it okay children C minus a let's run it accepted let's submit it okay it is accepted so that's all let's just discuss the time complexity for the give let's discuss the time complexity for the functionalities which we have implemented here so let's see for the insert we can see that for inserting a given word we are iterating over the word of this try so let's say the word has a length of K then that means that time complexity to insert a word of length K would be big of K okay and let's see the time complexity for search so to search a word in the drive we are iterating over the word and if the word has a length of K then the time complexity will be of big of K similarly let's say we want to search if there is a prefix if there is a word with the given prefix and the prefix has a length of K now we are iterating over the prefix and that's why the time complexity for that would be being of K okay because moving from one node to another node is a constant time operation so the overall time complexity will be big of K where K is the length of the word which we are passing to search or to insert or to check if it if there is a word in the try with this word behaves as a prefix fine so that's all these are the basic functionalities of a typical try data structure although there are a lot of other applications which we'll be discussing in the upcoming videos so that's all for this video if you like the video then hit the like button and make sure to subscribe to the channel and stay tuned with me for more videos on the tries we'll also be solving a lot of problems on the tries so I hope to see you all in my next video
|
Implement Trie (Prefix Tree)
|
implement-trie-prefix-tree
|
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
| null |
Hash Table,String,Design,Trie
|
Medium
|
211,642,648,676,1433,1949
|
554 |
hello guys welcome back to the channel today we are solving another lead code problem that is 554 brick wall before jumping into the solution I would highly recommend you should read the problem statement on your own and give at least 15 to 30 minutes before jumping into the solution let's get right into it what problem is asking that you need to draw a line that passes through the minimum number of bricks and bricks are one unit in height but their length is different they are one unit height but their length is different and they are in and rows what you are asked is that you need to draw a line that passes through the minimum bricks so let's see a example and try to understand yeah as you can see it is just this test case image what you can see is that while let me change the pen color which color would be this would be more visible while making this line you can see it passed this and this one and also in the problem it is written that if these are two for example bricks if the line passes through this it doesn't count any of the bricks still that's what happened in this case These Bricks these six bricks are not counted as intersected you know the reason why written in the problem so how to approach this problem the very important question how to approach this we have understood this much that this is that but how to compute this that using the programming language you can see if we write this three one two one three two four three one two what you can see is if we make our problem something like that we are concerned with this the joining of two bricks isn't it or not our major concern is this position we need to find this position because why because when the line passes through this it doesn't intersect any of the blocks or the bricks it doesn't intersect any of the bricks so the whole focus should be on this that this we have to get this position at maximum we have to draw a line at this position where bricks are intersected as much as less possible we need this position Now problem boils down to this we need to find this position we can find this position how basically if we draw this I am drawing this structure in bricks this structure Index this is one length this is to length and another one was to again two length and again one length am I right now yeah zero one two three four Did It Strike something did it strike something we have r as at 1 we have at H2 we have Edge at three we are not counting this and also not this only these edges we have Edge at one not Edge the meeting point of two bricks at one two three isn't it what we required that we want this joint now the problem boils down to this count the joints from the joints according to how we have one index two index three index we just have to count how many are present at one index at one position how many have this at two width position how many have this at three eighth position how many have this now the maximum we have this in whichever index we have maximum of this we got our answer because how if maximum let me draw it again if maximum are passed like this and we have this much row N so how many blocks did we crossed n minus 3 in this case in this particular case isn't it or not that the problem boils down to this index the index where these blocks joint also I have converted that index into this as this is also unit 2 also this is unit 2 but if you write it like an on inter number line you can see for yourself that at one index we find this at this index we find this at that index we find that three meeting points now you get it how to count the frequency of B's position at the certain index using hash map I hope I was able to make the intuition very clear and reproducible in the interview so let's get into the elbow our elgo is very basic that we will fill the hash map would be like in comma int this will be the index this will be the frequency of that of this at this particular index and another thing would be hydrate that hashmap and find the maximum find the max frequency and at last what to do whatever this the number of rows n is number of rows minus this the thing which we found let's call it X we have our answer let's try to take this it will be a hell long example two to one three two one not three one two one three two four let me drag this test case over here why I'm scrolling up and down again and again copy that's it now it's clear one three two four three one two foreign X so let's see how we gonna calculate is we take idx0 for every row we will take idx0 okay let's begin at index one at index 1 we have one now one plus two it's three at index three what we will have at index three we have one and three plus two five at index five we have what do we have one five six at index six what we have one we will not consider this one six sixth index we'll see again index is 0 we calculate this 3 it's changed to 2 4 a new entry form four plus two six now six is two my bad we I have just taken six is the last one we are not taking six my bed six we are not taking six my bed I just forgot myself you are not taking six that's why I even looked at the code that yeah six no we are not taking six again the next uh row one two one plus three four it's now two and four plus two six and last we are not taking we are taking up to this much only two to 1 2 plus 4 now we are also not taking this three is two three one no four three six we are not taking this the maximum we are getting is three how many rows we have one two three four five six F six rows we are getting three max did I just messed up somewhere one plus two three plus two five one we are not taking this three goes to two four it's four is also two we are not taking this one it's two one plus three four it's three and four we are not taking this two plus four six three how many times did we got three I just forgot to write the last test case that's why one it's three one plus three four it's now to four plus one five hits now two the maximum that we are getting is four or minus six it's two and again I am repeating that we are not taking that last because we don't want this here it is it's nothing we want bricks in between the bricks so I just messed up over here I was saying that but I did write it will not take that and also for every row we will do a reset of the index it's like a prefix you are storing prefix in the hash map I just build a whole story over it so that you can have a intuition as well as a reproducible logic at the interview so let's see the code let me Zoom it a bit yeah we are number of rows Max brick zero index idx as discussed the unordered map Edge frequency as name suggests just iterating over it for every row index is uh reset to zero prefix sum or the edge and putting that inside the frequency map and after that just calculating the max as it's a map not as normal Vector it's a container so that's why I T dot second because map has to entries first is the key second is the value so that's much very understandable again and here what we are doing as discussed maximum bricks minus the number of bricks you get the minimum bricks that are intersected or the bricks that are intersected you can even think as the number of bricks that are not intersected minus the total rows you will get the bricks that are intersected so you can even think like that so let's submit it and see if it is running or not yeah it is running quite fast so I hope I was able to make you understand the intuition and you did learn something if you did consider subscribing to my channel liking this video and you have to do what you have to do so keep grinding and you guys are awesome see you in the next one bye
|
Brick Wall
|
brick-wall
|
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
Given the 2D array `wall` that contains the information about the wall, return _the minimum number of crossed bricks after drawing such a vertical line_.
**Example 1:**
**Input:** wall = \[\[1,2,2,1\],\[3,1,2\],\[1,3,2\],\[2,4\],\[3,1,2\],\[1,3,1,1\]\]
**Output:** 2
**Example 2:**
**Input:** wall = \[\[1\],\[1\],\[1\]\]
**Output:** 3
**Constraints:**
* `n == wall.length`
* `1 <= n <= 104`
* `1 <= wall[i].length <= 104`
* `1 <= sum(wall[i].length) <= 2 * 104`
* `sum(wall[i])` is the same for each row `i`.
* `1 <= wall[i][j] <= 231 - 1`
| null |
Array,Hash Table
|
Medium
|
2322
|
37 |
hey um how's it going so today we're gonna do leeco 37 sudoku silver to write a program to solve sudoku puzzle by filling the empty cells of sudoku solution must satisfy all of their following rules each of the digits one to nine must exactly once appeared in each row and exactly ones in each column in exactly ones in each three times three sub boxes of the grid so the dot character indicates empty cells so um notice that in the input it's not actually numbers there are strings of numbers and your output should be um a failed sudoku but here it says that do not return anything modified board in place instead so okay um to solve this problem you have to um think about how human beings solve the sudoku uh by hand so for me like i will go to an empty cell then i will try to try test number one to number nine and uh for example i will try uh test number one here and i will see if one already exists in the row if it's one already in the column or one it is already in the subgrid and because it's it is not so i can template temporarily place one here and i move on to my next uh next one and i will try uh from two here because i already placed one here so i will try two here and i will try if to try to see if two already appeared in the row in the column and in the empty cell it does not so i put two here and so on and so forth i go to the next empty cell and try number one to nine and uh and this and uh try to fill the array if at some point i cannot fill the number then it means that probably means that in the last step the one i placed here probably was not right so i would probably go back and then change it to two and try uh the rest of the empty cell again so that's how uh we as humans solve the sudoku problem and that's exactly actually what the computer do uh this problem as well so basically in the algorithm you just need to loop through the cell and find an empty cell and in each empty cell you try number one to number nine and try to see if the number already appeared in the row column in the subgrid if it's if it doesn't it's not present then you can place that number inside and you recursively uh check the rest of the board and uh yeah that's it so um so this problem is not actually that hard so like i said we need to find the empty cells right so we write for loops to find to traverse the board and if we find an empty cell then we have to check if uh if that number already appeared in the row column and uh in the subgrid right so actually um we can write it as a helper function let's name it is valid so we pass in the board um we pass in the position i and j and we pass in um oh so actually we need to try uh each of the numbers so for let's name it num number string and also it's actually one to nine for each so f if there is an empty cell we loop through we try each number and we try to see whether that number is valid if it is valid then we can place that number in the board position at this point because it's valid right and we recursively call the our function that we just wrote on the new board because the board is updated right and remember the sof sudoku the main function only has one parameters the board if this one returns true it means that it's solvable for it's is solvable then i can return true if it's not solvable i will place it was dot again so basically i backtrack and the number doesn't so the number whatever number we are testing it is not going to work at some point so we put the num we put the number back to empty and we wait for the next for loop to try another number if we are have empty cell and i tried everything and it doesn't return true it means it's impossible to fill the empty cell within valid number at this point i can return false but if at the end of the or the whole thing i haven't returned true or false it means i am at the end of the um the grid and then i can return true so again you loop through the um entire board and find the empty cell and of you try any number from one to nine and if that number is valid you can temporarily place the number um in the board and you recursively test whether the rest of the board can be solvable if it's it can be solvable then return throughout otherwise you place it back to the empty cell and wait for the next iteration to try another number if i tried for if i for an empty cell i tried everything um every number and it's still not possible to fill out the sudoku board with valium number i know that i can like there's nothing i can do i have to return false it's impossible otherwise um at the end of the if i am the at the end of the cell then and everything seems fine then i can return true so that's our main function let's try to write the helper function called is valid let's name it row column so is valid so basically we are checking whether the number string is uh has no duplicate in the row column and the subgrid right so first of all let's check the row so this is because remember we are passing our position here so we know our current row in current column right so we know our current row so for the row we only change the column from zero to eight and we try to see if there is already a number that is equal to our attempt number right if there is already a duplicate then we have to return false so next we
|
Sudoku Solver
|
sudoku-solver
|
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid.
The `'.'` character indicates empty cells.
**Example 1:**
**Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\]
**Explanation:** The input board is shown above and the only valid solution is shown below:
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit or `'.'`.
* It is **guaranteed** that the input board has only one solution.
| null |
Array,Backtracking,Matrix
|
Hard
|
36,1022
|
442 |
hey guys how's everything going this is jayster uh today let's take a look at 442 find all duplicates an array given an array of integers some of the elements appear twice n is the size of the array some elements appear twice and others appear once and all the elements appear twice in this array well i think i did something submitted before about find the duplicates it's uh it's a nice trick is that keep swapping um so when we meet a number just uh try to swap it to the right position like we have array like this right so what we do we just search we just loop through the elements from uh index one zero so we find a four so obviously four should not be here right he should be at the uh one two three four should be at the position of seven so we swap them right so this position one is not settled and we have three two we swapped so we have four and then a two three one right and then we keep uh looping on the first animal is seven we should put it at seven right so the seven is uh here three so what we got here is three two four eight two seven one and okay so the first end becomes three it's still not the right position we swap it with one two three so we got two three okay here right yeah so now three four seven are at the right position right and now we got two so we want to we need to swap three again so what we got three uh three two three something like this you can still this is not the right number right so we swap it to three we meet three again when we swap three to these three we find that okay there is already a three at the right position so yeah we are trying to put three at the right position but there's already a three the same numbers at the position so this is a duplicate right so we ignore it so three is our target right so three is uh is duplicate so we skip it so we don't we do nothing and we find three and three oh two three four now we go to eight we got one right one two seven eight now we check one okay one is here um so this is a problem okay we check one we got three but three is already uh is uh invalid i think i should mark it as uh um is as a duplicate so i should just put that putty there so one two three four we do nothing and we three two seven eight right three is already collected this number we know it's duplicate so we do nothing because we're switching numbers from this position to another position and it is three so yeah we could just uh ignore swap it and ignore it and go to next one right because next number couldn't be here or could of cour or could uh if could we could just do the same right because three is our target so our solution would be keep swapping to the right position if same number meets then duplicate when duplicates we do nothing right okay so we find these three we're trying to put it to here because it's stupid okay we do nothing cool so this is it let's try to do it okay we uh keep track of uh results to keep track uh to put hold all the duplicate numbers and then for that i equal zero okay the index actually start with the uh base one from one right uh here we start with zero okay um i'll say while uh numsai which is the number is not i plus one so the first number if it is not one well try to put it try to swap right so we need to the target equals um nums i we need to put numbers i to um i plus one no we should put num if it is one we need to put zero yeah nums i to numbers i minus one at the index right so if the it's the same we find uh as we analyzed if the uh we have a duplicate number right because some exact twice there's no third times something like that okay so the number at uh target position would be okay no the uh right index would be nums i minus one right if nums if the target number to swap is the same if it is our number which is uh nums i then we find how do you pick a number right which is number itself and then we could uh we already find it so we need to break right yeah we need to break so continue so we break cool and if it is not we need to swap it which means uh nums i nums writing next equals nouns write index right mums i cool so we swapped and then keep check right so finally we will find a one or three and we go to the next one and do the same so yeah that's it i think result before i run a code let's allow me to review my code one more time yeah so uh for the input for the example here okay the initial case would be like this right so we go to zero four and then because four doesn't equal to one right we will continue this formula and it gets right index which is four uh here three zero one two three seven because it's not the same we swap it swap doesn't okay and then we continue this check three okay um oh okay seven three two three this until here it's right and then we swap three two three okay it's right and now we got three the target should be two it's the same right it's the same so yeah we should put three here and go to two right okay something here yeah all right wait a minute three yeah go to two hmm wait two three okay three two okay and we found it so we break go to two again here and then two should be put at two itself so it's at it is at the right position so we should skip to d3 right so it should be uh we should um wow because it uh here why look because it is not too yeah it is our a target so we continue to next one go to three here and it is so we go to four and four it is so we go to one it is not we go to one three and check three again and find it uh here's a problem when we find a three we push it so the result actually will be two threes in it right this is not good i use a new set so add it okay now we go to two is two okay we add it so three two in it the output is does the order matter i don't know that's just to return the uh the result oh accept it so actually the uh the order doesn't matter let's submit great so the time complexity for this one actually um time we just do swapping so this is uh um this is uh linear time we traverse through our index and while he's afforded but actually every time if we continue this while actually it will reduce another while loop right so if we swap one elements here like four swap to here then when the i equals four then we the white of b is gone so actually it's linear time right yeah so totally it's linear time space yeah we use the set here but it's the result so i think it's it should be constant how can i say um yeah at last we need you in linear space right so this actually doesn't matter so it's constant time auxinary uh constant time cool wow this is a new feature debugger what is this oh wow this is cool this is the first time i see it okay let's say add a debugger here what's gonna happen no oh cool man this is cool um this is cool wow looks cool just cool okay so that's all for this problem hope helps see you next time bye
|
Find All Duplicates in an Array
|
find-all-duplicates-in-an-array
|
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1,2\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
* Each element in `nums` appears **once** or **twice**.
| null |
Array,Hash Table
|
Medium
|
448
|
1,706 |
Hello friends today I'm going to solve lit code problem number 1706 where will the ball fall it's a medium uh level difficulty and this came on daily uh challenge only code so what's the problem let's see um so we are given a grade two by two grid and we are given um n number of balls so the number of ball is equals to the number of columns which means that from each column one ball is uh throne and then we have to find out if the ball is able to reach and come out of the last call of the last row or not so uh what have we given is a value one and minus one a value one means that um there is a diagonal span on the um on that grid on that cell which spans from top left to top right so if the diagonal is spans from top left to top right on that cell then the column value is one if spans from top right to bottom left and the value is -1 so let me just show you the value is -1 so let me just show you the value is -1 so let me just show you here with some um examples here we are I'm using the same Creed so the value here is equals to 1. this is also equals to one this is minus one since it spans from top right to bottom left and then this one is minus one now we have to see if the ball is able to reach the end and come out of the end or not so we are also given conditions like if we reach a v they're a valley then the ball is stuck there so the ball cannot reach the end which means when are we reaching a valley this is when we reach a valley if we have a one and a minus one also we reach our Valley if we have a minus one um a minus one and no so if we have a one and minus 1 we reach a valley so one comma minus one we reach a values which means that we cannot reach the end because one what happens in one so when we drop a ball here this is pushing to the right but again when this ball is goes to the right hand side when from the right hand side because of the slant it is pushed to the left so which is cannot move anywhere so this is where the ball is stuck and when is the ball able to move through the grate the condition when the ball is able to move through is when we have a one and a one so these two grid have a one and a one right that is when the ball is moved able to move through the gate so when we have a wand and a wand we are able to move down over the grid also when we have so this grid is a minus one and this one is also minus one and you can see we are still able to move down the grid right so any row if we have on the same row we have a same value uh for both The Columns then we are able to move down and if the values are different then we are stuck so that so we are going to use these um for make for coating purpose so let's get started I'll just do start with the coding so let me Define m which is supposed to create length and which is equals to create the number of columns and let me Define the result array because we need to return our return the area of results um yeah now for each of the balls so for each of the balls I'll Define it with a value k is less than n because the number of poles is equal to the number of columns K plus and now uh every time we for each ball we are starting from the first row so first of all we take ball number zero and then we start from we throw it from the top and it lands the row zero and then it proceeds downward and for the second ball B one we do the same thing right so I we are always starting from the first row and the number of column J is equals to the um number of ball we are throwing so b0 falls from the um column number zero B1 Falls from column number one but the end result could be different zero could uh come out of column number one so that is what we need to find out now uh while so what are our age cases if we are stock right if we are stocked and we return minus one if um J exceeds uh either of these balls so if J goes beyond this ball or goes deeply on this ball which means that we are stuck again so if J is um so we Are Gonna Keep moving so what are what we Are Gonna Keep moving as long as J is less than and right also for the case of I because we will be updating I as well so um which will be in our age case because um m is the length of grid right so we drop ball from zero and we want it to come out of row four which means I am while m is I is less than M we keep on moving and when I is greater than M which means that the ball was out of this column so that is when we and I've come out and then we push our result G which is the row and we are pushing it if I equals to m so now here if the value of J is oh great i j is equals to one equals to 1 which means that we are going to the right because if it is equals to 1 we push to the right the ball is pushed to the right so uh J plus and then if that create if J is greater than or equals to n which means that we have gone beyond this boundary or if grid I J equals to minus 1 which will give us a valley um that is when we push to our result -1 and then we break push to our result -1 and then we break push to our result -1 and then we break from the loop that is we break for that ball and then we continue with the next Ball but if in case similar thing we are going to do actually the similar thing equals minus one then we are pushing to the right so this is minus one so we push to the right so J equals to minus one if in this case J is less than zero which means that we have gone beyond this boundary again or the value of great e is equals to one then response Dot result.push result.push result.push minus one and then we trick yeah we also need an else condition else when um else we um we are able to move forward and then increment I now let me hold great okay so here's something wrong and what is it cannot read property undefined oh else we need an else here great so thank you for watching and talking about the time complexity would be since we are we have one for Loop which is equals to n and again one while loop which is either equals to n or M any one of them being greater so our time complexity is off and squared and the space complexities of n because we have a response array here all right thank
|
Where Will the Ball Fall
|
min-cost-to-connect-all-points
|
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`.
* A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`.
We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box.
Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._
**Example 1:**
**Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\]
**Output:** \[1,-1,-1,-1,-1\]
**Explanation:** This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.
**Example 2:**
**Input:** grid = \[\[-1\]\]
**Output:** \[-1\]
**Explanation:** The ball gets stuck against the left wall.
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\]
**Output:** \[0,1,2,3,4,-1\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `grid[i][j]` is `1` or `-1`.
|
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
|
Array,Union Find,Minimum Spanning Tree
|
Medium
|
2287
|
84 |
guys welcome to the tech grant today we are going to solve the problem of largest rectangle in histogram do like subscribe and share the video subscribe to the channel to get further notification so the problem is given n non negative integer representing the histograms bar where we have the width of each bar is one find the area of the largest rectangle in the histogram so we have an input array like this and each of the element of the array it represents the height of the bar so as we can see from here the largest rectangle can be formed by this tower 5 and it will be of area 5 into 2 because each bar has width of 1 as given here so this 5 covers 2 bars so basically with this 2 so the maximum area here is 10. so before going forward and understanding the tactic how we can approach this problem let us see some of the cases so we can have a histogram like this which is nothing but this histogram we can have something like this where the rectangle the largest rectangle is formed by this horizontal rectangle the largest area basically is under this horizontal rectangle we can have something like this where we have a gap here and then this forms the maximum area under the rectangle of this histogram and we also can have a cases where we have like the single bar itself forms the maximum area let me show you one more example i just copied it from google so it can be something like this where the maximum area comes from this horizontal rectangle which starts and end at the starting and end point of the histogram bar so like you saw in these example you would see that you have to traverse the whole array list to get the complete area and you need to move forward and backwards to get the uh get the value of the histogram and to find the area under that particular histogram so the approach in this case or in similar case where we have to solve similar kind of problem is to take a stack basically so you can simply put your elements in the stack and as and when required you can pop out and apply some formula to get the area under the histogram or to compute any of the stats where you have a similar kind of problem so the formula here we are going to use will be we need to get the height of the bar basically and then we need to multiply it by some factor like for this particular answer you multiplied it by 2 to get the answer because this is the biggest rectangle so let me share that formula with you so the formula that we are going to work with is something like this where every time we encounter a bar from this histogram we push it into the stack so when we have to calculate the area we will pop from the stack that we are going to get and here you see height so this i'm assuming that height is the name of this input array that we are getting so the formula will be you get the height of the element for which you have to calculate the area you get the previous index so previous index is why we need previous index is because suppose i reached here and then i need to calculate i reached one this starts from zero zeroth element and i have reached one but i need to calculate the area of zeroth element first so in that case i need the previous this previous index and the formula for getting previous index is this if we have anything in this stack we will take the previous index as -1 will take the previous index as -1 will take the previous index as -1 otherwise whatever we have post in this tab we'll pick it up so this will be more clearer once i go through this through the example of this histogram how we are pushing and popping out from the stack it will be more clear how this previous index and current height is getting used and one thing you should observe is that we are not actually pushing the element of this array rather than we will push the position of all these arrows like the zeroth position is position means one position two and ith position and so on so we will do that and the area will be calculated as the current height which we are getting here whatever height is this one into the i minus previous index minus 1 so it will be basically suppose i have reached 2 so i need to calculate the area of the histogram everything before this so if i is equals to 4 so in this particular case i will be 4 so the area under 6 will be 6 into i is 4 minus the previous index which is 3 and sorry in this case it will be 2 and then minus 1 so it will be 6 into 4 minus 2 minus 1 so which turns out to be 1 so area under this 6 will be 1 how it will be let me just scroll down and go through each of the index value so when i start my process the area will be when i is equals to 0 when i started so that time my stack will be empty the previous index will be minus 1 because i'm putting the formula stack if stack is empty i'll use previous index as minus 1 otherwise we'll peak from the stack so in this case previous index will be minus 1 and i won't do anything i just push the 0th element in the stack so here i am not pushing the element corresponding to the zeroth element rather than i'll just push that index i will push this i position here okay and i'll move forward so i'll go to the first position now so when i is equals to one in that case what i will do is i will uh i will peak this position and i will see whether the height of this position is less than or equal to the previous one okay so the current height is less than if the current height of this bar is less than the previous bar in that case we can pop from this particular stack otherwise we'll keep on adding so in this particular case since it's position the first position when i is equals to 1 this bar is smaller than the bar at position 0 so we will pop that and we'll get it as the height so here the current height will be height of the element which is there in the stack so height of and the height of zeroth position here is two so current height will be two for us now once i pop this stack will become empty so the previous index here again this previous index will be minus 1 for us so previous index is minus 1 and we'll apply this formula which says current height into i minus previous index minus 1 so the area here will be when we apply the formula 2 into i where i is 1 for us previous index is minus 1 and minus 1 so this turns out to be 2 and which is nothing but area under the first bar that we are getting so the area under first bar is 2 so this area we can store as maximum area because till now the maximum area whatever we have will be 0 and after that we will push the first element not the first element so the first index into the stack and then we go on to increment our i will go to i equal to 2 now here i equal to 2 the bar is bigger than my i equal to 1 which is the previous bar so i'll just do this check height of 2 is greater than height off i'll peak from here so it is greater so i'll just push 2 into the stack and i'll move ahead when i come to i equal to 3 my stack has 1 and 2 and i will again do the same check i will say height of 3 is greater than height of the stack peak which is the height of 2 basically so height of 2 is 5 height of 3 is 6 so 6 is greater than 3 so we'll again just push 3 into the stack and move forward when we come to i equal to 4 so our stack is 1 2 3 now 4 is the height of i equal to 4 is less than the previous one so in this case again what we will do is we'll pop from the stack the previous index in this particular case when i popped it the previous and the stack will have 1 and 2 and previous index will be this element 2 so the area will be 6 into 4 minus 2 minus 1 which i was showing here sometime back and this six denotes nothing but the area under this histogram this single bar that we have now again we will repeat the same loop like we need to pop from the stack till we have the condition where the bar at the ith position which is 4 is greater than the bar that corresponds to the element of this stack so since the bar at this second element this equal to 2 i equal to 2 which is nothing but 5 is still greater than the bar at 4 so we'll repeat this process so we'll just pop it from the stack so now the height of stack pop which is nothing but the height of 2 will be 5 this will be height of 2. and previous index now in my case will be 1 because i have popped from this stack so the stack had initially 1 and 2 and i popped 2 from it here so this stack has now one so the stack is not empty it contains one so this previous index value is equal to one so now the area will be five into four which is ith position we are at still at position i which is i equal to four the previous index is minus 1 and minus 1 we are doing this x additional minus 1 is that's because i don't want to consider the bar at 2 we are calculating the area which is behind to all the area that corresponds to the element which is behind two or the ith position basically so this turns out to be 10 so finally we will put compare whether the current area is greater than the max area that we have if it is greater then we will replace it with 10 okay so now we are left with one here in our stack so the bar at position one is one which is less than the bar at 2 so i will not pop this one and i will move forward so before moving forward i will simply add this 4 this i equal to 4 in my stack so now my stack will have 4 and one these two element and i reach i equal to five so when i reach i equal to five we have the stack width one and four and again the same comparison we need to do height of five which is greater so height of five is greater than height of 4 which is the last element bond so i will just add 5 into the stack so now my stack has 5 4 and 1 then i will again increment my i will go to 6 now we have added till 5 i equal to 5 so i equal to 6 we don't have anything so we'll consider that the bar at 6 is 0 for i equal to 6 so now since that bar is zero it is greater than the bar at five so i will pop five so the value at five is three so the current height becomes three previous index becomes since i have popped five from here the previous index becomes 4 and the area becomes 3 into 6 minus 4 minus 1 which is 3 now this is not greater than my current area current max area because my current max area till now was this 10 so i can just ignore this and again the bar at 4 which is 2 so this bar is less than the bar that i have got at i equal to 6 which is 0 so i will again apply the same formula i will pop the stack and i will calculate the area now this 8 comes as 6 minus 1 into 2 so basically this 8 is the area if this 2 formed the complete rectangle here starting from five if you see if from five till three everything with height two so there are four blocks one two three four and each of height two so the area becomes eight basically that is the area coming here and finally the last element is of height one so this will be popped and this denotes the complete area of height one but it covers everything from here from the first bar to the last bar this is the minimum one which is present for us so this gives area as six for us six is coming from when you traverse everything from zeroth position to fifth position and height is one so it is six into one which is the area is one and finally the max area that came was 10 for us which came from this five in this particular case okay i hope this is very clear it is pretty straight forward the only thing is when to pop your stack and every time you move forward you push that ith position in the stack so we'll just go through the code once i'll start writing the code so we will say in will keep a max which is zero and in the end we will return max will have an area equal to zero for i equal to zero by less than this height we will say i less than equal to this a dot length because we need to go to one if position more than the length of the stack where we will say that the last height is zero the last height of the bar is zero and we'll do i plus okay so once this is done so we'll say we'll from here we need to get the as for this formula we need to get the current height but before current height we need to get the height of each bar so height of each bar will be if i is equal to height start length which is the one in the end so if this is the case then height will be zero otherwise it will be height of the individual bar okay and then we'll put a condition if the and yeah we need to define once that this is that of integer stack is not is empty and this edge that we have this h is less than where is the formula in this case where this height is less than or greater than in this case we can just reverse it if it is greater we'll just continue if it is less than then we will start popping so if h is less than this right and we say sdk dot p so basically if this is less than this then we will start popping from the stack till it is less so when i reached here i will pop till i have reached one which was the scenario where i equal to four scenario basically when i reached here i popped it till only one was left in my stack so in this particular case i need my current height is equals to so my current height will come from this formula the initial formula so it will come from height and will pop the stack so we'll say current height equal to sdk dot pop and we need previous index and previous index will again be this formula if stack is empty then minus one otherwise be peak so we say sdk dot is empty if this is empty then minus one otherwise spk dot okay and then we have area so area is equals to this formula current height into i minus previous index minus one so this is current index into i minus the previous index and minus one okay so here we have calculated the area and we will say max is equals to math dot max of max comma area so if this current area that i have calculated is greater than my max area then you replace my max area with the current area that i calculated okay and once i am out of this loop so suppose i went first time so if i am not doing or maybe this scenario like if stack was empty or stacked uh the height is greater than the previous height like this case so every time i just go up and i say stackdrop and i put i which is the ith element okay so yeah i think okay so in this case it's 10 and we'll just submit okay so it's success it has executed it in 8 millisecond and yeah that is how you use stack to get the maximum area under any histogram and you can use this data structure stack to solve similar kind of problem like i told initially where you have to move all the way towards the end of a given array and then maybe you have to move back also to check whether the previous value is greater than or equal to or anything wherever you have to move back because you know the functionality of stack when you pop uh it's like lost in first out so it really helps in solving problem like these so thank you for watching the video subscribe to the channel see you in the next problem bye
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
926 |
welcome to august leco challenge today's problem is flip string to monotone increasing a binary string is monotone increasing if it consists of some number of zeros possibly none followed by some number of ones also possibly none you are given a binary string s of zeros and ones you can flip each index to zero to one or one to zero now return the minimum number of flips to make s a monotone increasing so keep in mind that we're trying to make it all zeros uh are not all zeros zero zeros whatever group of zeros and all the way followed by a group of ones but all those have to be ones right so basically uh we can see the length is going to be very big so we're probably gonna have to go with a grease solution of some sort here's kind of the idea of what we're gonna do we'll have imagine that we're um just thinking about this simply right and if we started it at the very end here uh if we said that we're gonna whenever we see a zero we're just gonna increase it to a one like how many of those then are will there be so imagine that we start here at zero um and whenever we see a zero we're gonna flip it to a one okay so basically this becomes one and this becomes two right here and you can imagine like we have what six zeros right so just go backwards like each time we pass one we go four three uh three and then it'll be three all the way to two one zero so what's going on here basically this part here is like going from left to right imagine that we're trying to count the number of zeros that we've seen and we'll and that we're going to flip to a one here because uh if we see a zero starting at the right side we have one we kind of have to assume we're going to flip all these once we want to be all ones at the end right so here like we go to one we flip we see one zero before so it's gonna be one two three four all the way up to six so that would be like if we started at the very right and moved all the way to left whenever we see a zero we'll just flip it to one in the same way we're gonna move left to right but this one whenever we see a one we're going to flip that to a zero and that makes sense because if we thought about the other way we want to just make sure whenever we see a one we're going to flip it to a zero right so at the beginning it's going to have nothing we just go zero and here we see a one so we flip that and flip that here and then this continues like all the way down and i actually think it's going to be more like this one two like that so if we just combined sum these up right well this is kind of like the cost of each one three four three two and imagine like okay we want to take the minimum from this summation like from each one of these index points and why is that well you kind of think about it like this side's going to be trying to flip all the zeros to ones and this side is going to be flipping all the ones to zeros and at some point we can imagine if we meet uh we want to minimize that number right and we can see here like if we actually just flip all the ones to zeros that's actually going to minimize here because forget this we just want to move all the way to the end and that's going to be two right here so that's gonna be the answer in the same way like imagine all these were ones like this like what would it look like then uh well that would mean this starts with zero and this just moves all the way here and we go with c is zero right so now it's two one is all right so three uh yeah nope my apologies this would be 2 1 0 like this and in the same way this would be what 0 one two three four five and what would be answer here then be three four five six seven eight seven six five here we can see the minimum is going to be three and that basically means well it's better to turn all these to ones so just make this you know let's say you think about like a monster going this way trying to make all the zeroes to ones and i'm also going this way making all the um zeros to ones and ones to zeros like this way uh so basically like at some point it's going to be minimized here with these two examples like we see at the very end that's actually going to be the minimum so it's just better to turn all these to ones and don't flip any of the ones to zeroes and that way this can be three right here so uh hopefully that kind of makes sense it's kind of weird why that works but um all we need to do then is let's first count up all the zeros that we see we're gonna flip all those to ones and all the ones that we see so this would be just like s count of all the zeros and this would start with zero here and we'll have some sort of output here we'll just start with zero because at the very minimum we know that could be an answer so four digits in s we if the digit is equal to a uh a one i'm sorry a zero then we're going to decrease our zero here and if the digit is equal to a one really i can just do it else probably but just in case we'll say one we're going to flip it to a zero so plus equal one like this so each time we want to store the minimum output here so that's going to be minimum output and the zero plus one finally just return output and this would actually work this would be o event time let's make sure it does this should be one here looks like that's working and there we go accepted so of n um and space complexity would also be of n or i'm sorry one i believe although i'm not totally sure no pretty sure it's so it's constant space and it's just o n time complexity now full disclosure i did not come up with this solution like i thought this was very clever it's pretty amazing to be honest i struggled with this one i knew it had something to do with moving forwards and backwards i just couldn't figure out what it was um you know i'll have to admit it's been a little bit discouraging the past couple days but i think you can't really think like that just have to move forward and just do your best and keep grinding all right thanks for watching my channel remember do not trust me i know nothing
|
Flip String to Monotone Increasing
|
find-and-replace-pattern
|
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the minimum number of flips to make_ `s` _monotone increasing_.
**Example 1:**
**Input:** s = "00110 "
**Output:** 1
**Explanation:** We flip the last digit to get 00111.
**Example 2:**
**Input:** s = "010110 "
**Output:** 2
**Explanation:** We flip to get 011111, or alternatively 000111.
**Example 3:**
**Input:** s = "00011000 "
**Output:** 2
**Explanation:** We flip to get 00000000.
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
| null |
Array,Hash Table,String
|
Medium
| null |
110 |
yo what's up everybody how's it going so guys today we are going to solve the another coolest problem which is balance the planetary yeah you listen right we have to balance the pantry let me just open my uh this thing so i will help you to teach very easily using pen so it worked like pen paper which i really like all right guys so what we are going to do today is uh so we have to solve this balance binary this problem is quite simple so it's nothing very difficult so basically what we have to do we have to check whether the tree is balanced or not okay so we have just given a balance factor so by using that balance factor we have to create a uh like we just can create one formula balance factor equals to left minus right all right so if this will be equals to one then the tree is balanced so like how this thing will work in this one is for example let's say uh we are this is our root all right so we have to check is this balance so it has to be one for that okay we have to check is it one all right so let's check so this is over here only one node okay and over there it has one node same this 20 has one node and this three has 20 it's a one node so one plus one two all right so two minus one will give us one all right so yeah this tree is balanced so that's what we got in our output as well as true all right guys so there is like a two way to two ways to solve this problem so one is uh we called top down approach all right and the another one is called bottom up approach all right so i will gonna tell you the both of them so i and i will tell you which one is good like according to the time complexity and all that so first of all we will use the top down approach so top down approach basically whatever it means by its name like we are going from the top to the down okay we are going by its height so that's what we're gonna do in this one all right guys so let's get start so first of all we will create our base condition if root is equal to null then we simply return what we return we simply return true yes now what we do we will create a height function for this so that we can calculate the height all right and i will code node over here all right so yeah so what we do i will just create one base function over here as well if we root if sorry not be quiz note so if not is equals to null then we simply return zero so zero being like kind of true because integer we can't put in integer we can put true so we have to put zero like that right so now i will calculate the uh max which one is left to right which one is max method max by using that so i will say height no dot left and for the right as well all right and i will add plus one to it what why i add plus one to this one because you know that uh three so this one will counter as one as well so this will count as a height as well all right so let me just uh calculate first it's a balance factor so how we're gonna calculate this i will use math dot absolute difference function to calculate that abs and i will say uh height root dot left okay minus height root door right and i will check if this is greater than one then i will simply return false all right i hope this thing makes some sense so let me just move this to over there right so yeah so this is what we did so i written false and after it i will simply uh return my this end function i've written my height function as well so i will say return is balanced root dot left alright guys and is right all right let me just give a run hit let's see is this working or not is there any compilation no it's good so uh i hope this thing makes some sense all right so if you like look at the this question is download because it's not balanced because if you carefully see this three has a balance factor of one this and this one has a balance factor of two so this one is not uh like it's not balanced because of the height as well uh because you know the height by the left and right so it's not balanced so yeah let me just submit it let's see all right so as you can see uh it's about 48.50 why is because the about 48.50 why is because the about 48.50 why is because the time complexity of this is o of n square so let me just uh show you the time complexity is o of n square why is that because we are going level by level to the downside okay so it's k uh it's consuming too much time over there all right guys so to solve that we have the bottom up approach so bottom up approach basically has a time complete of o of n so we will do that one now as well all right so let's move to the question let me just make it as uh normal all right so now what we're gonna do is we will go for the bottom up approach all right guys so let's just do this similarly we will create our first base condition if root is null then we simply written true all right guys now what are we going to do i will just again call the height function similar to that and similarly i will create one base condition for this one as well all right guys now what i will gonna do in this one is i will just simply say like uh okay let's calculate the height of left so how we gonna do is we will i will just simply put height no dot left similarly i will do for the right as well so just be bear with me so you will gonna understand like how what's going on in the court so you will easily understand it's not too hard this code is not hard all right now what i want to do is i will calculate my balance factor in this so i will call one function we name balance factor all right and i will say uh math total absolute difference okay uh and over here i will simply put left minus right all right guys and finally i will check the condition if i have to check if the balance factor is uh greater than one so if balance factor is greater than one okay and i have to check if the left is a minus one or the right is minus one if so that then we will just uh rewritten force from here so i will give that condition as well to this one so i will simply return minus one over here because minus one itself is like kind of false in this one all right so finally i will return my uh method max in this i will say method max of left alright and lastly adding plus one don't forget to do this and i will over here call my height function i will say written height root still not equals to minus 1 if this is not equal to minus 1 then we will do it let me just run this code so we got something over here balance factor okay i think the we did something wrong yeah here we go so let me just give a submit so this one is we'll go for the i think 100 yes as per expected so guys i hope you understand the question and the solution so i use two approaches top uh down and bottom up approach so you can use any one which one you like but just make sure all the time complexity the interview you're asking so you can tell the time complexity so which one is good all right guys so thank you guys for watching this video i will see you in the next one till then take care bye and i love you guys
|
Balanced Binary Tree
|
balanced-binary-tree
|
Given a binary tree, determine if it is **height-balanced**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,3,3,null,null,4,4\]
**Output:** false
**Example 3:**
**Input:** root = \[\]
**Output:** true
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
104
|
502 |
So how if you all do not want to be taught well then we will try to learn these things and whoever sees the pattern in it will absorb it and remember the pattern. If we say pattern then it means on this pattern, we will see more questions of this type and we will try. Okay. OK, you have to read carefully. OK, Projects on project, you increase its capital, Distinct projects of projects, Project have complete products and a minimum amount of capital, I need you to start date project, these are the same words for everything, I have not given sir, profit and same capital. Date c need to start d project ok initially c have and capital mains key and profit p and capital and equal to current capital debt mains i can select d current project and after complete un finishing d project so in simple words just given two meaning project There will be a capital and there will be a profit. So, if our capital is either less than or equal to the current capital of the project, then we can transfer it to the plate and after doing the plate, its profit will be included in our wealth. It will be fine. Okay, distinct from given project, you have to select maximum final capital and return. Let's have maximum capital constant 's value from 0210. Let's run it in the first example. Okay, so first example I I I can select the capital whose capital Is Yadav less or equal than the current capital? Can I select the project? What is the profit of the first one? Van OK, zero plus van means it will become van. You can see, I have two options, this is fine respectively, in this way we have done our driving. Pass is the starting W, which products can I select from it? Okay, what did I do from that? I have picked the one with maximum profit. Okay, can you think of it? Which can be the best project Projects Available To Be Used For Current And Wealth Profit Meaning Can I Do That To Keep All Those Projects That We Need To Be Used For Current And Wealth Profit, Then We Will Move On To The Video For That I Do Less, I am Taking An Example From Achha Okay, the first thing that comes in our mind, what can we do? What should I tell you about the Starting W Equals Tu Zero Man? Okay, so which is our study capital and okay, so which products can I select from them. I will be able to select only those products whose capital is zero or less than zero, Euro or less than zero. Okay, then I will select the project whose capital is zero or less than zero, whose profit is maximum. Sangeet] Available and Current w Projects are available with you, starting now because I removed it from here, I gave prediction team, now I see whose capital is less than zero, whatever we have available inside the project, I will pick the best one, why? Because the products which are falling within our criteria, I can print them with my current W. Okay, and I will print which one has the highest profit. Now, which is our available projection whose capital is less than or equal to W. Now which one are we selecting? Select the second project because we have already selected one plate. Okay, now that means we have two available project selections left. That means there is no such product whose capital is smaller than van or van. Now something. Okay, so now what will I do in the selection, I will give him priority, I will go to the priority, I will say to me, whose profit is maximum, then whose profit will return our maximum, what will happen in Van Kama Five, what will happen to our current W, 6 months current Joe. Waste plate W is selected, ok so our w6 is done and what is the count of available projects with us, it is done, that is, now I have only one maximum project and can tell, I can take one more max project, now I do. Among my available projects, do I have any such projector whose capital is equal to and be smaller than here Shiksha, we still have any such whose capital is less than six or six, then you will say, yes, this is a project, what will I do, okay now like this Any capital six, that is, now I have to select whatever project I have to choose from the available projects. Okay, whatever we have done, whatever we have two plates left which I can use from my current W. I can do it, I will pick one of the best projects which will have the highest profit. Which leg is your next most profitable one? Earn three vans. Commentary We have the next profitable ones left. What will I do now? 6 + 3 What is not done i.e. our Pass 6 + 3 What is not done i.e. our Pass 6 + 3 What is not done i.e. our Pass current and what has become nine and now we have equals you will become zero, that is, now I can select any other project. Rewind this video a bit and listen to it once again, you will definitely understand that I am shot. Yes, you must have tried rewinding your things. If you haven't understood then what do you do now? Let's do it from now on. Let's move you body part solution of IPO question. I will solve the question whose capital is either less than or equal to my current capital. Sometimes I can select the components for whatever is my present or our given, then whose help will I select from this, will I select with the help of private, will there be play stores or will there be any profit earning capital, will I give all the teams in the starting and that. They will be sorted in some way, the project which has the least capital will be on the top, two projects can be taken with current capital and OK, I can start with current capital, OK, then they will be compared according to our profit. I can select from, which are our available courses and current W, so what am I doing, it will be a project, it will go on top of us, okay I have given a leg, okay all of them, I will not go till then or else If we have considered all our projects and all our projects then our match will not be left. Okay, which we have checked till now, don't even consider it. What will I do if we have because I have some of our projects, children and Which is our today our Dalga reading What will I do Now what is our current W Next period ca n't happen Can you tell in which case In which case is our current W Next available project link What would be the lower term Capital is Okay, what will I do with the current capital, I will break even directly, so mines, profit, capital, okay, so it is saying that profit, okay is depending on two factors, in this case, that factor is capital and ours on a project. Which is the final answer, so what have we done? The second factor is left which is about profit. I am optimizing from that. I am trying to select the best profit based one on which our final answer is depending. So what you have to do is short one factor. You have to do it and try to make the other factors the best possible. Okay, in this way I can make you this type of question answer video or if you have any other question which you want to get solved then please let me know. I will make a video, ok, keep practicing and have fun, take care bye.
|
IPO
|
ipo
|
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects.
You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it.
Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_.
The answer is guaranteed to fit in a 32-bit signed integer.
**Example 1:**
**Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\]
**Output:** 4
**Explanation:** Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
**Example 2:**
**Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\]
**Output:** 6
**Constraints:**
* `1 <= k <= 105`
* `0 <= w <= 109`
* `n == profits.length`
* `n == capital.length`
* `1 <= n <= 105`
* `0 <= profits[i] <= 104`
* `0 <= capital[i] <= 109`
| null |
Array,Greedy,Sorting,Heap (Priority Queue)
|
Hard
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.