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,239 | Welcome to my channel code Sorry with Mike So today we are going to do video number 10 of the bit manipulation playlist, okay the lead is marked number 12 239 medium, already I have given a solution to this problem of this video in my DP's playlist. His question number is two, I think, I had posted it a year ago, okay, we had prepared it from recurs and had also included memorization in it, we had to discuss on the same thing, that is why I thought, I will tell in this video, okay, let's watch. Yes friend, someone has asked, do you already know the question? I have explained it in this video of mine, so definitely watch the solution. You should know that too. The present solution is also very similar. But in this I will teach you extra things, because we are growing slowly, so we should know more things, extra things, smart things, how to solve them smartly, so in bit manipulation, that is why I have included it in bit manipulation. We can further simplify our solution. Let's see how the question is correct. So you know what the question is, then you will remember that I had taken this example and we had made a nice tree diagram and from the tree diagram we can know this. I had said that its maximum length can be four, isn't it? And who were those u and a? Its length was yes. Look, its length is four. There are no duplicate letters in it. Look, none of the letters are duplicated either. It can also be i k yii look if any letter is not duplicate then see its length is four then our answer is four ok this is the maximum length of the concatenated string with unique characters so the length is four ok now look remember when this Earlier, when I had made this video of recurs, I had put memoization in it and today I liked it very much. Today someone commented that he could not see the memoization as to what we were memoizing and it was very good. Observation: This is a very old video, good. Observation: This is a very old video, good. Observation: This is a very old video, so I had not even discussed this thing there, so today I am telling you guys, look, this is a very important note, look, always make a tree diagram, if you are solving the problem of recurs, then do not complete it. Just make a little bit and see what happens. This tells you whether you have to memoize or not. Okay, see Rick, what I told you is that when you write recurs, see what parameters are changing. Whatever parameters are being changed, we will have to take the same dimensions for memoization. Okay, but one more thing, let's see whether we really need to memoize, that too, you will know, so let's do one thing right now. Now let's make a tree diagram of this and I will prove it to you that you will not need memorization every time. Look, pay attention. I will take an example, what else was there? What we used to do was take a temp, initially the temp is empty, okay, so let's make a tree diagram of it, so now look, pay attention here in the temp and let's assume this is the current string, I am here, there is no duplicate character in it. You can take it or you can not take it, there are both options, we have included and excluded, so if you include then what will come in the temp? 01 2 Come, my index has come to number one and if you exclude, my temp will still be empty and this is here and here I am here 012 Okay, now let's move it a little further, move it forward temp. If there is nothing duplicate in both the strings I and index number, then you can include it, you can also exclude it, so what happened to the temp, it has come, it is okay, yes, come, my now. The index has come to number two, okay, now here comes the option to exclude, we have the temp, what will happen in this case, the blank will remain blank, okay, so what is here, yi, mine. This time the index number has come to number two, here it is okay, after this look, we will go ahead, right now I have come here, so look in this temp and in this string, there is nothing or duplicate in the eighth string, so what should be the temp here? My i will go k and if i goes out of bound then this is my last case. After this if I don't take anything then what will be left of me. i will remain only and if i goes out of bound then this is my last case. Can't go below this ok now look here temp is empty and let's string is mine none of the two is duplicate then what will happen to temp or if I include and exclude then my temp will remain empty After this I will be out of bounds, that's why this is my base case, till now it is cleared, so what will we do, let's expand this branch to the left branch, so see what will happen in it, or it will become if I expand this I have included it because look, there is any duplicate character in Current Temp and IQ, otherwise in this case a, I will move ahead and i will come here, okay, it will come at index number two and in this case, if excluded. u1 u temp u1's u will remain the same, I have reached here in index number two, okay, now look, pay attention, this is my temp and the current string that has come, look at both of them, there is a common character, one is u in this too, u is there in this too. If it is included in both of them, it means that you cannot collide both of them at all. Okay, so i will move forward and will be out of bounds, so the value of my temp remains like this. Similarly, look here also, this is the value of temp. And here the current I string has a common gutter in both of them, u cannot be concatenated, you will have to exclude it, then the index item will be out of bound, in the end the value of u1 will remain the same, okay, it is clear till now. Pay attention to things, look here, the benefits of making a tree diagram, I want to tell you how important it is, look, observe very well, let's look at each state, look, when do we memoize, when any state is repeated, then here is this state. Look, here it is on index two and look at temp. First of all, see when brother used to do memos, when my parameters were changed. Remember, there are two parameters in our problem, temp and one index, these are the two changes that are happening. You might be thinking that yes, we will memoize it with the help of temp and i. First look here, what is the value of temp i and the index is i2. Find it anywhere and show where the value of temp is. And the index is also 2, you will not find the value of temp anywhere. Ik and the index is also 2, and this is just an example. You can take any example and see, no state will be repeating anywhere. Okay, now look, pay attention to this state, here temp is empty and index one is, here temp is empty but look index two is repeating, there is no repeating, nothing is repeating, all the states are unique and if all the states are If it is unique, then what is the need to memoize? Memoization was done only when some state was repeated. Repeating sub-problems came Repeating sub-problems came Repeating sub-problems came here. Repeating sub-problem is here. Repeating sub-problem is here. Repeating sub-problem is not there anywhere. Look, the value of time is Yvan and I- not there anywhere. Look, the value of time is Yvan and I- not there anywhere. Look, the value of time is Yvan and I- index of temp is on one. Value u is aa index is here on 2 so it is also unique. Value of temp is u1 somewhere else. If it is not there then any state is not repeating anywhere. Even without memoization. If you will solve this problem of mine. No, my video which you might have seen is this one: No, my video which you might have seen is this one: No, my video which you might have seen is this one: Second question of DP, Second question of playlist, I also did recurse memoization, so remove the memoization part, only if you submit through recurse also, it will get submitted, okay, this is what I wanted to tell and it is very important. I wanted to make this thing clear to you, that's why I say that tree diagram is the most underrated tool to solve any recurring problem. Okay, you should give maximum stress in the tree diagram only. If you could make a tree diagram. If yes, then recursion is nothing for you. Okay, till now it is clear. Now let us move ahead, today I have talked about discussing this question on bit manipulation, so what is the use of bit, here how can we solve our problem and make it easier. Maybe we will see, let's move ahead and pay attention to this example. I told you earlier also that remember it is given in the question that the string formed by concatenating should not contain even a single duplicate character. So see brother. This string itself contains duplicate characters, so it will never be my answer, nor will it be a problem with anyone, because it itself contains duplicate characters, so its life is over like this. If it is not there, then it is of no use to me by ever having trouble with anyone. Duplicate character. Look at this also, it is a duplicate character in itself. So, I will ignore it and kill it. Okay, so the first step is to know what we will do to solve our problem. To simplify it further, what will I do? Remove those strings which have duplicate characters because that is never of any use to me. You must have understood that it was a logical thing because it can cause conflict with anyone in it. If there is only duplicate character, then it is not satisfying our condition. There is no unique character in it. Okay, so first of all, what will we do, whatever my example will be, we will remove those characters from it like Let's say AA is A, we will delete those strings, Y is B, this is C, this is Y and so on. Okay, so we will first delete those which have unique characters, so I will delete this one first. I will kill, okay, the remaining two are left, so I will take out from these two, what is my maximum length, the pebble string is clear till here, the first step has been understood, let us come to a very important part which will give you a smart solution. This will help in finding out. Look, first of all I had said that I rejected both of them because they have duplicate letters in themselves. Now who are left? C and one are left. Okay, now remember what you did in the beginning They used to keep the temp empty in the beginning, then where did my index start from, the index I started from here, then they used to do the same thing, they concatenated the temp once from C, then went ahead and explored it again from C. Explored the temp with this u1 and explored further but pay attention when you are able to explore when there should not be some unique duplicate character in the rectangle string in temp and in this current string. Ok right now temp But it is possible that there may be more characters in the temp in the future, then we can do the problem only when there should not be even a single unique character in both, sorry, there should not be a duplicate character, it is okay in both, this thing is clear, now look, pay attention, then this is what What a hassle to check, is n't it? Checking duplicate characters, are n't there duplicate characters? How to check, whatever is my current tem, whatever is my string, whatever is my current, this is my input, isn't it? I assume this is mine. Yes, currently when we had to check whether there is a unique character in both of them, then remember how we used to check, if one is simple one sin is all lower case letter, then we would have taken it of size 26, 0 2 and so on. Took the size of 25 26 and noted down the frequency of all the characters in the temp. Noted down the frequency of all the characters in the temp. Okay, let's assume that there was in temp because of the value. Was in temp because of the value. Take as an example, there was A and E in TEMP, and the SI which is mine is currently C and E, so first of all, the frequency of all the characters of TEMP is stored here, where is the frequency of A? If you write a - a on 0 then the you write a - a on 0 then the you write a - a on 0 then the frequency of one has been written as one. Where will you write the frequency of e on e - a, okay then where we assume that the Where will you write the frequency of e on e - a, okay then where we assume that the Where will you write the frequency of e on e - a, okay then where we assume that the frequency of e is written here, you have counted one, okay after that all the conductors of S. Let's note down the frequency of 'c' here. 'C' is note down the frequency of 'c' here. 'C' is note down the frequency of 'c' here. 'C' is written here. 'Frequency of 'c' will come here. Let's assume. written here. 'Frequency of 'c' will come here. Let's assume. written here. 'Frequency of 'c' will come here. Let's assume. Okay, now see 'e' has come. 'Write down the frequency of 'e' here. Look at 'e' then there see 'e' has come. 'Write down the frequency of 'e' here. Look at 'e' then there see 'e' has come. 'Write down the frequency of 'e' here. Look at 'e' then there is already one here, friend, you will put one more 'e'. So it will become two, what does it mean that will put one more 'e'. So it will become two, what does it mean that will put one more 'e'. So it will become two, what does it mean that more than one character has come, who is that character who has come more than once, then duplicate character, you are the identification character from here, but no, this is a big problem and solve it smartly. What we have to do is to solve it more smartly because now you are growing, now you should know these smart methods right so that now you can solve it in a more optimal and even smarter way. Now let's come to bit manipulation, how to make this work easier for us. Okay, how does bit manipulation make our work easier? See what I told you just now that whatever is my example, whatever is my input, let us assume that our input was something like this: A B input was something like this: A B C here. Okay, let's assume this was the input, so first of all, we will do this that the string which does not contain any unique character, like look at this string, there is no duplicate character in it, so we will remove it first. It would have been like this, even if it had been A B A, why would we have removed it because look, a is repeating, we need a unique vector, so what did we do, we removed it in the first place, so what is left with us is A B C. I was saved and whatever I want to do, I have to do with them, okay, my temp is empty in the beginning, okay, now see what I am saying, the recurring calls you make again and again, okay, let's disturb the temp with this. Yes, then you check before doing the concatenation, first check whether the string in it and the characters in it are not duplicated anywhere, then the one who puts the duplicate, then you work hard on this one which I just told is not so hard. See, there is a very simple way to do this. These strings are so big that you have to store them. You can also represent them with a number. See how in the question, all the characters have been given a clear cut, isn't it? Lower case English letters. Okay, so if I want to represent in binary, look at these people, how will I do? A B C is a, meaning the first bit is let's assume we have so many bits. Okay, the very first character is a, so you will do a - a. So what will come then I will set the zero th will do a - a. So what will come then I will set the zero th will do a - a. So what will come then I will set the zero th bit to one okay what does it mean that I have a already okay so what I am doing is convert this string into na binary I am trying to convert. Okay, I set a to one because a is my me pa. Now come bb minus a. If you do b minus a then what will come one will come, what does it mean I will set the nth bit and also the nth bit. I have set it, okay now here it is C, right, C mine A, do it, what does it mean C mine A, it will come, sorry, okay, what does it mean, set the th bit, this is the zero bit, this is the first bit. This is the second bit, so what did I do? I set the second bit to zero. Now look at the first and second bit. Now I am this and yes, what will be the decimal version of this? This was binary, what will be the decimal version of this? What will be the decimal version? If there is Sen, then you know what you can say. You can say that brother, instead of sending ABC string, I will send Sen and what is the meaning of Sen means this is binary and which bits are there in this binary. Set is first second third, it means first alphabet i.e. A third, it means first alphabet i.e. A third, it means first alphabet i.e. A is second alphabet i.e. B is second alphabet i.e. B is second alphabet i.e. B is third alphabet i.e. C third alphabet i.e. C third alphabet i.e. C i.e. A B C. So see what we did in this string. i.e. A B C. So see what we did in this string. i.e. A B C. So see what we did in this string. We replaced this string with an integer. Have used it is clear that you can represent it similarly, how will you represent d, if you do my A, how much will it come? What do you mean by giving? Whatever it is, there will be a lot of zeros. Third, set the third and also set the fourth. What does it mean? Zero bit, first bit, second bit, third bit, fourth bit. Sorry, third and fourth have to be set, right? Bit is first bit, second bit is third bit, fourth bit is neither, see, we have set the third bit and fourth bit, what does it mean, which is the third character, D is the fourth character, E is neither, so what have we done to these two. It has been set, what does it mean that brother, this is representing Jo, isn't it representing D? This is the zero beat, this is the first beat, this is the second beat, this is the third beat, okay, what will be the binary value of this, its binary. The value will be 1 2 4 8 6 24. Okay, so instead of writing so much string, I will write it in place of ABC and instead of , I write it in place of ABC and instead of , I write it in place of ABC and instead of , I will write 24. Okay, it has become quite simple. Now I will write ABC instead and see here. I am writing 'from' and instead of 'd' I am writing '24', it is writing 'from' and instead of 'd' I am writing '24', it is writing 'from' and instead of 'd' I am writing '24', it is clear till now and look at the temp in the starting, it was MT, so MT means there is no character near it, what does it mean that all the bits are there? If all the bits are zero then what will be its binary value. If all the bits become zero then what will be its binary value. It will be zero, so look, I have considered the number as zero in the beginning, it has been cleared till here. Now let me once again make you clear here that this Is n't it ABC? How will you get the sequence that I brought, that is, how will you do it in the code? So it is ABC. First you have verified that there is no duplicate character in ABC, only then it is valid. Okay. First of all, I got a, so in the beginning, I have zero, okay, this is row, so this is the binary value of row, so I saw a, okay, let's a, minus a, so what happened, zero, okay, what does it mean? You have now learned well how to set any bit to zero because I have told you in the previous questions about bit manipulation that how to set the zeroth bit or any kth bit to one. Used to shift left by one time, so this one is mine, how many times do I have to shift it left, zero time, because I have to set the zero bit, so if I shift zero time, then it will remain the same for both, take 00, then it is mine. This is the result, it is fine now, okay, this is done for A, now it is the turn of B, if we do B minus A, then how much will one come, what does it mean that I have to set the first bit to one, then I have to set the first bit to one. What will we do for one, we will shift left to one time, we will shift the first bit, so take one and hit it left shift from one, then if you hit left shift from one, then one will come, zero will come like this, now take the root of these two. Sorry and take one and here it is 00 okay now my final result is this now it's the turn of c so c - a is now it's the turn of c so c - a is now it's the turn of c so c - a is how much is c my a is 2 what does it mean that I have to set the second bit so second It is very easy to set the bit, is n't it? If you press left shift two times to one, what will happen? One will come here and from this our result was already taken in it and taken 1 00 so see all the three characters of ABC here. The set bit is already done, isn't it, its binary decimal value is seven, it is clear till now, you will do it, okay, so we have reached here, our temp will be zero and our input will be 7 and 24 till now. You should be very clear. Okay, so now let's move ahead. Now let's see in the future, how will we check that temp is whatever is mine currently and i is whatever is mine, now it is not a string, we have converted it into a number, so those How will they know whether there is a unique character in both of them or not? Okay, so I have taken this example, this is my example, A B C D A E, look at both of them, I have converted them into binary, look at all of them, in this, the eighth bit is zero bit and the first bit is set. Why is it because there is a, here for CD these two bits are set, here this and this are set for a, is n't it ok, it is clear, I write it in binary only, I write it in decimal only, how much should it be And this will become 1 2 48 This will become 12 This will become 1 2 48 16 This will become 17 Okay and remember what my temp was in the beginning was zero Now let's assume that I changed the temp from A Because there is zero in temp, it means in the beginning, remember when it was made in the old way, temp was MT, there is no unique character in this temp and this A, sorry, there is no duplicate character, otherwise there is problem in both of them. If you can, then if you concatenate it will become A. Okay, now see, how to do it in this case, it is simple, friend, look, what is the temp, it is 00 and the current one which is my A has become my T, okay so 0. 01 This is my A, okay this is my temp and this is my A, okay both of them can be [ __ ], first of all we have to see whether brother can do both of them, how will they do so, can be [ __ ], first of all we have to see whether brother can do both of them, how will they do so, can be [ __ ], first of all we have to see whether brother can do both of them, how will they do so, how will we know whether they can do both of them or not. There should be unique characters only and only now, pay attention, will you get the end of both or not, if you get the end of both then the answer should be zero, only then there must be unique characters because look, here there is zero, here there is one, what does it mean that it has a. It doesn't have A, it means it has a unique character, it does n't have Also mine is this is the current index, let's assume that if it is zero, okay, what does it mean that brother, there is only one and only unique character in both, okay, then what does it mean that we can concatenate. What is temp and current is my string, whatever is three means A, then what will my temp become? Temp will become my A. Now how will we make temp A, meaning this is done in the string, how will we make it a number, simply temp. And which is this number, take their and, take what else operation, what is the value of tum, it is 00 and what was the binary value of the one which was mine, three was 00 1, take the and operator of both of them, what will happen if you take and? 1 00 What does this mean, see what happened, now my temp has become what, my temp has now become A, remember when we used to concatenate, temp used to become A, so the same thing happened here, we concatenated it, we just did a clever thing, we bit. Solved it with magic, look at it with bit magic, immediately checked in one line whether both have unique characters or not. Now remember, to check the unique character first, so much drama had to be done. Remember, this drama had to be done with that one. We don't have to do it, right? What do we have to do? Simply, we can check directly by using bit by bit manipulation and even in case of interference, it seems to be an off operation. You should know that let's assume that this is A, this is CD, both are If you do a concatenation of A then C will join B and then C will join then this is also an off A operation but look at the concussion here, how fast it has become, simple and you have to remove the concussion and your concussion will be done, okay here our solution has become quite simple i.e. So that you have understood Bit Magic here, i.e. So that you have understood Bit Magic here, i.e. So that you have understood Bit Magic here, how a person is using Bit Magic, here it is okay, I have explained it in very minute detail, already many people will know this thing, but I have told it in minute detail so that even the beginners can understand it. So that you can understand, okay now let us define what we have to do, so look, I have converted every string into numbers, binary numbers into decimal numbers, temp is now zero, okay, so now let's start the temp con from here. What can we do from the element in index number zero to temp? We can check whether temp is there or not. If 00 is my 0011 then it is yes. If you do end operation on both of them then it is ok then zero will come. What does this mean? There is no common character in both of them. There is no cotter meaning it can be concatenated. So what is the first possibility that I concatenated temp with i. Okay then what will be the value of t. The value of t will be zero. And what else did I do with three? I did another thing with three, right? If I made 0 and three become 0 and 3, what will be the result? Three will come, isn't it okay? So this is the first possibility, we will come 3 12 17 I will come here because I have used three here. Okay, what is the second possibility? This was the first possibility of yours that you have disturbed the temp with A. Okay, now there could have been another possibility that by not doing this, you could have done this. Okay let's concatenate, now look at this below, will it be explored and will bring? Now my answer is that if we assume that we do not do it with three, we do it with the one after three, then let's see what happens to the temp. The value is 00. What will be the value of 12? 1 2 4 i.e. 1 will be 00. If you do AND 2 4 i.e. 1 will be 00. If you do AND 2 4 i.e. 1 will be 00. If you do AND operation on both then zero will be written. It means there is no common character in both of them. It means there is a possibility of concatenation. You can concatenate. There is no common character. Okay, so the value of tem here, what will come here, value of tem here, what will come, 12, what will come here, 3, 12, 17, and since I had here, what will come here, 3, 12, 17, and since I had used it, I will run ahead, so I will run ahead, okay, one more possibility. What would have happened is that you would not have taken this also and you would have checked the temperature problem with this. Let's see what happens in this case. Will it be connected or not? Is it zero? The temperature is 17. Do you remember what my number was of 17? It is fine. So this is my 17, so now look, pay attention, this temp is zero and there is no common character in both of them. Right, there is no common character, so look at the end operation also, zero is coming, meaning can So see what happened to my temp here, so my tap became 17 and here it became 12 17, see I had used it, come when it runs ahead, it will come here, it is out of bounds, okay, so this is the case. That's enough, this much will come, okay, now let's see these two by exploring, you can explore it yourself, I will explore it myself and show it to you. Okay, look here, 12 and 17 are there, okay, so temp. is 12 and the current eighth element of mine is 17 so 12 I write once a 1 2 4 8 i.e. 1100 this is my temp done a 1 2 4 8 i.e. 1100 this is my temp done a 1 2 4 8 i.e. 1100 this is my temp done right and this is 17 i.e. right and this is 17 i.e. right and this is 17 i.e. 0001 sorry one 001 ok this is my temp and this is my Is it 17? This one is the current one, so let's see whether there is a unique character in both of them or not. There is no unique character in both of them. Look, this is zero, this is also zero, which means there is no unique character in both of them. And really look at the proof also now let me show you the meaning of temp 12 remember what was 12 was my cd ok and the one which is 17 is my a there is no unique character in both of them no duplicate character means really We are correcting it with the help of bit manipulation key, so what did I do in this current eye of 12, the value taken from 17 and operation is zero, that means we can correct it, okay, let's correct it, then what if I correct the temp. If you cut the ear from this 17, then what will happen to 12 and 17, whatever value will come, it is okay, whatever value will come, it is clear till now and after that, if this temp had not been cut from this eye, then aa would have gone ahead and aa would have come out of. If you got bound then this was the only option, you could not do it with anything else, it is ok till now it is clear, so 12 and 17 are ok, so I have written the binary of 12 and 17 here and have to extract it, right, and extract the operator further. Let's give 101 1. Okay, now look at what it means that I concatenated 12 and 17 i.e. temp and a, that I concatenated 12 and 17 i.e. temp and a, that I concatenated 12 and 17 i.e. temp and a, then the value of tm was 12 and the value of a was 17 and did that. Now look at the convolution, it is even. It is one, it is one, that is, it has four unique characters, that is, whatever string is made, its length must be definitely four. Okay, so how will you calculate the length. Whatever is the cut string, brother, the number of bits set is this character. This is the character, this is the character and let's see whether it is correct or not, remember the temp, ours was this, our temp, what was ours, 12 was 12, meaning this was this, I had troubled him with this, CD AE, what is its length, it is four. And this is also correct, length is four, there is no unique character, so there will be set bit at four places, one place here, that is, it will have four characters because it has four set bits, so how did I find the length in my problem. There are many ways to find out the number of set bits in a string. You can also use a simple library, the built in pop count in c+ will directly calculate the count in c+ will directly calculate the count in c+ will directly calculate the number of set bits in it, then you will find out its length from there. Okay, so I will keep storing the biggest length in the result, what is the length you have got, how much have you got, now you have got four lengths, so I have written four, let's see now, will you get a bigger length, is it bigger than this, okay, here also you can expand it. Do it yourself, expand it yourself, look here, this is the temp, this is three, this is mine, this is 12, so three means what is 0 1 0, okay and 12 means what is 00, the end operation of both is zero, what does it mean in both. There is no unique common character, meaning you can do both, no means you can concatenate both of them, if you do concatenate then what will happen, the value of 3 and 12 will be right and then you will move ahead 3 12 17 Aa will come here. Okay, now one more decision you could have taken here is that instead of doing this, you could have increased Aa here and done this, then you would have done three and 17, not three and 17, you would have checked before doing three and 17. There is no common error in it, only after that you go here, it is okay and every time you see the maximum value, whatever last value is coming, keep storing it in the result, like look here, the final value of temp and temp is here. There are 12 and 17, so its length is four, so I stored four in the result. Here, if any big value comes, then we will update the result. We will keep a global variable of the result and will keep updating the maximum value there. Till now it is clear. If you write the code then this entire tree diagram will be converting into code. Nothing new will be visible to you. If you are okay then how will you start the code? Remember what I had said that I will start i from here with zero and I had said that What did you do to the temp, once you tried to concatenate it like this, then when can you concatenate, when the end operation gives zero to both, okay, then if you had come to the end operation then go ahead to explore i + It is okay to do 1, otherwise what is another i + It is okay to do 1, otherwise what is another i + It is okay to do 1, otherwise what is another way, you tried i with this, then explore and move ahead, otherwise, you did one more method, explore and move ahead, otherwise see what you did, the value of temp aa is this first. If you tried this, then you will simply apply a for loop from i to where row to i < n a p plus, to where row to i < n a p plus, to where row to i < n a p plus, okay here we will check that brother if temp and are off a and operation of both. If zero comes, then it's okay, go ahead, right, go ahead and explore and bring it, DFS will call you back, either name the recurse, whatever you name it, you solve it, what did I do there? Before and since we struggled. If given then we will send the value of temp and array of come, the problem is also done very easily, how simple it has become, okay and we will keep a global variable result all the time and keep checking here that the result is equal to maximum of whatever. The value of the result was OK. Whatever value is there in temp now, how many one bits are set in it? Whatever value of temp, how many one bits are set in it, we will find it. Okay, here we will find out how many one bits are set in temp. It is set, we will keep updating the result. Okay, so this tree diagram is nothing, it means that if seen, this tree diagram is only the code. If seen, I am not seeing the tree diagram but the code, so now when I code, it will be exactly. You must be seeing only a tree diagram there, okay, so let's quickly convert this story into code and move ahead, so what I said, first of all, what I will do is that I will remove those which do not have unique characters. If there are any duplicate characters, I will remove them. Okay, so I take one here, vector of int, a unique character, say strings. Okay, and why did I take vector of int, remember what I said that I take every string as an integer. Right, now let's start, let's go to each string end s in a r. Ok, go to each string, now we have to check that this string has all the unique characters. Otherwise, a very simple way is that you put all the characters in one set, beginning of s and end of s. With the help of this, what will happen, you know, all the characters in this s should go in this set. Okay, now what happens in a set, you can keep only unique characters. Okay, if there were all unique characters in s, then the size of the set would be the size of s, doesn't it mean that if the add size is all the characters in the set? There will be unique characters in s. If not equal to s is found to be length, then what does it mean? Surely there must be some duplicate character in s. Okay, here I write that means s had duplicates. Okay, so we will not do anything, we will ignore it and kill it. I hit continue, okay, I will not store this s in it, okay in my unique character strings, and if the length turns out to be the same, meaning it is a unique character, then what will I do with this s, I will convert it into an integer and put it in case. Remember, I Had taught, why are you converting into integer? Interval = 0, why are you converting into integer? Interval = 0, why are you converting into integer? Interval = 0, took one, will go to each character for its care and s in s. Okay, remember how we used to find out value is equal to value and took from whom s - a times value and took from whom s - a times value and took from whom s - a times shift. Do left shift to one, okay, this is taken and taken, okay, and as soon as this is over, whatever the value of the value is, it will be the integer value of this string, right, so what we will do is put it in this, what by pushing back in the unique character? Put this val, this is clear till now, this thing should be clear for you, see ch-8, neither is it, I have to set that bit, ch-8, neither is it, I have to set that bit, ch-8, neither is it, I have to set that bit, so what I did was hit the left side shift on one, so many times - a times and val. If you shift on one, so many times - a times and val. If you shift on one, so many times - a times and val. If you take it then what will happen is that it will set my 'A' bit. It's okay set my 'A' bit. It's okay set my 'A' bit. It's okay that I have this character, that bit is set, that's okay. You must have understood everything till now, so what have we done till now? We have prepared our strings with unique characters, right? These strings with unique characters have been prepared for me but I have stored them in the form of integer. Okay, let's take the int result equal to 0. What did I say, I will make a recursive call. I will start from the index number row. Okay and remember my temp in the beginning had MT string in it. MT string means zero value. Okay, so temp also put zero. Okay, temp and will keep sending the result. By reference will send the result so that I will keep updating the result and also keep passing the unique character string and as soon as I return I will return the result. Okay from here now let's come to our recurs function which is exactly a tree diagram and nothing else okay void solve. Int i one is ok, what was the value of int tape, whatever it was, why are int and result by reference so that when the result is updated, it gets reflected, but I have to return the same too, ok, what are you passing after that? We are passing vector of int unique strings, okay, all the unique strings are in it, there are strings with unique characters, all this is fine and I had said in the beginning itself that the result is equal to the maximum of whatever is the value of the result and What is the current length of the concat string which is in the temp as many set bits as there are in the key temp, that will be the length of mine So Underscore Acor Built in Underscore Pop Count What will it do if it calculates out the count of all the set bits in the temp so that is my concat If there is a length of the string, then in the result I stored whatever will be the maximum. Okay, now see what I said that should I int the current temp by one or the lesson goes till here, dot size of all one by one. We will do it with plus, till now it is clear that we will try to connect the coordinates with everyone one by one, that is why we have put a for loop, once the ID is done with one, then if it is plus then we will do it with that one. If there is i plus then we will try with that one. We will go but first of all we will check that whatever string is there in temp which is the current index aa can be concatenated with whatever string is in aa when the end operator of both of them is given zero then whatever end operator is taken in aa if it is zero. Only then will I be able to do it. Means they have unique characters only, no duplicates, meaning both can be created. Look, you have done it in one liner. This is the specialty of bit manipulation. Okay, if you can do it then do it further. Go and explore i pv go ahead ok t and see the temp will change temp zar unique character zar what does it mean remember I told you it is not a zar and what does it mean that it is concatenated that is the value of the term. It is done, we will send the result, we will send it and we were sending it till now, it is clear, okay, now look, it will come after exploring, if we agree, you feel that it is okay, there is no need to disturb the temp after this. If you want to do it from the index, then i plus ps is self-explanatory, meaning you can do it with a for loop also, you should is self-explanatory, meaning you can do it with a for loop also, you should is self-explanatory, meaning you can do it with a for loop also, you should understand that here it can be done with a for loop also, see yourself and understand the flow. No, what is happening is the current temp, right now I am standing at E. Okay, so I tried to calculate the temp by i = standing at E. Okay, so I tried to calculate the temp by i = standing at E. Okay, so I tried to calculate the temp by i = E. Here and if the problem is enough to become a problem, then I sent it forward in the recurse by doing i + 1 that the problem is done now. You go ahead and check the doing i + 1 that the problem is done now. You go ahead and check the doing i + 1 that the problem is done now. You go ahead and check the answer below and if you accept that I felt like I do n't want to do this by ID I didn't want to do it by I, so I changed i to plus and then did temp. then see try all the possibilities here. It is happening and here I have also been calling recurs that after exploring every possibility, you should come up with my best answer, okay, let's run it and see, its time complex is not getting repeated, okay, but every index. But we are looking at two possibilities, that's why the power of 1 is A, its time complexity is not there, we are not taking any index, and look, the constraint is small, hence we will pass, so let's submit and see we should be able. To pass, indeed yes, we have learned a lot of informative things today, okay that's why the video may have been long, any doubts, raise them in the comment section, I will try to help you out, see you in the next video, thank you. | Maximum Length of a Concatenated String with Unique Characters | largest-1-bordered-square | You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**.
Return _the **maximum** possible length_ of `s`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[ "un ", "iq ", "ue "\]
**Output:** 4
**Explanation:** All the valid concatenations are:
- " "
- "un "
- "iq "
- "ue "
- "uniq " ( "un " + "iq ")
- "ique " ( "iq " + "ue ")
Maximum length is 4.
**Example 2:**
**Input:** arr = \[ "cha ", "r ", "act ", "ers "\]
**Output:** 6
**Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers ").
**Example 3:**
**Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\]
**Output:** 26
**Explanation:** The only string in arr has all 26 characters.
**Constraints:**
* `1 <= arr.length <= 16`
* `1 <= arr[i].length <= 26`
* `arr[i]` contains only lowercase English letters. | For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1). | Array,Dynamic Programming,Matrix | Medium | null |
837 | hey guys today we're going to be solving lead code question 837 new 21 game this is a medium lead code problem but it's actually a little tougher than a usual lead cold medium problem i would say it's leaning towards a heart problem what makes this problem difficult is not just the solution but the question like the problem statement itself because there are like three variables and they've thrown in some probability in there it's difficult to grasp the essence of the problem in one reading honestly but um yeah we'll get there i'll explain everything uh what i'm going so this is the solution is based on dynamic programming i'm going to present two solutions the first solution um is will is actually a tle solution in that it will exceed the time limit on neet code but it's easier to understand and it will lay a good you know foundation for us to uh proceed to the more optimal solution which is also dynamic programming solution but um we'll also integrate a sliding window component in there so don't think about the sliding window or dynamic programming right now we'll get there but i was just setting the expectations right anyway um let's get to the question cool so um i hope you read the question so um the as i mentioned the problem with this question is that there are like three different variables that we need to consider when we think about the solution so what we'll do first is we'll just eliminate some of those variables okay we'll not think about everything at once um what they have said is given a range from one to max points yeah let's say max points is six so our range becomes one two six cool uh what they're saying is we can draw numbers from this range and all numbers can be drawn with equal probability so say the probability of drawing a 2 is equal to the probability of drawing a 5 and we'll keep drawing numbers from this range so say we draw 2 and then we draw 4 we get to 6 say we draw 6 after that we get to 12 we keep summing this up and when do we stop right that stopping that threshold is defined by this k right so say k is 18 what they're saying is as soon as we touch 18 or we cross 18 we stop the game right basically there is no way to end the game until your sum is less than 18 as soon as it touches 18 or crosses 18 we stop the game right and if you're familiar with this card game 21 that's exactly what happens right if you reach 21 or if you cross 21 you stop drawing i am not familiar with that game honestly but i think it's um that's exactly the idea of that game anyway let's let i digress but um so yeah this k is the threshold right of when we stop drawing and uh so basically the game can never end until you have drawn k or more than k points right what they want um for the solution is the probability okay forget probability uh what is okay no let's think about probability what is the probability that alice has n of your points okay and n will always be greater than k greater than equal to k which is kind of more important for this question okay say n is 21 yeah so what is the probability of us getting n or fewer points now when does that fewer points end we know the upper limit n when does those f when do those fewer numbers end it ends at k right because the game cannot end until you cross k so when they say they want the probability of uh alice reaching n or fewer points what they mean is probability of n would be probability of n sorry not let's i'm sorry the solution would be the probability of n plus probability of n minus 1 until probability of k right that is the lower limit because the game couldn't have stopped unless we had cross k points and so the least we could have the least sum that we could have reached when the game stopped is k so when they say n or fewer points what they mean is this range the probability that our final sum is in this range k to n and k will always be less than or equal to n they've ensured that cool this is the problem this is uh yeah this is the problem statement i hope that was clear uh let's get to the solution okay i'll dive right into it let's define our recurrence relation first what would be dp of i okay let's define this as the probability of reaching the number i cool let's just define that now let's say let's this take this example okay we'll keep n 21 k uh 18 which is the threshold and max point six okay basically we can draw from one to six any number from one to 6 with equal probability there is no bias there cool so let's say we want to know the probability of reaching 21 right now what are ways of reaching 21 actually let's start with something simpler yeah in general yeah let's start with something simpler what is the probability of reaching 14 say okay that uh so i'm not this is let's yeah uh let's not let me not confuse you with putting in too many elements here just think of this objectively what is the probability of reaching 14 anywhere like anywhere anytime during the game what is the probability of reaching 14 so the probability of what are ways to reach 14 basically we could have reached 13 and then drawn one to reach 14 or we could have based 12 and drawn a 2 after that from that range to reach 14 right so what i mean is the probability of reaching a 14 is the probability that we have reached 13 somehow by drawing our numbers and then into the probability that we drew a 1 after that yeah please note that this dp is the probability of reaching that number and this probability is the probability of picking that number there's a difference there okay it's very important to understand that difference um anyway so we could have also reached 14 from 12 and picked a two from that okay this should not be a dot okay and i hope you are familiar with like basic probability laws because we want these two events to occur together like reaching 12 and drawing a 2 so we multiply that but there are like because we could reach 14 via this row route or this route or these other routes so we sum it up like if you know basic probability this should be easy to understand um then so we'll keep doing this right what is the largest number we can draw from this range six right so probably so dp of something into probability of six right so this should be 14 minus six okay which is 8 right this is the base of our recurrence relation and if you noticed what i did was this was 14 minus 6 right because that is the maximum distance behind from where i could have reached 14 yeah and if you think about it this 14 is max points right forget this 8 and this 6 is also max points so as you see i'm getting to the recurrence relation slowly okay now let's uh define this in terms of our variables so dp of i okay this i can be any number um would be dp of i minus 1 into probability of drawing a 1 plus dp of i minus 2 into probability of drawing a 2 until dp of i minus max points into probability of drawing max points now as uh mentioned as i've mentioned a couple of times and as it's mentioned in the question each draw is independent and the outcomes are equal probabilities what that basically means is the probability of all probability of one probability of two probability of max points it's all they're all equal and they're all equal to one upon max points okay um if again um probability is defined by the favorable event upon total events so the total events is max points because you can draw max points number of points and one is the possibility of drawing that one number of interest like of probability or drawing two is one out of those max points numbers like i don't i hope like uh i hope this is clear like if you know basic probability this should be clear so what that basically means is this is one upon max points right yeah and this is basically a recurrence relation let's simplify this more because it will actually it adds value uh it will help us think better as we go i'm just doing some basic algebra here i'm getting the fraction outside and writing this as a sum of dp of i minus 1 until dp of i minus max points and that's it honestly um now there are a few corner cases i have left out um i guess i could okay let me just mention one important edge case and the rest we can cover as we code right because it will be easier that way because one corner case that i do want to mention at this point is um say so this is all fine as long as this 14 is less than the threshold right but there are two edge cases to consider here say what is the probability of reaching three and your max points is six so in that case your recurrence relation will at some point want i minus max points which will be three minus maximum three minus six so you will be at dp of three minus six minus three which makes no sense so this is one edge case where we have to um consider the fact that our uh like we don't have numbers behind zero that is the first edge case that we need to think of this is basic like this is something that you would have thought of anyway the edge case the other important edge case is that the other end um is at the other end of the problem okay uh what think of this what would be dp of 21 now important things to consider here you cannot reach dp of 21 from dp of 20 right 20 21 minus so if i is 21 uh i minus 1 would be 20 okay there is no way of reaching 21 from 20 why because if we have reached 20 already we will not draw we are above the threshold so if we have reached 20 we can never get to 21 right this is an important edge case to remember similarly if i have reached dp of 19 or dp of 18 okay it is not possible for me to reach gp of 21 okay so when we calculate the dp of 21 we will not include tp of 20 19 or 18 in our solution this is important to remember this is a very important edge case to remember we'll only consider dp of 17 and lesser until we reach dp of i minus max points which is 21 minus 6 which is 15 right there's actually only one year i don't know why i put three dots anyway our dpo 16 okay we will not consider these three elements this is the other edge case to consider okay if you understood everything until this point the next two solutions that are present will be easy to follow okay um let's dive right into it because this is already going to be a long video and i want to yeah proceed fast cool we'll handle an edge case first if k is equal to zero return 1.0 1.0 1.0 uh what this edge case may and what this check means is if the threshold is zero which means we cannot start the game at all right like before our game starts our score is already zero and if the threshold is zero we've already crossed it or we are already at the threshold so we don't need to start the game so our score will never increase beyond zero and what like whatever the value of nb uh maybe uh will always remain at a score less than or equal less than n right so the probability of alice having n of your points is hundred percent which is indicated by probability one which is what this edge case handles moving on so basically with this solution i'm going to construct this relation like entirely right i'm going to put in two for loops that's why it's going to uh tle as well right but i'm just doing this because it's easier to understand it and it will be easier for us to move to the more optimal solution from this point okay uh so the idea is we're going to calculate dp values for all possible scores that we can get from this game and then we'll just uh like sum up the dp values that we need for our solution okay so we know that the lowest score we can get from this is zero if you don't start but let's not think about that the lowest is one let's say and what's the max score that you can get from this game right now you know you have to stop the game when you get to k so but think about it the largest score that you can get is if you are at k minus 1 like 1 less than k just like you haven't reached the threshold you've reach the maximum points that you can before reaching the threshold and if after if at that point you draw the maximum possible points right which is max points or six that's that will be your maximum score and as soon as you read the maximum score you would have crossed the threshold so you cannot draw anymore right so um the max score that you can reach in this game would be k minus 1 that is 1 less than k the threshold plus max points because that's the max points that's the maximum jump you can make from that point right so that's what we're going to do we're going to calculate dp values from 1 to max score and then for the final answer we're going to just sum up the dp values from k to n right as i mentioned n is something n is the high element that they have given us and the lower limit is something that we have found like we can the game can never end at a score that is less than k it will always end at k or greater than k and it will move on to n and um n will always be greater than equal to k so that there will be no index what should i say mismatch not mismatch but you get the idea there will be no issues there so this is a one dimensional dynamic programming solution this is me defining a 1d array 1d double array initializing all values to 0 the size will be max score plus 1 right because we want dp of max score as well that's why i'm going to initialize it to max 4 plus 1 and i'll just um i'm going to set the size as max 4 plus 1 and i'll just initialize dp of 0. what would be dpo 0 what is the probability of reaching number zero one right because if you don't start the game at all you're already at zero so the probability of reaching zero is maximum is 100 so i'm going to initialize that as 1.0 so i'm going to initialize that as 1.0 so i'm going to initialize that as 1.0 now i'm just going to insert my two for loops right so we're going to calculate dp of i values for all possible scores that we can get from this game so that is i to max score okay and then we're going to put in an inner loop this inner loop is going to help me construct this recurrence relation for every dp of i the j will basically be these values one two max points whatever we are subtracting from i cool so this will go from j to max points yeah um now we're going to handle those two edge cases that we spoke about right uh what we want is i minus j right so let's put in some checks for i minus j if i minus j is greater than equal to zero right as i told you like what if your i is three and your max points is 6 and you do an i minus j you get 3 minus 6 minus 3 dp of minus 3 which makes no sense so we have to ensure that the least value we pick up um from our past calculated dp values is dp of zero that's why i'm putting into greater than equal to zero right and now we have handled the problem at the lower end of the problem now we'll handle it at the other end at the end the i'm talking about that edge case uh this edge case dp of 21 that i told you about where uh to in calculating dpf 21 we will not consider dp of 20 19 or 18 because if you've reached any of those numbers you can never reach 21 right you will never draw again because you've already crossed the threshold at dp 18 19 20. so this next condition will handle that so this has to be less than k cool like uh like keeping this giving this example in mind if you do some basic mathematics you'll arrive at this condition this should be easy to do cool moving on let me just put this in parentheses okay so dp of i will be dp of i minus j divided by and this is me this casting max points right this i'm dividing by this to account for this fraction cool and that's it like at this point we would have calculated dp values for all possible scores okay so um now we'll construct the solution which is we'll um sum up tp values from k to l which should be very straightforward right let's initialize the result as 0 for i in k to n the result will be just the summation of these dp values and that should be it that's it um i'm going to run this code and this will move running the basic test case will pass but when i submit it will expectedly exceed time limit which makes sense right like so many for loops yeah so you see it exceeded the time number now we can move on to the more optimal solution okay now how okay let me lay the foundation for the more optimal solution now uh let's say let's look at dp of 14 right what is uh let's call this okay this is a constant right let's just call this c so this will be c into dp of 13 plus dp of 12 plus and we'll go on until dp of 14 minus 6 8 so dp of 9 plus dp of 8 yeah this is how it will be uh what about dp of 15 again c into dp of 14 plus dp of 13 plus like this plus dp of 15 minus 6 90 pp of 10 plus dp of 9 cool so if you notice the only difference between dp of 14 and 15 is that we have added one dp one term to the starting to the uh front of this sum and we have removed the we have removed one term from the tail of this term right the rest of the terms remain the same so the idea is if we maintain a running sum okay a running sum of running some what i mean is if you maintain a sum of these values and just manipulate those front and n terms and just keep reusing that it will be much more faster right than doing this entire for loop that's the basic idea i'm going to call this one sum the running sum okay and this is basically the numerator um by that i mean is because c is one upon max points will go to the denominator we're just going to keep manipulating the numerator and this running sum will be the sum of all dp values that can actually reach i yeah that idea remains same just that uh like maintain this is the sliding window part we are like sliding over uh sliding over all the numbers that can reach the subsequent eyes and you know just manipulating a little or manipulating at the front manipulating at the back and calculating the dp values so that's the idea and again we will have to handle those two edge cases that i mentioned earlier um the one which is um like the edge case at the zero end and the edge case at the top end right um let me just call this edge case two because i think edge case one is easy to remember edge case two edge case one is um the zero case so these two uh edge cases will handle okay i think this is uh enough uh for me to move on to the next uh next solution like i can start coding and i'll explain as i go along that okay and that's a very elegant solution like if you've understood everything under this part you'll actually enjoy writing that because it is very fast and um yeah it's just an elegant solution cool let me just keep this around i'll come in this i'll also remove this so that we can start fresh cool so adding some edge cases first if k is equal to zero actually i should have deleted everything right i'm just going to repeat okay i've already explained this edge case i'm going to define the dpra this time i'm just going to define the dpi until end right because that's we need only until dp of n i won't do it to max code like the previous solution um so initializing everything to zero the size to n plus one because we would need dp of n and dp of n minus one until dp of k and we'll just initialize dp of zero right um dp of zero as i explained earlier will be one point 100 probability now we're going to i'm going to introduce the running sum okay the running sum will be this numerator value okay so i'm just going to call this running sum it will be a double of dp of zero okay we i'm going to start my for loop for from one so i'm just going to initialize so for um one dp of one the numerator will just be dp or zero right that's the only number that comes before it so um i'm just going to initialize running sum as dp of zero so that i can directly use it for dp of one and then i'll start manipulating the dp for future dp values okay cool um let me just this is just the numerator the sum of dp values that can reach i okay this is also the sliding window just mentioning it okay cool um okay let's also uh we're just going to uh i could have done this separately but let's just do it right now we're going to construct the result on the fly okay it's easy like you won't get confused let's just do it will be very fast so excuse me for doing this like i'm explicitly specifying the type and still doing 0.0 still doing 0.0 still doing 0.0 it's fine let's not concentrate on that so for i in 1 2 n right because we have already calculated dp of 0 let's start with dp of 1 and go to dp of n because that's the maximum that we could need cool so dp of i will be running sum upon double of max points right okay at this point i'm assuming that the running sum is has already been prepared for the current dpo5 like for dp of one my running sum is already correct because i have initialized it with dp of zero that's what our assumption will be throughout this for loop that at the beginning of the for loop my running sum has the sum of all the correct dp terms for current for the current dp of i and for the rest of the loop like below this i'll actually construct like i'll actually manipulate the running sum so that it's correct for the next dp of i okay you'll understand that let me just add a comment calculating dp of i assuming running sum has already been correctly prepared okay moving on let's um handle the front end first okay front end running some cool like you'll understand what i mean by front end and tail and basically we have to add a new term at the front of the running sum and remove one term from the tail end or the rear end of the running sum right and that will differ right this if condition if is if i is less than equal to k comes because of the db21 case that i told you about right we are going to handle that right here um because you remember as soon as we touch k or we go beyond k we can't include those dp terms in for uh dp values that we calculate after k right because db of 21 is after dp of 18 where 18 is the threshold so we can't include dp of 20 dp of 19 or 18. so as soon as we touch k or we cross k we stop including those values and that's the logic that will go here if i is less than k we are below the threshold we can add terms peacefully no there's no problem okay so that's what we'll do we'll add the current dp value to the running sum why are we adding the current dp value because we are actually preparing the running sum for the next tp value in the for loop right so say we were at currently we are at dp of 14 um currently we are at this iteration where we are calculating where i is 14 right we'll add tp of 14 to the running sum so that dp of 15 can use it yeah that's the idea and if so this is at the front end of the running sum if i is less than k we can freely add dp of phi to the running sum if not we cannot add it but here's the elegance what we can do is actually add it to this result right because the result will only contain dp values which start from k and go until n and this for loop ends at n and if we um if i is if we are at the threshold or at any value greater than the threshold we can't add it to the running sum but we can add it to the result so let's just do that right cool and now we'll handle the tail end of the running sump cool and this is where we'll also consider the um first edge case the zero end edge case right this one uh oh i haven't added an example there but i hope you remember um if i is if i minus max points is greater than equal to zero right we can only add dp values which are at zero or greater than zero we can't have dp values of i's which are less than zero that makes no sense just handling that this is the first edge case that i told you about the zero end edge case if and everything is okay at that end we'll just remove the dp value from that end right and you have to uh remove the uh dp value at the maximum and at the back so that we can get by subtracting by max points that's the maximum back you can go right and that's it right let's just return the result cool let me check if i missed anything okay i've missed an edge case um so this k equal to zero edge case we understand now what is one other case where the probability of uh the of alice having n of your points is also maximum what happens if the max score that we can get from this game what happens if n is greater than the max score we can get from this game the probability that we'll always have n of your points is 100 right because the maximum score we can if n is greater than the maximum score we can get from this game we'll always have 100 probability for this right so let's just handle that cool i think let's run this code accepted cool that works i hope that explanation was clear i'm recording after a long time so i apologize because i was a little rusty today but happy lead coding guys stay safe have a good day or a good evening wherever you are bye | New 21 Game | most-common-word | Alice plays the following game, loosely based on the card game **"21 "**.
Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets `k` **or more points**.
Return the probability that Alice has `n` or fewer points.
Answers within `10-5` of the actual answer are considered accepted.
**Example 1:**
**Input:** n = 10, k = 1, maxPts = 10
**Output:** 1.00000
**Explanation:** Alice gets a single card, then stops.
**Example 2:**
**Input:** n = 6, k = 1, maxPts = 10
**Output:** 0.60000
**Explanation:** Alice gets a single card, then stops.
In 6 out of 10 possibilities, she is at or below 6 points.
**Example 3:**
**Input:** n = 21, k = 17, maxPts = 10
**Output:** 0.73278
**Constraints:**
* `0 <= k <= n <= 104`
* `1 <= maxPts <= 104` | null | Hash Table,String,Counting | Easy | null |
1,281 | hey everyone today we're going to be going over leak code 1281 subtract the product and sum of digits of an integer so given an integer number and return the difference between the product of its digits and the sum of its digits so we go down to this example um two three one if we take that and go over here the individual digits are two three four so two times three times four is equal to twenty four and then two plus three plus four is equal to ten and um or sorry nine and twenty four minus nine is equal to fifteen so basically that's kind of the logic that we're going for here so we want a product we want to sum we want to subtract them so let's do that let's get our product let's get our sum and let's subtract them so the product is 1 because we can't initialize it to 0 because anything times zero is zero and then sum we just set it to zero so basically you could convert n to a string and go through each character and do it that way but there's really no point in doing that so we're just going to go while n is greater than 0 and just get each digit using math and how we do that is we can actually get right most and we'll just mod it by 10 and that's going to get the rightmost digit in n because this is actually the remainder if you're not sure about this modulo thing so basically what we want to do is we want to multiply to the product and that would be rightmost and we want to add to the sum and then after this we'll just divide it by 10. we want to divide it by 10 so we keep shifting so it would basically be like if we started with 234 we divided by 10 it becomes 23 divided by 10 it becomes 2 divided by 10 it becomes 0 and it'll break out of this loop and then we'll return product minus sum so let's go ahead and run this and see what happens and there we go and let's submit it and there we go so really straightforward this is one of the easier ones i just wanted to help out a little bit and i hope you guys enjoyed it thank you for watching | Subtract the Product and Sum of Digits of an Integer | can-make-palindrome-from-substring | Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.
**Example 1:**
**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
**Example 2:**
**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
**Constraints:**
* `1 <= n <= 10^5` | Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome. | Hash Table,String,Bit Manipulation,Prefix Sum | Medium | 2165 |
494 | Hello hello my dear friend for the question is targets of I will explain the question ok so basically award given in this question a will be given to correct an SMS given date we want targets MS Word question what we can do is used plus minus sign and The equation and the desire or will tell you how fast you plus minus plus okay so basically * * * * okay see you can we use to plus minus news pimple fennel okay so dil se equation this will give out this one correct or following rules possible With its latest plus one plus 2 and minus plus 13101 subscribe to the Light subscribe let's give me to the giver subscribe button way not possible to share so that way MP3 220 how to find how many true how 1000 possible if your problem statement is Clear now so basically letter to convert this question to the question tattoo also folder affects all the question was like this a government was valve 123 that and they wanted final time dream that wikinews saini stayed in plus and minus science that show what we can do Years the latest tried to find out what they are doing arrangement inter science ok like this plus one minus plus three and getting to taste one ok to service properly convey like this oneplus 3 - like this oneplus 3 - like this oneplus 3 - 21 a all negative and positive one plus one who will Again I one correct this is the first observation that was seen it's we're going to write all the plus 2 and all the - 21st open settings plus 2 and all the - 21st open settings plus 2 and all the - 21st open settings please do the thing minus plus 2013 near I'm taking minus sign comment hair oil ready going To get well soon basically that in question was given with elements 123 What we have done with divided into two Okay taking this example - OnePlus one minus example - OnePlus one minus example - OnePlus one minus plus cutting in half 21.12 and the rate side and applied sciences and 21.12 and the rate side and applied sciences and 21.12 and the rate side and applied sciences and the answer is it means what we have divided Into that difference give it means as one - two way give the same difference give it means as one - two way give the same difference give it means as one - two way give the same problem in last to divide this question is * divide this question is * Survey research difference give ok power question statement is channel it means here also you can say exit poll shifting this example ok understand divided Into Two Halves One Does Not Cross Than Any Fear To Inquire Into Death Valley Is One OK Assigned Got What Is The Question Now At We Need To Divide Into Two Survey Research Dad Difference Give It Is The First Question Difference Give The Question No Matter What Is The Value of Is Vansh Vriddhi Phir 12381 Plus Two Plus 2 and All Elements of the Series Page 6 7 What You Want You Are Going to Home Main Tere Hua Tha Okay Disawar Secondary Question Perfect Number 121 Ones Asked One Student Equations with Both of Them Into The time of one is equal to two different class of ok what will be the difference of a the latest check weather we are getting sms1 notes what is the difference between the question difference given was amazed another one to three some where will be seven times 272 plus 1824 It Means The First Subscribe To Be Okay So Let's Check Pyaar Getting A Good Example Plus Minus One Minus Two Plus Reel Andhiri Look So And Way A Plus 2 - 3 Okay So S We Are Going To Write A Plus 2 - 3 Okay So S We Are Going To Write A Plus 2 - 3 Okay So S We Are Going To Write The Last One What Was The First One Does this world or subjects one-way Does this world or subjects one-way Does this world or subjects one-way arrangement so yes hair oil time what is the formal wear getting 40 also give water well s for ok latest on 1 december the latest plus share - share all sorts latest plus share - share all sorts latest plus share - share all sorts of subsidies for it means what one thing date First of all we need to find way to find its ok so basically what is the question converted into elements way 2 f 3 ki and requests ambrose required aap sambhog shyan correct and you can right leg this ok requests MS Word this govinda question what they have Done a divided into two saver is letter this is one and this is S2 true difference giver and this note required request number were correct saunf astar bola babu converted our question into account the number of true rescuers different is difference give dengue to know the best years Were going to solve * Find two variables * Find two variables * Find two variables 125 and Basic Maths eliminated as Survivor Targets 2.1 eliminated as Survivor Targets 2.1 eliminated as Survivor Targets 2.1 Leaves Means to find the number of subscribers to OK and questions converted into like this is it means award given no need to find how many subs Center Possible Hello How Many Subjects Of Possible Through Samay Is Equal To Defeat ODI Test Difference Plus To Will Get To Know That Point To Make One To Your Internet Samay For Watching This 130 Internet Samay 4 2013 Subscribe To Check How Many Sub Scans From This Is the first question of the series OK Not this can't be sold in the multiple choice question More programming I will explain you for the way Dynamic programming OK What they are doing things The base condition located here Another thing what will requested is the choice diagram Okay so address given to connect with elements way to three layers officer 14 and s one is request for correct this question on I also now some find how many true subset is formed at that time equal to for correct this question first of all what we have to Do we are going to find the best condition developed solution what happens is vr trying to reduce the input ok software going to gonda three lines where going to see weather we are getting should be agility and not will go to ok and will see man * Suck this too and don't be drawn man * Suck this too and don't be drawn man * Suck this too and don't be drawn into this one and were going to take decisions I love you will need to selected and liquid correct so I just end value will welcome zero okay soft what do you to take medicine this element dangerous element in this element off This element certifies decision on all the elements correct if it is equal to equal 2012 returns mintu returns phone it means sexual suggestions dualism element is are you going to get at the time 490 never going to get at the time it means this is equal to 04 2012 at 210 Correct Exactly In Record Seat Solution What We Have To Yaar Ullu Straight Minimum Possible Outcomes And Tell Me One Thing Ipsum Vikram 0 Ki Ism Vikram Veer Suppose You Want Samay Jin Officers * Get Yes Points Null Set Officers * Get Yes Points Null Set Officers * Get Yes Points Null Set Show The Sum Of All Elements Of Journalistic 120 It Means Youth Possible Nand Set OK Sorry Now * * * * Return File Member Will Be Our Now * * * * Return File Member Will Be Our Now * * * * Return File Member Will Be Our Base Condition A Perfect Record The Two Things That I Want To Change Only Number of Elements of 0530 Elements in the Are They Not Go into SMS for Soldiers Were 10000 OK Can They Get Dark Yes Any Element Of Possible As They Are Correct Subscribe Now To Receive OK So Elements Of The Year 12381 Samspur Not For Example Late Se Is The Amazing Even Give One To 16 Fall For Choice But To Check Face Elements Greater Than A Stay in Aphid Tell Me One Thing Tips Gyan Arvind Choose Image Want Final Time 406 Give Winners No Stay in So It's Clear Date of Advertisement Is Greater Than The Some Will Not Go Into It's Okay This Is The and Limit View Take Medicine For This Is The Price Of That Choice Diagram A Puppet Show To Some Unknown Puberty We Elements Of 123 Required Spoon Do Ready To Take Decision Weather You Need To Select Real Life In O Kunwar Going To Live Free-Look Daru Will Not Free-Look Daru Will Not Free-Look Daru Will Not Supposed to select 3512 ok so let's as it means ninth sammati ko switch off element subscribe my channel subscribe now to for - dated check weather or not you are going to select element final will reduce final understand subscribe our time ok to tarpan this person time they Need to select OK from the request submit will be easy all - stupid - OK the element - one who already been updated on that be easy all - stupid - OK the element - one who already been updated on that time want to right leg this deaths pattern keyword you can right and the devices using code after late say this question in subjects For I will take a rest size of your name some OK developed solution they need to write 2009 elements in the written S120 by now you all the best way to the perfect choice he told you will not go into what we do the element function Subscribe Spent One Event The Size of Area Will Be Decrease Okay I'm Told You Na 10 Way Support 1060 Don't Want to Select This Element They Need to Listen What Will Be The Rise of Liberty End - Vansh We're Going Rise of Liberty End - Vansh We're Going Rise of Liberty End - Vansh We're Going to Pass the Again But the number of element VPN - to Pass the Again But the number of element VPN - to Pass the Again But the number of element VPN - 1the mid term OK so the health effects of smaller thought it is rear OK what we have for you to take decision come here specific select three and note 3 OK it means view to return to go into right this We Are Going to Live 10th Pass Are the Living Element Nobel Prize Will Be the One Who Will Not Change Without You Are Not Going to Three Final 141 Likes and Subscribe Now to Go to the New Year Spent Elementary Love You to the Element Means the Life Will Be reduced to 100 quite old it will be one - are off and old it will be one - are off and old it will be one - are off and minus one okay adaptive want all the okay so finally Bigg Boss solution what were the best country in the world channel subscribe my videos and the solution as well Dynamic programming basically choice question is this a give you one to three Vivo v5 plus minus point will be divided into different than big b * sum of every day that two variables * sum of every day that two variables * sum of every day that two variables latest decrease variables and find f-18 will be difference plus samosa are by f-18 will be difference plus samosa are by f-18 will be difference plus samosa are by To a perfect done without you know that we address given to 10 minutes check how many truth highest possible at that time say one and finally returned the answer ok I hope you guys solution I will explain what is pollution in dip what do you need to make A Diner Matrix OK Net VPN Plus One 102 Hai What is the Value of and Values for Hai What is the Value of and Values for Hai What is the Value of and Values for Civil Diploma Request Samvardhan 455001 5.5 Matrix in Just Making of Matrix Dynamic Programming What We Do We Need to Field ISRO and Discover Manually Monday Here What is Going Excerpt from To Happen Every Element Is One WhatsApp Message 012 340 12314 Latest Make One Mode Call Rohit R A Perfect Saunf Astpal Here What This Tells This Book Tells That Every Element Is Okay Initiative 123 On This Blog Says That There Is No Element Zero No Element dark you want them one is it possible not possible so we are going to fields with zero phone what is this that you have one element in the detention first limit candidates from 100 chus-chus channel subscribe 280 chus-chus channel subscribe 280 chus-chus channel subscribe 280 possible saiya welcome to use A Flu Field Event And What Do You Want To Reduce 2.20 2.20 2.20 Phase Plus One That I Plus I Hope You Can Feel This Poster On First Elements Very Easily Now Half Lemon Interviews For Deposit U0 Some Plus One And G Plus Dan The Effigy Are Of I - Boys * IS GREATER THAN Effigy Are Of I - Boys * IS GREATER THAN Effigy Are Of I - Boys * IS GREATER THAN JEE SO WHAT YOU ARE GOING TO LIVE THAT ELEMENTS AND DEPOSIT KO MAJEE WILL BE EQUAL TO DEFEAT OF I - BANK BE EQUAL TO DEFEAT OF I - BANK BE EQUAL TO DEFEAT OF I - BANK MAMA JEE I - 100 * LOVES AT ELEMENTS AND MAMA JEE I - 100 * LOVES AT ELEMENTS AND MAMA JEE I - 100 * LOVES AT ELEMENTS AND WE ARE GOING TO NOT TAKE Any decision on the element is what you need to fill the elements of the DPI rate selected all limits for this is the logic to limit the floor with selected 100MB reduce twelve years after - - The Amazing Do you need to return A DP off and comma is summit means a view to return this element What this book tells in this book tells you have all the element alive Hey what are the element wave 2381 request SMS 400 basically what happen and pierce finally I want this position but Instead of directing solution we are going to braid this problem into smaller problem and finally today final solution hair return of hot water complete method video thank you for sharing. | Target Sum | target-sum | You are given an integer array `nums` and an integer `target`.
You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers.
* For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1 "`.
Return the number of different **expressions** that you can build, which evaluates to `target`.
**Example 1:**
**Input:** nums = \[1,1,1,1,1\], target = 3
**Output:** 5
**Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
**Example 2:**
**Input:** nums = \[1\], target = 1
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 20`
* `0 <= nums[i] <= 1000`
* `0 <= sum(nums[i]) <= 1000`
* `-1000 <= target <= 1000` | null | Array,Dynamic Programming,Backtracking | Medium | 282 |
145 | in this video we're going to look at a legal problem called binary tree post order traversal so given that the root of the binary tree return the post-order traversal of its the post-order traversal of its the post-order traversal of its node's value so this question for post-order traversal basically we want post-order traversal basically we want post-order traversal basically we want to traverse the left subtree first so if we given a binary tree so like this right we want to traverse the left subtree first then the right subtree and then the current node right so the order goes like this so left right and then the current node okay and in this video i'm going to show you both recursive approach as well as iterative approach and for iterative approach there's also a couple ways we can solve it i'm going to show you the easy iterative approach and then i'm going to show you kind of like a medium level iterative approach as well as a little bit difficult level of iterative approach and then basically for the recursive solution in this for this problem basically what we're trying to do is we're trying to print the left subtree first and then the right subtree first then the current node right so the goal is we want to traverse this binary search sorry binary tree and we add the uh the notes value onto a list of integers and we turn that at the end right so you can see we have an example of this right this is our binary tree so we're traversing the left subtree in this case the left subtree is null then we're traversing the right subtree so now we have node two also we do the same thing we traverse the left substrate first so we have node three and we're traversing the right subtree in this case null so in this case we have we just visit the current node which is two right so in this case we have three two and then we're going back to the parent stack right the parent uh or the root node and then in this case we just basically add the current notes value which is no one on to the list right and at the end we're basically returning that list and you can see that if we have empty list or empty or just trees no we basically have null right so to do this using a recursive approach what's going to happen is we're just going to do this recursively right we're doing a dfs we're passing the route and then what we're going to do is that we check to see if the current route is null if it's not which is returned we've done our searching right we've done our traversal um if in this case if not then what we're gonna do is we're going to traverse the left side right and then traverse the right side then at the end we're basically once we traverse the left subtree and then we traverse the right subtree we're just going to um take the current route right so if i give you an example uh if i have like a tree like this right so we first traverse the left subtree and left up this note has it'll also have the left subtree so we traverse the left subtree first we know that this is a leaf node so we add a leaf node onto the list and we come back to this node and this node has a right sub tree so which reverse the right subtree and then uh we know that this is a leaf node so we add this node onto the list then we come back to the root of the subtree so it's this node so we add this node onto the list then we're coming back to the parent also has a right sub tree that we have in traverse so we traverse the right subtree which is this node right here we add this node onto the list then we're coming back to the root in this case this root uh this node hasn't added onto the list so we add the current node onto the list right so we basically traverse the left subtree the right subtree and then the current node right and then it's pretty simple if we do it in a recursive approach um and the time complexity right for solving this problem is basically going to be big o of n where n is number of notes that were that we have in our binary tree right and for space complexity in this case it's going to be big o of h um h is basically the height of the tree right we basically uh doing a dfs and then once we uh you know reach to the end of the tree right the end the word to a leaf node where he basically um coming back to the parent stack and then do and then traverse down the right subtree right so in this case the space complexity in this case is just going to be big o of h now let's take a look at how we can be able to solve this problem using iterative approach and by the way the code is in the description so let's continue watching uh what we can do is we can use the um we can do the same thing that we did in pre-order traversal right so did in pre-order traversal right so did in pre-order traversal right so pre-order traversal we visit the current pre-order traversal we visit the current pre-order traversal we visit the current node which reverse the lab subtree and then the cur the right subtree so what we can do is that we can basically do the same algorithm and then we're just going to append the node right the current node um last or sorry the first right so that we can always get the orders that's the opposite of the pre-order that's the opposite of the pre-order that's the opposite of the pre-order traversal right so for pre-orders traversal this tree is so for pre-orders traversal this tree is so for pre-orders traversal this tree is basically two um the left subtree is just one the right subtree in this case is three and then the four or sorry four and three right because we're going for the current node and the left sub tree in the right subtree but in this case the post order traversal in this case is going to be different because we're visiting the left subtree first so we have one and then we have three we have four we have two right so you can see this is basically the left subtree and this is the left subtree of this node the right subtree is null and then the current node right and then we have two is the current node as well um so in this case where you can see the order is always pretty much like the opposite right so in this case um you can see right we have two we have four three which is the right subtree we have one which is the left subtree so it's left the right subtree and then the current node left subtree right so what we can do is that we can basically just add it differently like so we can basically have a list and we can always add it first so in this case when we enter this loop we have no two so we add the root onto the stack and then we just pop that stack off or just pop that note off the stack and then what we're going to do is we're just going to add it on the first right so in this case we have no two um here right or just no just two right and then what we're going to do is we're going to traverse the left side first so because we're using the stack so that the last element um in this case the last element in is the first element l so we're basically adding the left node first right so in this case no one and then we add in the right note first so notice that we're basically traversing the right side first so in this case you can see it's the in this case here you can see it's the left the right and then the current node right because you can see we're always appending first so in this case we pop the top element out of it so sorry this should be four right okay so we have pop four out of it right so we know the four has the left subtree and the right subtree so we add that onto that as well so in this case we add four onto the list right because here and then four has a left subtree so we have um at three under the stack right and then in this case what's gonna happen is that 4 does not have a right node so we continue so then we pop the top element off the stack so it's 3 so 3 has is a leaf node so we add 3 onto this list and then what's going to happen is that three is a leaf node so we don't add anything onto uh the stack right so then what's gonna happen is we're going to um take out the last element out of the stack so which is no one so in this case we add one right first so this is our list right which is identical to this so notice that we're basically going uh to basically um go for the left sub-list right or subtree and then this sub-list right or subtree and then this sub-list right or subtree and then this is basically the right subtree and this is the current node right so you can see that we're basically just going to put where we're actually just going to visit the left subtree last and the right subtree first and then in this case we're always append that right we're doing the pre-order right we're doing the pre-order right we're doing the pre-order traversal algorithm but we're just going to append first right so that we have the current note um at the very last and then the left subtree at the very beginning of the list and then the right subtree after the left subtree right so what are some other ways we can be able to solve this problem using iterative approach like how can we be able to traverse the tree by insert the each and every single node last instead of insert first right because previously we're basically insert each and every single node first onto the list right so how can we be able to insert last into onto the list so what we can do instead is we can basically uh traverse the tree um and the problem about post-war traversal is that about post-war traversal is that about post-war traversal is that we don't really know if the if we already traverse the current those children at all right because for pre-order traversal because for pre-order traversal because for pre-order traversal we're going from the top to bottom right we're working our way down so we know that we already visit the current or the parent node already because we're going from top to bottom right but the thing is that we're going but post water traversal we're going from bottom to the top so we don't really know if we already visit the current those children at all right so if i'm at no two um right i came from here and i go down visit the left sub trade the right subtree but then i come back to the root which is no two how do i know if i already visit no four and no five right how do i know that so what we can do instead is we can actually be able to delete the connection right in the binary tree so in this case we can delete this connection so that we ensure this node is basically a leaf node if it's a leaf node we just add it onto the list right so let's just go through this so basically what's going to happen is we add the root onto the stack now we take it out we know this is not a leaf node so what's going to happen is we're going to add the children right we have no three notes that we're adding no the right note first and then no two and then we take the top element out of the stack and then we know that no two right um because in this case we know that uh oh sorry we're saying peak so in this case we have no one no three and no two right so we peak right so in this case we know the node two um has is not a leaf node so we're adding its children so we have note 5 and we also have note 4 right and no 4 is leaf node so we take that out right because this is a leaf node so we take it out we add it onto the list and then we just pop it out right and then what's going to happen is that we basically just take the top element or peak the top element on the stack so there's no 5 is a leaf node so what's going to happen is we're just going to remove that right so in this case we just added on to our list and then you can see that one when we add the uh the left and the right node we're actually deleting the connection so in this case we're adding node four or no five we're deleting that connection when we add node 2 and node 3 we're deleting that connection right so what's going to happen is that we're basically take the top element out because node 2 is now leaf node so in this case we pop that out and then we add it onto the list and then the next thing that we have here is node three nodes three we basically uh it's not a leaf node so we add its children in this case we have no six added onto the stack right and we make sure we remove that connection and then what's going to happen is that we know no 6 is a leaf node so we just leave that out a bit right so in this case we have no 6 out of it and you can see we're just going to basically left with no three right so in this case we have no three is a leaf node so we add no three onto the list and then we also left with no one right so in this case we get this as our answer right so this is also how we're going to do it but the thing is like what if we don't really want to modify the tree right what if i don't want really want to delete that connection what can we do so this approach is kind of very similar to the in-order of very similar to the in-order of very similar to the in-order traversal problem that i did so if you haven't took a look at the in-order traversal took a look at the in-order traversal took a look at the in-order traversal problem that i did please take a look it's very similar we're using a variable to keep track of the nest or in this case a temporary node now we're about to traverse right so in this case you can see we're starting and we're basically didn't really add any node onto the stack and then what we're going to do is that we're going to have the current node is equal to root which is node 1 right and the previous is basically null for now so what we're going to do is that we're going to say current does not equal to null okay so what we're going to do is we're going to add the current node onto the stack so we have no 1 right onto the stack and then current is equal to current.left equal to current.left equal to current.left so now current right is basically node two and then what's going to happen is we're just going to um continue right so then we check to see if current node is does not equal it is does not equal not in this case it doesn't so we just keep adding the left node right so the goals here you can see we're basically just adding the all the left node until we get to current is equal to null right so we add no 2 we add no 4 until we get the current node is actually equal to null so then what's going to happen is we're going to take the we're going to pick the top element on our stack in this case the node four we know that node four dot right is equal to null right so what's going to happen is we're just going to add this leaf node onto the list and then notice that we're what we're trying to do here is we're basically pop this node out of the stack and then uh we're just going to get pre is equal to top right which is basically so pre is basically now equal to node four and then we have current which is equal to null and the reason why we get current is equal to null here is because we want to not traverse the left side again right in this case you can see we take the node four out and then currents go null so it will continue to go down this path the else statement right here right so it will not go down so notice that the if statement above this condition right like if current does not equal null this condition will just keep trying going down right keep trying going to the left side until we hit null then we're just going to try to traverse the right side right and this is what we're trying to do here is we're trying to traverse the right side and in this case you can see current is null so we take the top element outlets or peak the top element in this case node two dot right is in this case uh is not null right so what's going to happen is we still have to traverse the right subtree so then what's going to happen is we're gonna get current is now equal to what equal to node 5 right and in this case um pre is still no 4 because that's the last element that we inserted onto the list okay so then in this case what's going to happen is we're just going to add no 5. uh sorry in this case we know that no fi current is does not equal at all so we add no five onto the stack and then current is equal to current.left which is pretty much null current.left which is pretty much null current.left which is pretty much null now right because node five is a leaf node so we have null um and then what's going to happen is we're just going to uh go down here right because now the current node is null so we pick the top element in this case no five uh that right is null so in this case we're going to take that note out of the stack and then we're just going to add that onto the list and then we're just going to get current is going to null um and then pre is equal to the last element or the note 5 now right okay so then what's going to happen is that we set current is going so we continue to go down this path again right so now we're uh we're continuing the loop and then because current is equal to null so we go down here so we pick the top element which is node two so we know that node two dot right is not null okay but the thing is that we already keep track of the previous element right which is no five we know that top down right is equal to pre which is node 5 which is the node that we already visited right so what's going to happen is we can basically just add node 5 right or sorry just take this note out because we know that we already successfully traversed as children so we have no two here and then in this case we basically have no two as the previous node or yeah the previous node and then the current is equal to null right because in this case uh we're can we want to continue right going uh to the top right trying to go back to the parent node in this case no one right so the last element is no one in this case uh we peak in this case no one right so no one in this case dot right is not null and dot right it does not equal to no two so what's going to happen is we're going to get current is equal to uh in this case the no three right so in this case note three is basically the right child no one so we're just going to go traversing down the right subtree right so i won't try to finish this walk through now pretty much you get it right so we're basically trying to use a previous pointer keep track of the right uh the last note that we inserted on the last notes value inserted uh sorry the last note that we take it out of the stack so that we can compare to see if that node is actually the right node of the current nodes subtree right if it's if it is we know that we traverse all the children of the current node otherwise we going to basically traverse the right stop tree right so you can see that this is basically all the three ways that we can be able to solve or in this case all four ways because including the recursive approach so these are all four ways we can be able to solve the post order traversal and you can see the space and time complexity are pretty much dissimilar like they all have a time complexity big of n and space complexity of big o of h right so there you have it and thank you for watching | Binary Tree Postorder Traversal | binary-tree-postorder-traversal | Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the 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,776 |
142 | then play cycle 2 giving a head of Link this return the node where the save will begin if there is no cycle return now there's a cycle in English if there is some note in the list that can be reached Again by continuously following the next pointer and internally position is used to denote the index of the node that the tail next pointer is connect to index is negative one if there is no cycle know that the position is not past this parameter do not modify during this so here's the example for example we have this link list as we can see when we add next to four we point back to 2 that means its form a cycle and uh two is where the cycle starts so we need to return this node with value 2 . another example we have one two and . another example we have one two and . another example we have one two and two point to the point back to the one and then we have a cycle and the circle starts from uh the node with value one so we return this node and then if you have just a link this with a single node that means there can be have uh they cannot have a cycle that means we will return now and for this question I'm gonna use a iterative approach I'm gonna looping through the link list and I will have a two pointer one uh slow and one fast this little pointer will be moved one node at a time the first printer will move two node at a time whenever they match each other that means there is a cycle in the link list and then I will set the slow pointer to the Head and then I will start moving those two pointer one node at a time and then whenever they meet this will be the starting point of the cycle and then I will return that note now we can implement the code so first I will have a list note called slow according to the hat first and then this note called Fast also point to the head first and then I will have a while loop so well uh we don't want to have now pointer exception so well fast is not equal to now or fast uh next is not equal to now that means we didn't reach the end of the linked list uh so like here when fast enough when fast is equal to now that means we reach the end if the faster next is equal to now that means we also reached the end because we don't want to go too fast the next or next that will give us non-pointer exception and then I will check I will start moving post pointer I will move it slow equal to slow down next uh fast equal to faster next the next and then if at some point so you go too fast that means they met that means there is a cycle and then uh if period cycle we I want to set the slow pointer to the pad and then I will have a while loop so well slow it's not equal to fast I will keep moving them one node at a time so slow you go slow to next fast equal fast the next and then whenever the value break that means they match in that case that's the node where the psycho started so I will just return one of node I will return slow at this uh and then if the well if we exit the outer well Loop that means there we have reached the end of the English that means there's no cycle that means we will return now like the question asked and then maybe we can lastly have some edge cases so we've had equal to now or at the next equal to now we will return now because if headaches now that means it's an empty linguist with no note and if I had done next to you to know that means it's a linked list with one node in both cases there is impossible to have a cycle so therefore we will return now and then next let's analyze the time complexity will be uh of n because we use a while loop and then for the space complexity will be o of 1 because we only create few variables which use constant space next Let's test this out looks like we passed the test | Linked List Cycle II | linked-list-cycle-ii | Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
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 (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
**Do not modify** the linked list.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** tail connects to node index 1
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** tail connects to node index 0
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** no cycle
**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 | Medium | 141,287 |
1,184 | in this video I will solve this between bus stops from wig code so in this problem we are given and bus stops and they form a circle and we are also given distances between all the neighboring bus stops and our bus can go along in both of the directions so it can go clockwise and counterclockwise and our problem is to find the shortest distance between given start bus stop and the destination bus stop so let's look at the first example here we are given for bus stops and distances between them so we have two ways to go from 0 to 1 and we also can go from 0 to 3 then 2 and then 2 1 but we can see if the shortest path is from 0 to 1 because it is only 1 point and in the second case the shortest path is from 0 to 1 and then 2 because it's 1 plus 2 3 and it's less 4 plus 3 7 so this problem is very easy one so we can just count you can just calculate both distances and return the shortest one let's declare these two distances clockwise and counter clockwise and then we'll iterate our vector from size I plus and then we will check if I is greater than or equal to start and I is less destination then we will add the distance of between current stops to clockwise direction and else we will add it to the counterclockwise direction then we'll check if clockwise direction is greater than counterclockwise direction then we will return counter so counter clockwise direction and else will turn clockwise direction so ashamed is solution now wrong answer strange we are the input is seven and two okay so our start or the number of the starting bathtub can be greater than the number of destinations top solve this problem let's just check if start is greater than destination then we will study swap start and okay it's accepted now thank you for watching this video and please subscribe to my channel and ask me to solve other legal challenges in the comments below | Distance Between Bus Stops | car-pooling | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given `start` and `destination` stops.
**Example 1:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 1
**Output:** 1
**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1.
**Example 2:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 2
**Output:** 3
**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3.
**Example 3:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 3
**Output:** 4
**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4.
**Constraints:**
* `1 <= n <= 10^4`
* `distance.length == n`
* `0 <= start, destination < n`
* `0 <= distance[i] <= 10^4` | Sort the pickup and dropoff events by location, then process them in order. | Array,Sorting,Heap (Priority Queue),Simulation,Prefix Sum | Medium | 253 |
144 | all right let's talk about binary triple the traversal so pre-order traversal the traversal so pre-order traversal the traversal so pre-order traversal mean you are yourself you are your left you are your right and if a list is uh av i mean i created this right if a root is not it's equal to no so if a blue is not i can return this and what i do is i have a stack as stack is like saving the adreno so while stack is not empty and root is not known i can traverse the traversal root right three sorry so while root is not known i add the value because i can add myself right i add a value and i push the trig node into a stack and i keep going left right so this is mean i before i go left i need to add myself right that's the idea so when the value i mean when where ru while loop break is mean rule equal to no right so i can reduce the variable to root you're going to stack a pop so you will pop like for example you will pop a wine right and i can say root equal to root right i'm going to see if there's any things on the right if there is i can keep inside the while loop and keep going left and if those tree is pretty big or the tree is small if your right is not normal i mean if the right is no you are not inside this value you're still popping you i mean you are still pop right the side is still popping if the right is equal to no you pop if a right is not known right you keep inside the value and you just return to this okay let's run it okay it's pretty good and i should pause and you should pass okay let's talk about time and space you need all the fun to store every single element inside of this and definitely stack right so they are separated so all of them right and for the time complexity you need to traverse the traversal tree right so it's all fun the idea is pretty straightforward but just think about it like when should you add the value into a list and when you push or push a stream into a stack and how do you like go left go right that would be your ideal solution but this is mine and pretty straight forward and all of them for time and space and good luck and like a question like the video like yourself | 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 |
392 | Well, it's in the golden cage, our 3D up's c, they wrapped it in the microphone, Ah Sumina, the 2nd team, without Corliss, Guns, so uh, even if you use it's done with PVC, the B side, maybe the Seventh 4, the maximum LSC course, which 103 days ago, the capital city Whisper You and I hang out, drink quickly, there is no reading, Tae-woo Jeong, more bin than me, Yeon-woo's Latina, spurge suits, second pcell no reading, Tae-woo Jeong, more bin than me, Yeon-woo's Latina, spurge suits, second pcell no reading, Tae-woo Jeong, more bin than me, Yeon-woo's Latina, spurge suits, second pcell space is a b c d focus, a c e s ceases to helm, mermaid o i was, please ah, what are you using? Remember Ren's darkness, inhalation, my sister, quilted, line, sol m, in sc course, ost 2 anders sso series se reflexes in yonsei baxter sleep so as i exist, mi na db, schnell slant, so these days, the sum that is being paid out is the investigation and my mbc do the rest swish sauce initial spot can be of some help service or twin can be um listen to words from overseas due to cs our sls sles cst sci source soon il sang soon there a can you do it sie es sein emerson friend nen 4na nj can nail mist oz v10 monster world jason lee s i anderson slice and list and distance senti shun max tissue stars tex pester line ssss bullet better sl final this scales of root next year cern in ai issue pes mp10 cube house bidon Toss is already this green mountain reader Shen Shana Miss Dachau procedure now the law what can't come now there is everything meaning each speed cs service i see srs down hidden sun 1l sm4 else iceland friends source camping raw 3 adi hull appearance not in ohol declaration In the interest of Nietzsche Seo-ya dei, my appearance is steel, finance, Seoul, declaration In the interest of Nietzsche Seo-ya dei, my appearance is steel, finance, Seoul, declaration In the interest of Nietzsche Seo-ya dei, my appearance is steel, finance, Seoul, fly, write 3 me to ipod, why the service, the universe, the shortened lend a b c e s, without the gun service, nfl sax c, so among the cucumbers, it's okay, now the amplifier, this is ah, these people are comparable. So people column stainless steel 9 now alcohol bum window also lived and now this sample source that story sci erm island bios ox I d line shirt with musso presidential election jam d line finance soul tax stove accumulated soul only proviso your child gross come Came and blew 70, but Nana's best solution is the source underneath. Our buffet app wouldn't have been excreted, but the lsd accident that I leased and forgot is now much more spread out. Short 1 Ah # The senses that are attuned to the pursuit | Is Subsequence | is-subsequence | Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code? | null | Two Pointers,String,Dynamic Programming | Easy | 808,1051 |
771 | okay welcome to my channel i'm here to do my hundred little challenge today we have leeco 771 juice and stones your given string juice represent the type of stone that are jews and stones represent the stone that you have each character in stone is the type of stone that you have you want to know how many of the stone you have also jews leather are case sensitive so that a is considered different type of stone from a capitalized okay this question is really easy and you can tell in jewelry type f2 one small k lowercase a and uppercase a there's two type of jewelry and here you have this character a and this two character so you have three stone that you have are jews so in here only z lowercase z um is jewelry but you don't have any jewelry in your hand so it's output zero so what we can do is have a set put every uh character in the juice inside the hash sects and loop through the whole stone string see if that character is inside the headset if that's the case if this is this character is in the headset then we accumulate one then eventually you output the account then that's it for this question let's take a look at this code now we have account and then um we have set of character um we call set equal to hash set now we do we put every character in string j um character in string j into the set oh now set will have all the jewelry you have now you have to check your hand so for character um another c check every character in string s and see if that character is inside the headset or not so if set contain c then count should be incremented by one that should be it and return count i think this is pretty simple question for or warm up with how to use a headset and that's it for this question yeah so if you have any question please comment below and i will see you in the next video bye | 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 |
253 | hi i'm ali today i want to talk about another important interview question this question is called meeting rooms and it is among one of the most recurrent and important interview questions this question has been asked by lots of companies like amazon google facebook bloomberg and others so in order to solve this problem let's first read it carefully and understand it don't forget to ask clarifying questions when you are reading the problem it shows that you are invested in the problem for example you can ask about boundaries or problem dummy before i explain today's problem i should say that this problem has two versions today i want to talk about the second version that you can see here as you can see we have been given an array which shows the meeting intervals and we should calculate the number of rooms required for all of those meetings to be held so i'll explain the second version with two examples that the question gave us the first example gave us three time intervals as you can see and the output is two which means we just need two rooms for all of these meetings so the first meeting starts at zero and ends at 30. as we don't have any room yet i assign a room to this meeting so this is my first room and this is my first meeting the second meeting starts at 5 and ends at 10. so as you can see when this meeting wants to start this meeting hasn't ended so we need another row and i assign this meeting to the second row but the third meeting starts at 15 so by the time that this meeting wants to start this meeting has already ended so we can assign the third meeting to the second row and that means we just needed two rooms okay let's see the second example in this example we are given two meeting intervals and the output is one okay so as you can see the first meeting starts at seven and ends at ten and the second meeting starts at two and ends at four okay so i'll start with this with the second meeting so i assign it to a room this is my first room and this is the second meeting and by the time that this meeting wants to start this meeting has already finished so i can assign also this meeting to this room so we just needed just one rule i hope you understood this problem thoroughly and on the next step i will talk about some algorithms to solve this problem before i talk about the suitable algorithm keep in mind to captivate the interviewer with your thought process because they are searching for those great problem solvers that can also present their ideas so now let's go to the algorithm and see how should we solve the problem now that we understood the problem completely i want to talk about the suitable algorithm to solve this problem there are two algorithms that we can solve this problem with them the first one is called priority queue and the second one is chronological ordering i'm going to solve this problem with chronological ordering algorithm consider this is the array of our time intervals what do i want to do is to separate the start times and the end times so i will have an array called start times and i will add the start times in an increasing order into this array so this array would be 1 2 3 8 10 and 11 and i'll do the same for the end times so my end times array would be 7 10 12 19 20 and 30. so then i want to build a table with these two arrays in this manner so that would be my table this is my start time and this would be my end time so i put 1 7 2 10 3 12 8 19 10 20 and 11 30. so now i'm going to check each of these start times with the end times and with all of the end times and by comparing them if i find a start time which is bigger than the end time that means that i have found an empty room and i can assign that time interval to that row so consider i have two pointers here one for and array and one for start array so first we compare one and seven one is lower than seven so i have to assign this time interval to a row so i'll look the one time interval here in the array it's 1 to 10. then i move the start pointer the second one again two is lower than seven so i should assign it to a new room so that would be two to seven again three is lower than seven so i'll add 319 from the array and the next start time is eight which is bigger than seven so that means i have a room here that i can assign this time interval to that room and i do not need a neuro so let's look at the eight it is from eight to twelve so as you can see this meeting has ended on seven so i can add this meeting to this room which is eight to twelve then i should also move my end pointer too when i found you know i match the condition so my end pointer would be here and my start pointer would be here okay so 10 and 10 are equal so it is also match with our condition so it means that there is a room that i can assign this meeting to that so as you can see here this meeting has ended on 10. so i can add this meeting to this row and i do need to change the end pointer again and also the one okay so as you can see 11 is lower than 12 which means it is lower than all of the other end times because it is a sorted list so i should assign this time interval to a neuro and that would be my fourth room and i'll add this time to this row okay so we have assigned all of the time intervals or our meetings to the rooms with this algorithm and i hope you have understood this algorithm correctly and completely on the next step we are going to write some code and analyze the complexity of this algorithm now that we understood the problem and the suitable algorithm let's talk about the code so as you can see here i have a method in my solution class called mean meeting rooms and this method is an integer method which returns the number of used terms this method takes a 2d array called intervals as an input and i first check the length of this array so if it's null i do not want to process that and then i built the start and end arrays and i assigned values from the intervals to the array to that and then i sorted these two arrays in increasing order because i want them sorted in order to check them then i defined two pointers the start and the end pointer which are the pointers on my start and end arrays as you can remember in the algorithm we had two pointers and we moved them on these two arrays in order to calculate the number of rooms required and i also have an integer variable called used rooms which calculates and counts the number of used rooms for all of those meeting intervals so this is my main algorithm this is where the main algorithm happens in this while loop i just check if the start pointer which means the pointer on the start array is less than the interval's length which means we still have meetings to operate inside my while loop i have an if statement and in this if statement i just check the start and end times in the start and end arrays so if the start time is bigger than or equal to the end time that means that i currently have an empty room and i do not need to assign my meeting to a neuro so i decrease the number of used rooms by one and i also increment the end pointer by one based on the algorithm outside of my if statement i incremented the number of used rooms by one because that means that i do not have an empty room now so i have to assign my meeting to a new room and i also incremented the start pointer by one based on the algorithm that we discussed earlier and at the end i return the number of used rooms now let's test our code and see how it works so here i wrote the two examples the two meeting intervals that the question gave us so with this example with this array we expect that the output will be two and that means that we need just two rooms for these meeting intervals to be held so let's run the code and see the results okay as you can see the result is two so it seems that our code works properly with the first example and let's go through the second example too uh the expected output of this example is one so let's see the results so as you can see here the output is one and it seems that our code is running properly so now i want to submit our code in to see the final results so i'm here let's paste it and just submit the code so it was successful and to show you the results in more details i go through this section so yeah our code passed 78 out of 78 test cases and our runtime was 6 milliseconds and our memory usage is about 40 megabytes as you can see our code was accepted and we are here uh in the runtime based on the run time we are here so we are better than 75 percent of java submissions uh and you can see here about the memory we are using this amount of memory and yeah so now that we are sure that our code works properly i want to talk about the time and space complexity of this code the time complexity of this algorithm is an order of n log n because as you can see here we are sorting two arrays individually and also we assumed that each of these arrays has n elements so the time complexity would be an order of l log n and this space complexity is an order of n because we have two separate arrays the start and end arrays and each of those has n elements | Meeting Rooms II | meeting-rooms-ii | Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106` | Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room. | Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue) | Medium | 56,252,452,1184 |
791 | everyone welcome to my channel so in this video there are two goals the first goal is to see how to solve this problem and then we are going to do some live coding the second goal is to see how you should be helping in a real good interview so before we start the real content for today i would really appreciate that if you can help subscribe this channel because it can help this channel to grow so thanks in other words let's go through this question remember the first step in the real code interview is always try to understand the question so please don't jump into the coding part too quickly so first ask some questions if you don't understand some parts and also at the same time think about some ash cases you need to take special care of in the next step so let's read through this s and t are strings composed of lower case letters in s no letter occurs more than once so s was sorted in some custom models previously so we want to permute the characters of a t so that they match the other that s was sorted so more specifically if x occurs before y in s then x should occur before y in the return string okay so return any permutation of t that satisfy this property let's see the constraints it says that s has a lens at most 26 and no character is repeated in s all right so s contains uh characters up to 26 and no duplicate so t has a lens almost 200 smt consists of lowercase letters only yeah that's a good to know stuff which is a largest letter only so this means uh that um yeah so that this means that we only consider 26 characters here so the next i don't well i think currently the i don't really see some clear ash case here so if we think that s or t can be ash case uh when they are empty that could be ash case but i think it should be covered in our general garden so let's see how to solve this problem so we could use something similar to barclays to bucky sort so essentially you're going to go through the t do one pass through the string t and then uh get a map so the map is from the character to the frequency of the characters within t so we are going to go through the strand t once do one pass and then get this map and then after that we are going to go through the characters within us uh from the start to the end so if the corresponding character has a frequency larger than zero then we are going to uh insert the number of the character like i said the a appears three times and we are going to insert a into the stream builder three times so because we go through this uh as uh from the start to the end then we should be able to keep the order of the corresponding character so it should be we should have a uh a other which is the same as the characters in string as and after that after we go through that uh we need to also go through the other characters that are not within us to make sure that uh we include everything within uh t so having said the runtime is going to be olive n maybe let's say all of t so t is the length of the string t because the length of s is uh up to 26 so this is a constant stuff so we don't need to worry about the length of s essentially all right so having said that let's uh do some coding work so for coding care about the correctness of the code readability of the code and also don't be too slow because there is any there is a limitation on the interview time so first of all we need to have a map um so the map is going to have the characterize the key and the integer which is the frequency so let's say this is car free map is new so we are going to go through everything and then form the map here so um uh okay so car c is equal to t dot to car array so car free map dot put c car free map.get c car free map.get c car free map.get or default this is c zero plus one so until now we have the character and frequency map form here for string t and the next step is for us to go through everything so within the s so let's say car c is from c dot s.2 car array s.2 car array s.2 car array before that we also need to have a string builder so we use stream builder here because it can help us to speed up so if you use string then every time you're going to get another string which is going to be horrible regarding efficiency so we use string builder here so string builder uh well we will have um mine is equally well uh okay so it seems to be like if not uh car free i have falcon tinies so if the car free map doesn't contain the so if it let's see so if the car frame might doesn't contain the key which is a c then you're just going to continue otherwise we need to insert the number with frequency for the character uh smaller than car three dot get c and the plus i append the character and finally we are going to remove the thing from the uh from the map and at the end i think what we should do is uh we should go through the rest of the characters uh within this car free map so uh we are going to do this again actually um so yes i think this one coffee macbook contains the key it should be actually it should be car free map dot key set and then we just don't need to do continue here because everything is should be considered should be within the car framework all right so i actually don't need to remove here as well and finally we return a speed.2 string so i think that should be pretty much it uh let's do some testing let's make use of this platform to help us do some testing so testing is a very important part please don't forget to do testing after you're done with coding so for simplicity we just rely on this platform but in real interview you need to have your own way to do the testing all right so um i think we should be good about this question um so that's it for this question if you have any questions regarding the solution or regarding the coding whatever feel free to leave some comments below so if you like this video please help subscribe this channel i'll see you next time thanks for watching | Custom Sort String | split-bst | You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**. | Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right. | Tree,Binary Search Tree,Recursion,Binary Tree | Medium | 450 |
1,043 | Problem 1043 Partition Here For Maxim Sir Problem Statement Is Given Darkness Name Se Z2 Play N To Continue Savera Length Don't After First Name Is Savera Hair Oil Change To Bank Wave New Updates Amazon People Have Been Told We Have Said This And people have to share the size of donut which is in the lunch survey, we can divide it and after division, whatever will be in the morning, then whatever will be the increase in the morning, like the pose in the morning, when and this morning, the excitement is of three, then in this Also, if we have taken this support of 20, then what will be in it, after partitioning, its value will go. What is the fee for making Maxim Holi from 100 feet, then this will also be removed. The value of intake will be updated and shifted by increasing by 5109. He is not saying anything, so now what has he given us in the East Zone, the return is also the largest Samadhi, after partition into parts, it is not a good politicizing system, it is the day, so how can the test related dancers be proved again, test cases on 300-400 people. Let's see test cases on 300-400 people. Let's see test cases on 300-400 people. Let's see Dimple number one is given that one is ready or allowed, they all understand the status, all of you people have given the initial one, hey given, what will we do with this, people will do this in DP and the DP will tell Anjali. The DP will tell us what is the maximum amount that we can get for the next few years, support me, when the volume comes, we will use it, so there is no option in this, either only one coriander is available. You can use it Sir DP's person will become OnePlus DPI Mention Some people give one feel here who think that we have to use fake, this is it, friend, you guys will grease it or will use both of them sugar mulay ko single If I choose then how much will be its test best? We will take a variable which will tell us that if we use this then how much will be the best. Waste is equal to what will happen if we use feel in 10 inches then this value will be Which will be on DP, this will be different itself, so if we call Paytm as single year, this is so much, this is different, if free mode is on, if they are single, then what is its value, what is the height of DPI - 110 DP OnePlus 15-9- It will be 2016 DPI - 110 DP OnePlus 15-9- It will be 2016 DPI - 110 DP OnePlus 15-9- It will be 2016 and what is the length of the vest? 16A and one of us is the front. If we use it together then what will happen to the shoulder EP0 plus and how much will it be updated? Shift 3000 plus0 plus 230 will be updated. How many thirty will be reached here because of this supposition, then the best jubilee here will be 3830 thousand suppositions. Now what do we do with those people, let's see together in these days, what will we do to clear the follow on 115 700 157. You will take the seven single-handedly. If the group takes the seven single-handedly. If the group takes the seven single-handedly. If the group takes the seven single-handedly then the best will happen single-handedly then the best will happen single-handedly then the best will happen and the best will be given here and the waste is equal to what is now. If we only take the team as a single layer seven, if we remain alone then the best. It will be said thirty plus episode 237 Utsav vestige will be 137 if we take 5007 together then what is the value of these two sevens or 1538 so now whatever is will be best OnePlus was one plus that is 3131 37th and how much is it So, we will keep this 70-80, now we have given how much is it So, we will keep this 70-80, now we have given how much is it So, we will keep this 70-80, now we have given only how much time to these three, don't we can take the team along, if we can take these three together, then only these people will not go under Chiffon President, this is the best to spread. It will cost so much to go to office, now you can't do anything more than its star, you can value it, at what time will the flavor come, if we look for it online, no single will use it manually, then how much will be the best here, the servant shift will suit single ladies. It will happen that if we take it single-handedly, that if we take it single-handedly, that if we take it single-handedly, now if we take a seven and a nine together, then 797 remain, so the maximum in this will be the maximum line which is 1930, sure Gu Shyam people, Vestige will remain for those people only. It will remain only chiffon, if we then take these three, let's do all this, what is the maximum in this, 15th 3315 more 6.06, we will not take it here, we will 15th 3315 more 6.06, we will not take it here, we will 15th 3315 more 6.06, we will not take it here, we will let you people keep only this much, then they will be given the name of Shyam Blood Bank. From this side, if Fragnet takes all this, then only we have taken these three together, so we cannot add one, we can take the maximum that we can take, so we can take this, that is why those people 192 will be shifted in the same manner, then we will continue to move forward in this tube will be in this, the tube is not a bar, we will take it with the note, we can take 192 together as advanced, in the same manner, the future GDP will be further increased. People will return the last DPN. Everyone used to call it a body part, so called invite prof and whom does Sonu try to support. Now they remove it. Sohan, what did people do to Sara here? Hey, their living has become fanatic, let's find out the size of that side, break one of their pimple admin group and here people and zone DP was taken, for what size was it, for the size of one plus one because from those people Will start the deposit click. We were assuming it to be zero and we will make the entire balance zero from ma'am. This is - 4a we will make the entire balance zero from ma'am. This is - 4a we will make the entire balance zero from ma'am. This is - 4a that maybe you like Shayari's massage of Hrithik Majar when DP 's Sudan went to 10 and in its place 's Sudan went to 10 and in its place 's Sudan went to 10 and in its place all these people are in a loop. Will run the event from intangible to one Are equal to the end because I am running on DP I 1 second look Now here we will have to do world in the match For that less people will fast That when Meghnad's request card must be made Of a best type Let's create a variable, its value will keep the exit poll of the interview broken. Now we will run a loop which will run from one to k. The value of this garlic and is equal to k and the value of i - g is greater than are equal to two. value of i - g is greater than are equal to two. value of i - g is greater than are equal to two. Below zero, if one goes out of the tax, induction map goes into minus one, then its type is there is an index, then people have to keep this thing in mind. Sorry, here we have made JJ Singh's In Like Available first. Here is the list of Plus and Sonu, where do we start the Mexico Rally, which will be Max, it will tell us what is there till now, what is the value from I to K, how much we will remove, the age of 18, what is the maximum in it, then the maximum of Mix Earn, I - Yes. This is what Gallu told that Max told that - Yes. This is what Gallu told that Max told that - Yes. This is what Gallu told that Max told that waste juice will be the best visual to maximum of waste. What did DPI do - the one who used to take plus chumma used to sleep. DPI do - the one who used to take plus chumma used to sleep. DPI do - the one who used to take plus chumma used to sleep. How many people have been very angry with him, if he is taking it once, there are three who are taking the medicine. How many are there, he will tell. Now the people here will tell the value of DPI, whatever is the value of those people and the waste, they will return it to the people in plaster and VPN and after dropping the rupee coins of the return DP, they will see that their play will be run too. It is taking some time, Akshay has been updated, let's see after submitting, it is a little time, similarly, we have given this question on gas, people started the above follow, they burnt it for DP, GDP which is till now, GDP which is waste oil. Yes, how much will it be, what is the maximum in this, he is telling that as of now, John people are running, who will make one cup, two cups, three rooms of stars, which layer, then how much is the maximum one and what is the waste. Whatever is the Western low maximum till now, we can mix it, so how many times we have to take the maximum which is there, it is telling that the page is as if it is dirty, that is why it has been done here that I Why should they give energy, they will make it difficult once, then twice, then again, thrice, how many times have they filled it and the DPI, which I have been filling till now, before reminding them with this, I will give it to them in jeep and lastly with different pattern. If you guys have fully understood all this then thank you for watching my video. | Partition Array for Maximum Sum | grid-illumination | Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer._
**Example 1:**
**Input:** arr = \[1,15,7,9,2,5,10\], k = 3
**Output:** 84
**Explanation:** arr becomes \[15,15,15,9,10,10,10\]
**Example 2:**
**Input:** arr = \[1,4,1,5,7,3,6,1,9,9,3\], k = 4
**Output:** 83
**Example 3:**
**Input:** arr = \[1\], k = 1
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 500`
* `0 <= arr[i] <= 109`
* `1 <= k <= arr.length` | null | Array,Hash Table | Hard | 51 |
203 | Lead Code Question 203 Remove Link List Elements It is written sir that you will be given the head, the edge of the link list is normal and an integer will be given, whose value of node will be equal to this integer, you have to remove that node from the link list. As you will see here, value equal to 6 is given, so we have removed six from the link list. The final link list will be our two 2 3 4 5. Well, obviously, if the link list is empty or that element is not there in the link list. So as it is, we have to return, okay one more example, here all the seven are there, so obviously all have been deleted and we are left with nothing See, in the last video we had asked a question which was remove duplicates from sorted. List 2 Okay, what was done in this, we did almost the same work in this also, here as you can see, there are three duplicates, so we have blown three, four are also duplicates, we have blown that too, okay, you will see in this 1 2 3 Okay, what is one, what are those duplicates, so we have removed them, final list two and three, so the question is the removed link list elements, they are similar to this, okay, I would suggest you to watch this video, let's code. The 82 one is fine because see, I am going to use the same code. Okay, this is a very easy question. There is no rocket science in this. Let's copy this and paste it here. What were we doing here? See the duplicate in the previous question. But there is nothing like duplicate here, we have to give the value only in the question, so here we had written that brother, the value of current should be whatever and equal to next but there is nothing like that here, we will check the current dot value e value. We are fine, current dot next is not required, now there is no need to extract the value here, let's remove it because the value is given in our question. Okay, with this change the question will be ours. Let's run it and see. It has been accepted and submitted. Let's see if it has been submitted, okay, I would suggest you to check the lead code 82, okay, this will give you two questions, this one and this one Lee | Remove Linked List Elements | remove-linked-list-elements | Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50` | null | Linked List,Recursion | Easy | 27,237,2216 |
395 | you there is like something on the chat like give me a sec yeah I also wanted to mention that for the previous problem water and jet problem when I was like looking into it there is also a mathematical formula that can lead us to a very fast solution using GCD okay I will encourage like people to read if they're interested about it okay so let's jump to the last question for the day this question is find the longest substring with at least K repeating characters okay so first example is let us say backed-up example is let us say backed-up example is let us say backed-up different examples like to collect clarify the question first it's always like to ask clarifying questions given K equal to 3 so we need to pay substring in a b hf at least k repeating characters okay so the solution here is a we cannot include B's cause they're there count is less than K okay what about if the string is a b what should be the answer in this case the answer could be seven because for a the frequency is full and it's a larger than K 3 and the B the frequency of B is also 3 yep so the holy spring can be done so cause we have like 4 days which is greater than 3 and we have like 3 B's which is equal to 3 okay what about a ba p in this scenario what's the count of a three and count of B is also three yeah so the answer is six yeah okay cause the question says we just need to count the characters if they repeat at least K times they don't need to be adjacent they can be anywhere in the string okay now what about let's say I inside see in between each will be zero no six way from the ADAC ei okay so here we can be easy in the solution no yeah we cannot include the C so the answer will be zero yeah we cannot include see in the solution and the question clearly say says it should be a substring not a subsequence okay so we cannot have the answer here is zero okay what about let's take like the second problem second example ABA BB C and the K is 2 and they also will be fine yes because we can include always and all these there are two ways and three B's and C is less than K so we don't want to like include C so hopefully question is clear to everyone I will take silences yes any approach how we can solve this problem anyway they still hear me yes sometimes I feel like silence maybe I lost everyone so any approach it can be brute-force approach it can be brute-force approach it can be brute-force approach any approach so what can be the good force approach could be iterated a whole string and for each length counted every characters frequency if every fruit every character frequency is larger or echoed than pain yeah which will be done yes which is correct cause given let's say this example okay k2 we know like we need to have a string with at least sighs - so we can come up with sighs - so we can come up with sighs - so we can come up with all the sub strings within a given string of size two and then see if the conditions are matching so in this case we can have a vsfs string then B a then a b then b matches - so at then a b then b matches - so at then a b then b matches - so at this point we got the answer as - then this point we got the answer as - then this point we got the answer as - then BC then have length three strings ABA yes this does not match us cause like B is of size one Bab we cannot include that a BB we cannot include that bcc we cannot include that a heavy string of size for a Bab can we include that yes okay so we got updated answer which is for ba BB we cannot use this as answer a BBC we cannot use that as answer okay we are done five okay ma'am - okay we are done five okay ma'am - okay we are done five okay ma'am - weighs three B's yep definitely we can include that as answer so our result is five now and then be a BBC we cannot include cause a and B a and C counts are less than K less than two so we cannot include that so that's one possible route for solution come up with all possible sub strings greater than or equal to K and less than the greater than equal to K and then count the character counter frequency thanks for suggesting that what can we do better there are two weak character and separate the pastor the last and cake versus the characters bigger and cake and we iterate through the string you know as soon as we encounter the character the less than K and we are okay yes you can click there like fact again so let's take this example where let me see this and k equal to 2 so what should we do here can you please repeat the algorithm that you mention about the approach week out we will count I'm sorry I'm driving right now it cannot do the screen but you know greater than okay and then we iterate through to the screen from left to right as soon we as we encounter the character at last and K and we are yep so that's a good approach so I would like to repeat that roach so what we are talking about given a screen be count all the frequency of all the characters so what's the frequency of a here for frequency of b4 frequency of c1 so what this map indicates us what's the idea if it will be solution in the course here after Kate yeah so this indicates like C is a bad character here you can have like more characteristics IBM we have like D okay but I'm just taking like in a simple example or let's include D also D equal to 1 okay so we have ad here right here so this indicates both C and D are bad characters okay cuz their frequency is less than 2 and they cannot be in the solution okay so given this string what is we break this string by first bad character that we found it can be any like okay so what if we break it by C we divided the whole string into two parts yeah two parter so this is the left part and this is the right now the divided our problem into two similar subproblems right into recursively do the same thing to the left astray and nicely yes so let's say let me like take a different example I have a B here and let me insert to D here maybe okay so in this case we have break it down first C frequency of C is 1 okay correct frequency of a is 1 2 3 4 5 6 frequency of B is 1 2 3 4 5 6 ok frequency of D is 1 & 2 frequency of D is 1 & 2 frequency of D is 1 & 2 okay frequency of T is 2 okay and given this a string know what's the known bad character here C right so let's divide this string into 2 parts please don't see so we got two subproblems if we take a then we like to look into each sub-problem separately look into each sub-problem separately look into each sub-problem separately and then combine the result like whichever has the greater result now on the Left what's the frequency of a 2 frequency of B 2 okay and this thing length is 2 okay so we got like one possible answer as for right now on the right what's the frequency of e 4 frequency of bees or frequency of these two okay what should we then there's also will be this length of the whole string yeah each character frequency is at least two yep so the answer that we got here is ten and then we look into what solution like what's the answer that we get from the left subtree what ons that we get from the right subtree and take the max of that so in that case it's the ten okay what is on the right subtree let's say we might have I'm just like assuming we might have like e here in the middle okay then we have to again repeat the same problem okay let me write it separately the ease and then we have to take this substring and then remaining substring okay now on the left we will again break it down by T cost east count is less than one okay so we will get ba and on the right also like we will get ba so both of those leads us to answer so this is that Rouge that was suggested and it's divided in concur we can keep dividing finding the back bad character and then divide the screen find two sub-problem similar screen find two sub-problem similar screen find two sub-problem similar subproblems LEP what would be the complex in the string okay entity substring what should be the context today anyone so let's say it will be yeah well and let's listen back to them keep oxygen everything by half so we have to keep running 24 so I can do and I think this is very similar to like a you're constructing a tree in a case where there is a perfect display that say you are splitting the string right in the middle okay so the left subtree and the right subtree they have similar nodes okay which is kind of a tree that we are constructing like binary tree that we are constructing compare it with mud salt same algorithm same kind of operations we are performing so if n is the length of the string what should be the complexity and login okay what is the split is like not even let's say we have this string a multiple times B will be multiple times and then we have C at the end okay so in this case we will just have left subtree right and then again let's assume we come up with something let's say there's like something that just I'm just like taking an example okay there if you split by C first cause C is the first character that you will find when you apply creating a map cause generally like we create a map in this fashion in and dislike some Java code okay it counts you in 26 okay so we will find the first like we count the frequency then when we have a tasting to this count the first character that will come is C okay so the string is a split something like this then we will find B then the string is a split like something like this correct so we will have like kind of a linked list where we only have the left sub-tree there is like no right subtree sub-tree there is like no right subtree sub-tree there is like no right subtree okay what is the complexity of that instead of login it should be n okay so obviously it leads us to any square okay any questions tennis which it has progressed lighting ringo question like then i found no there has multiple solutions but it could end up bringing it at them yes there is one more approach as a see mister saying it's a sliding window approach which can lead us to expect order of n solution okay I don't think like we have time to discuss about it and right now I have fully formed how phase 2 so maybe if you guys want to try it out give it a try implement this divide and conquer approach cuz it's kind of like a recursive approach come up with the bases okay it should be easy to implement and then see how sliding window works obviously thanks brother okay thank you guys have a good day thank you | Longest Substring with At Least K Repeating Characters | longest-substring-with-at-least-k-repeating-characters | Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.
**Example 1:**
**Input:** s = "aaabb ", k = 3
**Output:** 3
**Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times.
**Example 2:**
**Input:** s = "ababbc ", k = 2
**Output:** 5
**Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only lowercase English letters.
* `1 <= k <= 105` | null | Hash Table,String,Divide and Conquer,Sliding Window | Medium | 2140,2209 |
202 | Hello my dear friend so today you are going to solve d lead code problem happy numbers ok so what will be given in this question number so what is d happy number positive wait and what c have you do c have you replace d number by Sam of d square of un digital ok suppose if van and nine is given it means you have tu square van square give you have 82 give nine you are number will become 82 c have tu repeat this process until number bikams equal tu van and loop endlessly In d cycle ten not include van ok and do number happy numbers ok so see this example first of all nine 68 6² 8² = 100 give if you are going to do 68 6² 8² = 100 give if you are going to do 68 6² 8² = 100 give if you are going to do d square you are going to get value one van Similarly if you are going to C D Example of N = 2 So every it is given Example of N = 2 So every it is given Example of N = 2 So every it is given falls so that same it is given falls so if you are going to do you square it will be four square will be 60 nine What you have you do square of one And square of six so you're going to get 37 nine what you have to do You have to do this square of three and 7 so 3² is 9 and 7 square to get 49 so what you're going to get 58 again you need to do d Square So What Is 5² 25 It Square 64 So Aa What You're Going To Get Her Is Un 89 Perfect So Again You're Going To Do 81 Perfect So If You're Going To Add Dame What You're Going To Get Van For 45 Again If You're going to do square so what you're going to get van square will be 16 5² will be 25 so see you are going to add dem so it will be 6 + 6 12 and 2+13 dem so it will be 6 + 6 12 and 2+13 dem so it will be 6 + 6 12 and 2+13 and 14 perfect 42 you are going to get So if you are going again you do 42 square it is 16 + you is 16 + you is 16 + you square this 420 C have again entered in D loop okay they are not getting final answer again valuable for that 1637 So this loop is going you and OK C are going you enter In d infainight loop and c are not going to get d solution so in this case what c need you do c need you return d value one false ok so you go same in you it is false and if c take d example of 19 it is 1 + 9² is again 81 so 82 will be 64 is 1 + 9² is again 81 so 82 will be 64 is 1 + 9² is again 81 so 82 will be 64 + 8² is 64 so it will be 68 If you are going to + 8² is 64 so it will be 68 If you are going to + 8² is 64 so it will be 68 If you are going to do six squares 64 so you are going to get values 100 so 64 so you are going to get values 100 so 64 so you are going to get values 100 so 1 square + 0² + 0 you are going to Get 1 square + 0² + 0 you are going to Get 1 square + 0² + 0 you are going to Get Final Answer Aaj Van So If You Get Final Sam Aaj Van So What You Have You Do You Don't Have You Go Further This Is A Happy Number So You Every You Need You Return What See You Do In This Question Okay So Nine Late As si d approach date si need tu follow ok so first of all si go tu know date elements i repeat after a certain period of time ok so what date as structure si are going tu us har si go tu us set ok so si know In set elements it will not add duplicate elements OK so first of all what will see will require un set so what will I do I will write s = asset OK which is initially black this is the one thing now they need to calculate D square Suppose N is 19 So what you have to do is you have to calculate d square of elements one and nine ok so square will be equals to and ho you have to calculate d square 1/1 of all d calculate d square 1/1 of all d calculate d square 1/1 of all d digits and ho you are going to get D digits one by one so if you're going to find D reminder so you're going to get value one nine so what you're going to get once you get D value give one nine you're going to add in D square so initially square will B equal to zero so you are going to add and percentage of 10 ok so it will be like this and percentage and to power to this step once this is than what you need to do and it is equal to n divide by 10 and this should be In D loop till all D elements are dan suppose you get element tu 34 so first of all c will get for then our n will become 23 let c will become in square what c will get 3 so again and will become tu give C Will Have You And Like This And It Should Work In D Wild Look And Tell N Let It Be Greater Than Zero Because N Suppose N Is Started With This Number So Van City Divided It Will Become 23 Let It Will Become You Let It Will Become Zero So This show this loop should run until n is greater than zero perfect nine once this loop ends ok aa ok let me right downwards ok let me right every ok once this loop ends so what you need to do is you need to check weather d square h Become one or not if square has become one you will return true ok one thing what you have you do you have you check weather D element loop it or not so what I told you have set so what see will do as hear us see Will get sum square result Suppose square result in D case of 19 So what is D square value 1 + 19 So what is D square value 1 + 19 So what is D square value 1 + 9² Will be 81 So square values 82 So what C need 9² Will be 81 So square values 82 So what C need 9² Will be 81 So square values 82 So what C need you do first of all C will check is it equal You want if it is equal tu van return tu give what see will check whether this value already exists in d over set and not ok if d value already exists in d set it min c are going tu enter in d infinite loop today i show new so see have started with four And C Come Back To D For So C Have You Check If S Are In S If D Element Exists Give What You Need To Do C Need To Return False Perfect So First You Will Do What You Will Do This Time You Are Going To Upgrade Your number so first of all here you can see initially n way 19 so see will check here is d result equal tu van it fit is not what see will do see if date number exists in d over set and not if both d Things Are Not Correct So What C Will Do Our Number Will Be Updated S 802 So What C Will Do C Will Upgrade Over Number So N Will Be Equals Too Square OK Date D Value Date C Have Calculated OK Just Second I Think Stop OK Or So what see will do and will be equals tu S2 ok once date element you have then you have upgraded so here and value see need you add this 82 in d set so next time what see will do in this condition see will check if see will Get 82 C Are Not C R Directly Going To Return D False So What C Will Do S Dot Add And Ok So These Are D Steps That C Are Going To Follow Nine I Will Help You Write D Code For D Say Ok So C R On d screen you can see in input c are going to get a value as n so first of all what c will do c will define un set date do not do it initially and square is un variable date is going to start with zero and what c Will Do See Will Run D Wild Form Till Square Is Not Equal Tu Van If Square Is Equal Tu Van See Will End This Will Loop And What See Will Do See Will Start D Square Value With Zero And Her What See Will Do See Will Run A Wild Look Same Look I Told You Dat C Need You Check D C Need You Find D Square Value So C Will Run Will Loop On D N OK So Will N > 0 C Need You Are This Loop So What I Will Do N > 0 C Need You Are This Loop So What I Will Do N > 0 C Need You Are This Loop So What I Will Do Square Will Be Equals You square plus and every i will find d last element so n % time and last element so n % time and last element so n % time and c need you find d power of c need you square date number so initially c have one and nine so nine square ok and percentage What c will do c Will upgrade over number tu square ok so today c told further i told you initially n way 19 but nine will become 82 and once c have upgraded our n what c will do c will add date element in our set so s dot add end in this Set What C Will Do C Will Add Element So This Will Help Us To Protect From D Infyanite Loop And Let Us Try To Summit D Solution Aaj U Can C I Think Or So It's Faster Than D 98% Think Or So It's Faster Than D 98% Think Or So It's Faster Than D 98% Solution Ok Date C Have Written So This way of seeing can solve this problem so it is very clear to you that this sim approach is very simple so further so these things that are given have given this thing so what it is old it has told you find out square so this is d code you find d square ok sum of square it should be equal tu van d return d solution ok and check wether it is entering in d loop and not let c have check d se condition respect vice what c have dan c Have added date c have upgraded our number and then c have added in d set value ok so this is d solution of this problem so if you have any other doubt please let me know in d comment section if you find this video useful you can share this Video with your friends so I will be solving python problems daily and if you are new to this channel you can subscribe to this channel so I will be solving python ok so thank you | Happy Number | happy-number | Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1` | null | Hash Table,Math,Two Pointers | Easy | 141,258,263,2076 |
967 | in this problem we have to return a list of numbers such that they are all of same size that is if we are talking about three digit numbers then the list will contain only three digit numbers and another condition is that it has three digits so we will take the difference between first and second and we are interested in absolute difference not that first minus second it can be second minus first so absolute difference between two consecutive numbers two consecutive digits of the number are same similarly for second and third so the input will be what is the number of digits in each of the numbers and also another thing k so the difference between them should be k so let's look at an example then it will be more clear so let's say our input is n equal to 3 and k equal to 7 that is difference between each consecutive digit should be 7 and all the numbers should be 3 digit and there are some conditions that n can be from 1 to 9. so n is always valid and k can be 0 also you can see 0 to 9 and another thing is that you cannot precede a number with a zero although zero ln alone is valid so if when for one case where n is one then that means we are talking about one digit number in that case zero can exist but other than that zero will only exist after first digit so it can be one zero one it's fine uh but not zero one so what's the way of solving it so clearly we know number of digits beforehand so there is no confusion about this so first digit can be any of these nine values first digit cannot can never be zero it can be zero for a special case where n is one so let's say that special case is not there we are talking about some general case and let's say we have n equal to 3 then first digit can be 1 and let's say we took 1 we will similarly have 2 also as the first digit 3 also and so on we will try with all the values so once we have 1 as the first digit then there are second digit we can have 2 values either 1 minus k or 1 plus k since the difference needs to be k so let's say this level denotes the digit number this is the first digit or the most significant digit from the left and the next level we will talk about second digit so at some general level let's say the digit value is d so what are the two possibilities only two possibilities are there not more than that either the next one will be d minus k or d plus k or both may be valid so this will be valid here we are subtracting k is positive number from 0 to 9 so if this d is less than k then this becomes negative so this will be invalid and if in this case we need to check that d plus k should not exceed 9 so it can go up to 9 then only we are in the single digit range so one of them will be valid always and if none of them are valid we will not include any of them maybe both of them are non-valid maybe are non-valid maybe are non-valid maybe this d is 5 but k is let's say 8 so we can neither subtract nor add so both can be invalid as well so depending on your validity we will pick one of them or none of them so we will in that case we will return from that so this branch has become invalid so it will propagate to the upper layer that this is invalid so look for other possibilities so let's start with this we pick one as the first node then next k is 7 so clearly 1 minus 7 this will be invalid it will become minus 6 that is negative so second digit can only be k d plus k this branch is invalid in our case so it's uh one plus seven that is eight next eight plus seven is fifteen so this branch will be invalid so next can be only eight minus so here we added seven here we subtracted seven and we got one and now number of digits is three so we don't look further we stop this is one solution which is one eight one so that's all we got from this one as the first digit next we pick 2 as the second digit so again 2 minus 7 this branch will not be there but 2 plus 7 will be there so it will be 9 then again 9 plus 7 will not be there but 9 minus 7 will be there so it will be again 2 and now 3 digits are there we will only go up to the number of digits or the number of levels so next is 2 9 2 from 3 again minus 7 is not possible plus 7 will be again 10 so both are invalid so we will try with 4 again 4 plus 7 is 11 4 minus 7 is negative so this is also invalid so we will try with five minus seven again not possible six minus seven not possible seven minus seven so next we will pick seven then seven plus seven exceeds 9 so we just take 7 minus 7 that is 0 and then from here we cannot subtract so only add so next is 707 and then 8 plus seven not an option so one eight next nine to nine so in this case we had a very slim tree just one branches but it can be uh multiple options also if k is small you can expect much more branched trees so let's make this k equal to two and let's take the same example so n is three digit numbers and k is two so one next can be one plus two that is three then uh again one from two it can be 2 minus 2 that is 0 2 plus 2 that is 4. now you see branch is coming out here then from here it will be just 2 but from here it can be 2 as well as 6. so these are all valid 1 3 1 2 0 2 uh 2 4 2 two four six similarly for three we will have one and five for four we will have two six again 0 4 8 so you now see much many more numbers and if n is even larger let's say n was 5 so you can expect further branches from there again if depending on k we will have many branches so in the worst case we can have if this is n and n is limited to 9 only it cannot be more than 9 so maybe k is very small maybe k is 1 or even 0 is a possibility so we can have multiple branches at first level 0 second level or 2 next level 4 next 8 so 2 raised to the power n for one tree but we can pick different trees also so this is for one tree and this is secondary third tree so number of trees can also be from one to nine so it can go up to n multiplied by 2 raised to the power n so this is the time complexity of this approach and space also each leaf node corresponds to a valid output and we can have this many output also so both time and space both are o of n raised to the power n multiplied by 2 is 2 raised to the power n so how we are solving it you can relate to it to some approach called depth first search so we are starting from this node and go as far as we can go until we reach a dead end and then we return we either reach a dead end where no solution exists or we reach to a solution when the number of remaining digits becomes zero so here we needed three digits to start with we added one digit and passed two to the next level that we need two more digits it again if there is a valid solution valid digit it will add it and pass to the next level next option and it will pass 1 and from here it will call pass n equal to 0 and that will be the termination condition so similarly you can see that we start from 4 we go to 2 we go to 0 and then we return then we backtrack from 2 there is another option 4 which is valid and then we go back to 4 since there are more options from 4 from four as the first digit so clearly this looks very similar to a depth first approach and we will follow that here so let's write the code for this will be just like depth first search so it's like a visiting these are different connected components all the nodes here are connected similarly here so remember that while if you have solved some of the graph problems and we have to uh do a depth first search on a given graph then we run a loop like that for i equal to 0 to v minus 1 if visited i equal to false then we trigger a dfs from this node so this dfs will visit all the nodes which are reachable from this i so we need this multiple times since there can be multiple connected components and this is what it is so i have pretty much covered whatever conditions are given here so if uh we will add the edge cases later so what we need vector of hint to store the results so this is the main function from where we will just decide the first digit and first digit can be only from one to nine first digit cannot be zero there is a special case where first digit can be zero that is n equal to one we will cover that or let's add it here if n equal to 1 then so we add 0 to it otherwise we will never add 0 so when n is 1 and k is let's say 0 then we will have 1 0 to 9 everything so that's why we are adding the 0 separately d equal to 1 d less than n first digit can be up to nine and plus d and we need to define a dfs here we will pass the digit first digit then one digit we have added so we need n minus one more digits and then k will remain constant and then also the result by reference so when do we stop when there are no more digits to add that is n is 0 so this means we have reached here so here we pass 1 here we pass 13 and here we add 1 to it so every time we add multiply the past number by 10 so when we passed 1 here what it did it multiplied by 10 and added this 3 so it became 13 and it passed 13 below and what it did it again multiplied by 10 and added 1 to it so it became 131 and now it passed below this num and also n equal to 0 so it will see that n is 0 there is no more digits required so whatever number is given to me just add it to the result and then we return back but if that is not the case then we need the last digit because the next digit depends on the previous digit plus minus k if last digit is greater than or equal to k then only we will subtract it otherwise it will become negative and we will not subtract it so if it's more than k then we continue further otherwise if we reach a violation we return that this branch is invalid so if this branch is valid we continue the search we continue the dfs num multiplied by 10 plus last digit and n becomes one less and also minus k since large digit plus minus k so this is for this large digit minus k now there is a case where now you will say that just write this another case for plus k and this here we should check that last digit plus uh k large digit plus k so minus k we have already taken we need plus k so this should be less than 10. so we will argue that just do this both cases we have covered but there is one case where this will fail other cases it will pass let's first go with this then we will modify that expected 4 past 3 num is there n is there k is not there okay so this matches the solution but what we are doing wrong let's see this let's say we have 2 and k is 0 so in that case now you see that where is the problem so once we do last digit minus k that is minus 0 and then we do last digit plus k that is last digit itself plus minus 0 does not make any difference so both these calls will be made if both these conditions are satisfied so we will have repeated values so let's see so you see 11 then 22 33 44 55 these all are occurring once but here you see all are occurring twice because of that this is being done twice so this we will do only if k is more than zero otherwise there is no it does not make sense to make it twice since this will always be true last digit will always be greater than equal to zero so once we have added this now you see it's being done just once so let's submit and the solution is accepted and we are here but if you run a few times it will be zero millisecond i am pretty sure so now let's write this same thing in java and python or we will pass a list we don't know the size so this is a list of integer but need we need to return into array so we need to convert this list of integer to uh array of ins so we could have directly called two array but here it's integer and not int and here it's int and the java solution is also accepted finally we will do it in python 3. so if you want to keep a different end so that it you are not confused with this outer end you can change it so and the python solution is also accepted | Numbers With Same Consecutive Differences | minimum-falling-path-sum | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n = 3, k = 7
**Output:** \[181,292,707,818,929\]
**Explanation:** Note that 070 is not a valid number, because it has leading zeroes.
**Example 2:**
**Input:** n = 2, k = 1
**Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\]
**Constraints:**
* `2 <= n <= 9`
* `0 <= k <= 9` | null | Array,Dynamic Programming,Matrix | Medium | 1224 |
109 | That a Hello Issue Se Samay Channel Debit Solid Liquid * Benefits Share and Solid Liquid * Benefits Share and Solid Liquid * Benefits Share and subscribe the Channel and Unlimited Slides Unlimited is the captain that today he is in more subscribe to subscribe Video Please subscribe and subscribe the Video then subscribe to but will do specified mid point turn Of the input RS 300 plus 4 battu is metal index and subscribe must subscribe the last point of subscribe button on closed side is to cause to be created during idiot and in two-three hours to same process for it in two-three hours to same process for it in two-three hours to same process for it subscribe left side will be used in incomplete desire subscribe karo ki end five common hai sudhir wa subscribe kar lu subscribe namanat mein tha middle element of this short list on if is do the best 201 9 pass law and approach and you want to decide the middle end tours 116 smooth do coding for android Explain how will reduce problem tooth on 13010 Mitron paas lootpat hai to post album solving its problems in the to aap subscribe channel subscribe skin ko subscribe video ko mouni subscribe to please return that changed route of the free mode on this subscribe Intezaar Hai Ko Vijay And Images And Anischay Inke Started Step Into Being Reborn In Us Apne Mitra Please Return Nall From Web And Ajit Bhai Please Find The Needle In Next Midnight Certificate Started Please Like This Hey Bhai Tu To I Want You Know Renewal Rules Do That absolutely news free mode on that I will extra the calling from dr a phone number shot the middle and once a that the next six use this question principle scientific evidence in more mid 8 - from this time will reduce The 8 - from this time will reduce The 8 - from this time will reduce The Amazing subscribe to that iPod a Right to work with you my courage to say hello to my midcap index plus one form of candidates an unheard of return on investment a place performance to Akshay dead game start depression and now let's move will introduce contest subscribe to a swag copy paste same golden remedy Just Right Diet Kya Hai Surgical Unit You Will Write That And Let's Get Started Recent Issues Norms For 1000 National Rural Electrification Tunnel Hai Otherwise Let's Go For The Recognition That They Will Define Adherents Of Two Ministers Starting Point And Subscribe And Share And Subscribe To That Electrolyte The Information Properly A Tree Helper That And WhatsApp To Start List Notes To Start From A List Node That And That Point To Notes Passport Crops Interests So Please Note A Lesson Equal To Had A Similar Lift Not Luttu Hai That David Se Half Fuel Also Video then subscribe to the Page if you liked The Video plz Written On and Ajay Bhai Flats and Shop Light Point at the Fundamental Element Ki Aunty Lakshan Rider Code Patra Not Equal to End Password Next9 2222 Email Increment Point to Times Password Next A Daughter Gates and Plut are according to Dual Point to Middle Element of according to Dual Point to Middle Element of according to Dual Point to Middle Element of Interest 200 Let's Refine You Nord Stream's Node Adventure That New Note's Value is a New Dream World and Will Live with Anil Sign on Left Side Play That Auntie New Node Daughter Is Equal To A Helper Slot Next That Crow Thank You Last Playlist On A New Not Come Tomorrow Morning Viewers Student Point Approach 225 Meter Element Tree Subscribe To Smart District Coming To Received Equal To Not Great Think Well Before The Are Comparing To Points 98 A Plus Point And Entertainment Are Akshar Friend Thanks For Watching Video Open Which Updated On Hua Hai | Convert Sorted List to Binary Search Tree | convert-sorted-list-to-binary-search-tree | Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** head = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST.
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in `head` is in the range `[0, 2 * 104]`.
* `-105 <= Node.val <= 105` | null | Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree | Medium | 108,2306 |
57 | insert interval it's a median legal question so basically you're giving array of non-overlapping intervals array of non-overlapping intervals array of non-overlapping intervals where interval i equals start to end represents the start and the end of the i interval and the interval is sorted as in ascending order by start i so you also given an interval a new interval that represents start and to another interval and you basically what you need to do is insert a new interval into the existing interval by merge them together and make sure that they don't have you have to merge the overlapping intervals if necessary so return intervals after the insertion and you can see the existing interval is one three six nine so the interval is two five and then you wanna return the result because one and three um is overlapped with the two so you wanna merge them together so it will be one two five and then um six to nine that's the uh output and the second example you want to look at it is one two three two five six two seven eight to ten and then the interval is four to eight so it overlapped until this eight and then four is in somewhere in between here so you essentially merged these two interval and it became 3 and 10 right that's why the answer is 3 and 10 here and if you look at it here's some constraint here the intervals is sorted which is really awesome so you don't have to worry about it and in the past six months google asked this question 11 times and let's take a look at the example here and one example is one i have interval one two three right and six two nine and that's the existing one my goal is to basically let me add some more dots in between them so you can kind of imagine and this is the number in between and what i need to do is i'm i want to insert two um and to five right five is before six and when i merge these two you can see that um i the answer is one two five right one two five if that's the answer we get basically the overlap them and merge them together i expanded on the left side i have selected the minimum on the left side one compared to one is smaller and the three compared to five but on the right side i select the maximal because on the right side is actually bigger the five is bigger so you want to um so you already can kind of see that's what we are looking for if they are overlapping left side we want to select the minimum of these two number and the right side arrange we want to select maximum of this these two numbers three and a five but there's also other scenarios like um if the uh if the number um for example like uh let's say if i want to give it to uh let's say this is four and then three right and then if what i need to answer is one two that then the answer will be uh one two and a three two four and then six two nine right and that's the other scenario that we have considered the other scenario is that um i can put uh one two here and then uh what we need to insert is three two four if that is the case we simply just answer one two three four six nine and you just basically append it together right and then that's the a few different scenarios that we need to handle and in the end you can just return the result um uh in the end and i'm gonna show you how to write this in code so i'm just gonna assign a result like this because it shows as the array in the end and every single time so basically for i in range length of the intervals um that they have defined for so i'm gonna go through every single interval right um the first scenario is that if the new interval um we just want to make sure that i spell it right new intervals or first number that's how you specify it in python the new intervals first number if it's smaller then let's handle the um the first scenario it's on the left side say this is a 0 to 0. if the newton new interval's second number is smaller than the intervals first number that's what we mentioned earlier in the example that if it's completely on the left side there's no overlapping so all i need to do is just append the result the new interval i just append the result to the uh the new interval to the result right and then all i need to do is basically just return um the result plus interval uh starting from the i if it's this is the i've i interval we're looking at right so you basically just return the result because you appended the new interval to the result already and you just basically print the result first which is the new interval and a plus the interval starting from the i that we're you're looking at and that's the answer right um if new intervals uh if new intervals first number is bigger than intervals i've first number um do you see if uh the intervals zero number that's basically it's that's basically this if new intervals first number is bigger than interval i say we're looking at this example and i've for a second number basically the index 1 instead of zero here what are we gonna do we're just gonna resolve append we're just gonna append the interval we're just gonna append the intervals this to the and the result right because um it's the new because new intervals first number is bigger than this and we're just gonna append the this to the result and then else is the other scenario that i mentioned that say this is three if this is the case if i'm overlapping what i'm gonna do so new interval newton new interval will be equal to minimal left side i would do minimum of the intervals i um first number basically index 0 with the new intervals beginning number i will the first number basically i will take the minimum and then for the right side i will take the maximum of the new intervals first number with the intervals i numbers second number so basically three and a four whoever that is bigger i'm gonna take this and then that's it for the for loop right and then i'm gonna say rest append i'm just gonna append a new interval to the end result and then in the end i'm just going to return the result if you think this is helpful please like my video and subscribe to my channel and i'll see you soon with more legal questions bye | Insert Interval | insert-interval | You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105` | null | Array | Medium | 56,715 |
107 | welcome back everyone we're gonna be solving Lee Code 107 a binary tree level order traversal 2. so we're given the root of a binary tree we need to return the bottom up level order traversal of its nodes values so they give us the tree 3 9 20 15 and 7. we need to return the levels 15 and 7. first then 9 and 20 and then the root node so what we can do this is obviously going to be a breadth first search but what we'll do is we'll run our initial breath first search right we'll get the output as 3 9 and 20 and 15 and 7. and then all we have to do is just move these levels right we'll move the bottom to the top uh the top to the bottom and the middle will stay the same in example one's case so we'll Implement our DQ from collections so from collections import DQ we'll set that up to be Q equal to DQ which will initially contain the root and we will have a resulting output uh let's yeah we'll have a resulting output and let's say we'll have output one equal to an empty array so when we run breadth first search the first time we'll get all of these levels on our array so let's put these in here so we can see what we're going to do foreign okay so this is what our of like the original breadth first search will give us right it'll give us 3 9 and 20 and 15 7. so all we have to do is just run a while loop and we'll say while this output contains levels we're just going to pop off the last level right which would be 15 and 7 and we can take that off and then just put it onto our resulting uh output array and we'll do the same until this output 1 has no more levels in it and as we can see it gives us the correct output so now let's run our breadth first search which is going to be while the length of our Q is not equal to zero what are we going to do we're going to define a level equal to an empty array and we will say 4i in range length of our Q what do we want to grab the node which is going to be equal to Q dot pop left now we want to check and make sure we are not at a null node so we'll say if node is not none what do we want to append the nodes value onto the current level so we'll say level dot append the node.val dot append the node.val dot append the node.val now we need to check for the left and right children so say if node .left is not none we will append that .left is not none we will append that .left is not none we will append that left child onto our queue and we'll do the same for our right child so if node.right is not none Q dot so if node.right is not none Q dot so if node.right is not none Q dot append node dot right and then after we exit this for Loop here we are done with the current level so we can take this level and append it to our output one so we'll say if the length of our level is not equal to zero meaning we have nodes at this level we will just say out one dot append the level now let's print out our out one array so we can see what we have now we should have the exact same thing um as what I showed you earlier so we do have 3 9 and 20 and 15 and 7. so now we can just run a while loop so we'll say while the length of out one is not equal to zero we are going to take the very last level we're going to pop that off and append it to our uh resulting array so we will say res dot append the out one dot pop value and if you wanted to make this more clear you could say um what should we call that we can call it Lev and it will be out one dot pop and then instead of appending the pop value there we can just say love and okay so let's print out our resulting array after this gives it some space and there we have it we have our what is this a level order traversal two right so backwards essentially we've got 15 and 7 9 and 20 and then three so all we have to do is just return that output array and we do pass all three test cases so let's submit perfect it runs so time and space complexity time complexity is going to be o of n right we are touching all of our nodes at least once in our tree but then we are also doing a while loop right this is going to be an O of n as well but o of n plus o of n is going to simplify down to an O of n run time and the space complexity is going to be bound to the length of our Q Plus the length of our output one array plus the length of our resulting array so we'll say o of Q dot length plus out one dot length plus our resulting array.length plus our resulting array.length plus our resulting array.length all right that'll do it for Lee Code 107 | Binary Tree Level Order Traversal II | binary-tree-level-order-traversal-ii | Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[15,7\],\[9,20\],\[3\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000` | null | Tree,Breadth-First Search,Binary Tree | Medium | 102,637 |
519 | all right uh doing this problem called random flip Matrix let's have a read given a m cross n binary grid Matrix uh with all the values set to 0 initially okay design an algorithm to randomly pick an index IG where Matrix I J equals to zero and flip it to 1 okay so we have to pick one index which is non-zero and to pick one index which is non-zero and to pick one index which is non-zero and flip it to one sorry which is 0 and flip it to one all indexes i z by matrix size equal to zero should be equally likely to be returned so you have to only pick an index which is zero so the ones which have been converted to once they are not have to be picked okay optimize algorithm to minimize the number of calls made to the built-in random calls made to the built-in random calls made to the built-in random function of a language and optimize time and space Computing so basically optimize everything implement the solution class solution this initializes the object with the size of the binary Matrix a flip returns a random index ISO The Matrix where Matrix size equal to 0 and let's say to one and resets it research the values of the Matrix to be all zero okay so first things okay let's come to a whiteboard now first thing is so given a 2d Matrix right given uh 2D Matrix and if I have to get a random number I can basically if this Matrix has am cross and elements then basically I can generate a random number between anywhere between 0 to M cross and minus 1 right and then whatever number I get I can convert it into an IJ format right so and that's come Samsung effect any 2D Matrix essentially you could represent as a 1D Matrix right so for example essentially you could have 0 1 2 3 and then four five six seven eight nine ten eleven right so zero would map to this zero one essentially this so for us uh so meaning this what if it really what it really means is that uh given X your rho equals to let's say if it is M cross n where n is the number of columns then rho equals to uh X by n right and that column will be X percentile n right you can put for anything so if you look for five in this is a matrix which is what three Cross Four so the number of columns are four so every row has four columns that's why you divide by according to the row number right so in this case five by four is one so your row number is one and then within that row if you do percentile n so five percentile um four is one against that is why here on the first column so the short point is essentially you should be able to get uh you generate a random number and then from that random number you can get to an ing instead of say generating a random row and then a random column because you need a single random number and return and convert that into the in its mapping into the 2D Matrix that's one bit now second bit is how so let's do the representation in a single 1D format itself right so let's say uh I have a matrix to begin with which is all zeros right so I'm really more interested in the index rather so uh so I have a matrix and I'm just simply its indexes let's say I have this Matrix and they are essentially all zeros but I'm just mentioning the indexes here and I generate a random number and let's say I land on three right so that whatever three Maps two is a 2d Matrix I'll convert that to one and I'll return that uh and now next time I have to not include this three which is where the problem is so I know so earlier I had eight numbers and then I could generate from one zero to seven now I have seven numbers left I get a number between 0 to 6. but how do I exclude this guy in the middle or other multiple guys in the middle that have been uh converted to once so one way could be okay I got this I convert it to one now what I want to do is I uh remove this right somehow so I'm if I can maintain my mappings um so let's say so initially it's okay so initially what I'm thinking like is initially let's say I maintain a mapping of index so it's let's say 0 1 2 3 4 5 6 7 they all mapped into the same thing right and now when you get this 3 as a random index now you want to remove these three so just remove this three and what essentially mean that means is shift all of these here so make it something like 0 1 2 3 4 5 6 now I have one less and this three is removed so they all will actually map to 0 1 2 and 4 5 6 7. right so these are your actual indexes and this is the virtual indexing so if you are adding another level of indirection essentially and now when you put a random number out of this let's say random number that you get is 4 here right so that means this 5 will be converted to 1 and you wanna shift these things here so this will then change to again so 0 1 2 3 4 5 and you will shift so zero one two four five has been removed six and seven and that is how you will keep doing things now when we talk about the time complexity essentially so you're taking a virtual index a virtual array to address the actual indexes and then whenever you get you shift right but shifting is linear now we are shifting because we are trying to maintain your about maintaining the order is really not that important right what I mean by that is when here we got three we wanted to just delete this three and to release shifted everything else but instead of Shifting everything else what if we just replaced this three with this seven the last guy yes the order changed but order doesn't matter right and that can be written in O of one instead of actual shifting so again here when you get this index score and you're removing this five instead of like shifting it to making it six seven you could just you could have just uh swapped it so this 6 would have remained six and this would just have become seven and this would become six so just to explain again but then I think the concept is clear so initially I go with the same things 0 1 2 3 4 5 6 7 I get a random index let's say three so what I do is just okay three has to go away so I change one element is reduced and this three will become seven all right and then let's say again I do random again I got three so that means okay now the 7 is gone I have to reduce my size and I'll replace it with six right and this everything is happening in open now let's say I do random number to this point I let's say get one okay so that would mean is okay this corresponding index to 1 that will get uh replaced to one and size has to reduce whatever is the last guy I put it here five and that is how I can do it in o f 1. all right let's come to code and so now one bit before coming to core so essentially what we're doing initially is we are mapping indexes to indexes right there is a mapping from index to index and initially that mapping is all one to one like zero maps to zero one map so one two maps so two three maps to three if we have to actually do that initializing then it will take us and cross M times so we could actually avoid that initially we could say hey if the mapping does not exist then by definition it means it maps to itself right and then only if the definition uh has to be updated then we'll update it so let's come to the code now so what we're saying is what we are doing is we are mapping index key index so we'll generate like a hash map from uh integer to integer right let's call it map and we'll initialize it in here so map equals to new Cashmere and we are also maintaining the size upon the number of zeros right so we also maintain a number of zeros so uh and we'll just call it zeros right and the zeros are initially they are M cross n and now when you say flip what I'm doing is this I am getting a first of all a random number so in uh random and R equals to I think to get a random I need some random class right uh so that also maybe we Define outside so random uh random run and we can do just a new random or rather you know what I don't even I feel like I don't need I think there is a math uh so in let me search okay math dot random products is there a what is the value between zero and one okay so maybe not this one I need like uh maybe this is a better I think there is something called like a next in so you define a random class and you define an extent with this bound this is what we'll do 0 is inclusive and the specified value is exclusive so then let's use this so we have and uh and we'll use new uh random and then equals to run or just get some integer and that integer has to be bit till the number of zeros that we have right and it will give minus one so zero to this minus 1 yeah so we get this number now in our virtual array this is the guy that we want to replace so what does it actually map to so and actual this actual it maps to uh this map dot get or it could not have been mapped so uh Cate or default uh it will be present or it will be it or will take it as a search this is what it actually maps to right so we'll have to return now whatever you have to return equals to um now I and J we can do easily so let's save what uh let's say the number of columns as well right so when you're returning we have to return uh new thing uh actually White Band will be the row and actual percentile and will be the column and we can return this but there is something else to do now we have to reduce the number of zeros right and before that we might wanna bring in whatever is at the last index which is so we'll do and we'll put it here swap we don't really we just need to copy the last guy over to this position so because anyways we're reducing the size so putting this Square to the last doesn't really make any think so what I do is map dot put whatever the position was in the virtual array I want to put here the last guy so last guy would be what uh in the zeros minus 1 and it could also be just us on so whatever is the last guy I bring that guy here and then I reduce my total number of zeros and return this now come to reset so when I have to reset that means I have to make everybody zero um that would mean that uh I just initialize my map array so is there a something called map.clear is there a something called map.clear is there a something called map.clear let's do in Java so hash map Java Docs foreign m equals to m so 0 is equals to M cross n what else well since the map is fine zeros is set random can remain the same and then this can remain the same okay run and get a compilation error it's random okay submit and it works | Random Flip Matrix | widest-pair-of-indices-with-equal-range-sum | There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`. | Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b. | Array,Hash Table,Prefix Sum | Medium | null |
948 | hey guys welcome back to this video now we're going to solve liquid problem bag of tokens you have an initial power p an initial score of zero and a bag of tokens where tokens i is the value of the ith token your goal is to maximize your total score by potentially playing is token in one of two ways if your current power is at least token i you may play the ith token face up losing token's eye power and gaining one score if your current score is at least one you may play the ith token face down gaining tokens i power and losing one score is token may be played at most once and in any order you do not have to play all the tokens and you have to return the largest possible score we can achieve after playing any number of tokens here we have some examples if we have this tokens 100 and p equals to 50 then we have to return zero and here we have explanation you can read that and we have some more examples okay now let's go to slide okay this is our problem backup tokens and we have this problem statement and we have these two conditions if we see the power is greater than the current token then we will down the power and will gain a score and if we see the score is greater than zero then what we can do we can add the token to power and we can down the score okay for example we have p equals 250 and this array of tokens this array only contains one token 100 and we can't play this token with power 50 because we see the token 100 so we have to written zero and initially we have score equals to zero what we have in the problem statement then for this example we have p equals to 150 and these to token 100 and 200 and we have s equals to zero so we can play with this token 100 since we have 150 power if we play with this token then we gain one score and we lose this token from the power so power become 50 then for this token we see we can't play with 50 and we can add this token to power by losing the score and we don't need that right so for this input we have to written one for this input we have equals to 200 and here we can play with this token 100. if we play with this token 100 we gain score 1 and we lose here 100 token in the power so power became 100 now what we're going to do we're going to lose the score and add the token to the power whenever we found the maximum token in the array and the maximum token in this area is 400 so we'll add this token to power then 400 plus 100 equals to 500 okay so power become 500 and score become zero we have to down the score because we're adding the token now we have two token or 200 and 300 if we play with this token 200 then it will lose then we lose 200 from the power and we gain one score so score one and we have now token equals to 300 and now we have power equals to 300 now we have particles to 300 and for this token we have 300 so we can play with this 2k if we play with this token then we gain score 1 so score become 2 and power become in this case 0 and we're done so for this input we have to return 2 now let's see how we can solve this problem let's suppose that we are given this array and power equals to 200 and this is the code to solve this problem first what we're going to do we're going to sort the array this arrow is already sorted then we're gonna check if the length of the array is zero or if the array contains only one element then we're gonna check if that element is greater than p if that element greater than p then we'll return zero because for that we can't play with the token if we have the power less than the token when we have only one token in the array then we're going to declare a variable in square equals to zero so initially we have scored equals to zero then we have left and right left point to this first element and right point to this last element now we're going to run this while loop while left is less than equals to right and now we're gonna check if we see power is greater than or equals to the tokens at left we see that 200 is greater than 100 so we'll increase the score by one so in this case score become one okay now we're going to subtract the token from the power so now power become 100 now we're going to move the left pointer to the next element so right here then for next iteration we see 100 is less than 200 so this condition is false now else now here we're checking if we see the left element is not equals to the right element by doing this formula right minus left greater than zero since the array is sorted if we see right minus left is greater than zero that means the right element is greater than left now what we're going to do we're going to down the score that means we're going to decrease the score so we're going to change the score to zero then we're going to add the current power where right pointer is pointing here 400 so if we add this 400 to 100 so it's become 500 okay then we're going to shift the right pointer to the left so right pointer now pointing to this element 300 now for the next three iterations we see the power p is greater than this element 200 so we're going to increase score by one so now score become one then we're going to subtract this token 200 from the power so power become 300 then we're going to move the left pointer to the next element so next so left pointer is now pointing to this element 300 and we're done with this iteration for the next iteration we see 300 is equals to the token on the left so in this case we'll increase the score that means we gain one score so score became a two then p equals to p minus token left so let's subtract this token from the power so in this case power become zero then we're going to move the left pointer to the next element and the left pointer is now pointing to this element 400 and we're done and to the next iteration of this while loop we see that the left pointer is not less than or equals to right because now left pointer is pointing to the next element of right pointer okay so we're done with this while loop at the end we have square equals to 2 so we'll return to this function called bag of token score okay so we return here 2 and this is how we can solve this problem the solution will takes big o of n log n time complexity to sort the given tokens array and it takes linear time complexity for the sorting okay and this is my solution to this problem if you like this video if you want more video like this please subscribe to the channel thanks for watching this video i'll see you in the next video till then take care | Bag of Tokens | sort-an-array | You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed).
Your goal is to maximize your total **score** by potentially playing each token in one of two ways:
* If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**.
* If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**.
Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens.
Return _the largest possible **score** you can achieve after playing any number of tokens_.
**Example 1:**
**Input:** tokens = \[100\], power = 50
**Output:** 0
**Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score.
**Example 2:**
**Input:** tokens = \[100,200\], power = 150
**Output:** 1
**Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1st token since you cannot play it face up to add to your score.
**Example 3:**
**Input:** tokens = \[100,200,300,400\], power = 200
**Output:** 2
**Explanation:** Play the tokens in this order to get a score of 2:
1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.
2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.
3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.
4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.
**Constraints:**
* `0 <= tokens.length <= 1000`
* `0 <= tokens[i], power < 104` | null | Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort | Medium | null |
342 | Jai Hind this problem this picture where number 13 is a power for and note Sudhir different from power to check all they can modify the to check the power of formal wear look at a few more solution starting with its truly great Vriksh solution and one solution and In service company call to learn is a flat CEO Vikram That point is also one number late from 1658 power for its representatives in this one 0 210 is 12481 enjoy that Shimla defeats 646 powder next power to do is 200 so is number two power After what is the Power of Tourism Power to Business Power to the Real Power to the Self to Ours 2010 The Video then subscribe to the Soviet Multiply Bittu Again Multiply Bittu Din Wicket Another Power of Karo Ko Soft Bhi Under Witch Can Earn Their Rights But even numbers give 1051 345 the widow right only bittu so welcomes one 's day also left back to cigarette 104 even 's day also left back to cigarette 104 even 's day also left back to cigarette 104 even less performance this is not difficult means late evening numbers which were also set up side and distance between last Tubelight 600 800 wiki donor its rear number 210 is the best goddess keep track of how many types of subscribe thank you will regret backing notification number 90 time complexity of 1532 its original also have in bits so avya a writing by to is time so they can have log In a locked course to and when is the number of but not the number 21 roll number can relate to 13 number four number is ccr dividing brother for writing brother tu menu sunday wedding life for writing by one means dividing it into switch off foreign that That blot tour and space one tubelight servi wave this time that all already no.in and in - 1304 power that all already no.in and in - 1304 power that all already no.in and in - 1304 power of two that is in power up to that any se power to than in brighter 200 it's that in power up to play list this power To effective from this is vikram all but one and euro for example and 108 you can take 1561 i safe country 181 that singrauli fifteen years dec switch you subtraction from this and you will welcome 0 pimple raw to check the only four wickets at swades chak Guarantee Act But This One Month Properties And Power Subscribe 151 6000 Model Urs Hai Yogurt One Mantri You Get One Mandal Answer E Love You Get 210 Cigarette 1081 And 2nd Power For Youth Brigade And Sudhir And Solution Time Complexity And Final Odi Against 10 Solution Of Time And Gives No Independent - 08 2018 Know The Power Of Wave Behave - 08 2018 Know The Power Of Wave Behave - 08 2018 Know The Power Of Wave Behave The Next Powerful v10 Enemy Like Four Next Vighna 64 220 Disbeliever 8.66 Sixty-four Will Be Sixty-four Will Be Sixty-four Will Be 90 That In This Will Continue To I Will Always Keep One Place Sudhir 123 456 sure jo chha twitter horoscope set in different parts of and only one visit and vinegar opposition 024 600 water fair-minded 110 subscribe button video hai to karthikeya sa first david next video oo loot 1000 232 recent and with this division more share tabeer 13574 Channel Subscribe Visit 0 subscribe this Video Subscribe - 10 subscribe this Video Subscribe - 10 subscribe this Video Subscribe - 10 Hai And Shy System A History Class Eight Sentence Written AP Suji College Main Ek Time Spotted Sudhir Vikalp 000 Work Sudhir And This Is Us Time Complexity Of Wave Space Complexities Of Wave United Subscribe My Channel And and departure time's superhit dialogue rhythmic solution login veer wa ki is kyun na misslad one the return gifts ki uski par number nam in as per let's pick hai net ki problem vid oo liye subscribe tab dividing if you have hai to suno 200 Simply Return New Delhi Get Any Great Work Number And Note Idon't Work Number We Submit Last Date This Mode Turn On Twist As Per Electronic Store Is Accepted In This Case Which Will Not Object To Make A Difference In Timing Dual Office Late Every Small Time Sudesh Login Solution Now Will Comment It A That Electrolyte The One Solutions Will Right Bahut And Dum 200 G Vikram Right In One Line Return Phone Number 10 And Phone Number 90 Se B0 And Phone Number 2 3 K Dushman Bhi Khol To The One You In Directions Accepted Subject To One Provision And With Zero Millisecond Now Will Write The Other Solution Minute By Minute Oven That Slats Commented On I'm Involved David O Phone Number And 90 From This Which Times 5678 Difficult 0 210 Giving Falls And One More Author's Discovery Channel Also Accepted And It's Just A Matter Of Time But For Mid-Day Just A Matter Of Time But For Mid-Day Just A Matter Of Time But For Mid-Day Experiment Via Best All The Best Auditions | Power of Four | power-of-four | Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_.
An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`.
**Example 1:**
**Input:** n = 16
**Output:** true
**Example 2:**
**Input:** n = 5
**Output:** false
**Example 3:**
**Input:** n = 1
**Output:** true
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion? | null | Math,Bit Manipulation,Recursion | Easy | 231,326 |
292 | hey everybody welcome back and today I'll be doing another lead code 292 name game you are this is an easy one you are playing the following name game with your friend initially there is a heap of stones on the table you and your friend will alternate taking turns and you will go first uh on the each then the person who's done it is will remove one to three stones from the Heap and the one who removes the last stone is the winner so if there is one stone I have there is uh I will be going fast so I will be removing the first stone and I will win if there are two Stone I can remove two stones because the limit is from one to two one to three if there is three stones I will be removing three stones and I will win now if there is four stones in on the table and it is my turn to go first so whatever I do I'm going to lose because even if I remove the Three Stones there will be one stone left and my friend will win the other person will win so then my loose condition will be four now let's see five if there is a five I will just remove the five and give the 4 to the opponent and my opponent is stuck because whatever he does like this I will remove five okay whatever he does he removes one two three my friend will or the opponent will just remove these three and because he can remove three at a time or two or one either way if he doesn't remove three like this you can see uh if he says okay I will remove four I will remove these three and I will win okay and that's it yeah now let's see it for six I will remove these two and upon it will have is again stuck now what will he be doing he can either remove four again or two or just three but whatever he does he cannot take the fourth false Stone from the table he can only take three and there will be one left and in that case I will be winning again now let's see for seven I will be removing Three Stones five six seven and he is again stuck with four so he is again whichever of us is going to stuck with four is going to lose so that's it and now let's see for it so you can see now it is uh very difficult for us to when we are basically lost because whatever we do if we remove one the opponent will remove uh let's remove it and the opponent will remove these three and again we are stuck with four so whenever there is a number that is divisible by 5 we are just going to lose and in else case we are going to win so that was it and if the number of stones in the price are which are present are equal to zero if they are divisible by 4 we will just return false because we are going to lose and in the else case we will be winning so that's it let's submit it and that's it | Nim Game | nim-game | You are playing the following Nim Game with your friend:
* Initially, there is a heap of stones on the table.
* You and your friend will alternate taking turns, and **you go first**.
* On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
* The one who removes the last stone is the winner.
Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** n = 4
**Output:** false
**Explanation:** These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
In all outcomes, your friend wins.
**Example 2:**
**Input:** n = 1
**Output:** true
**Example 3:**
**Input:** n = 2
**Output:** true
**Constraints:**
* `1 <= n <= 231 - 1` | If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner? | Math,Brainteaser,Game Theory | Easy | 294 |
278 | first day of mail it coding challenge and we are solving lead code problem number 278 it's called first bad version and this problem is very similar to typical binary search with very little variation here so you are given a list of versions of a product and you are told that the current version is faulty this you are given and here you see gg and then bbb so here bb denotes the bad versions and gg denotes the good versions of a product so once a bad version occurs then all the versions after that are bad no g can occur after once a b occurs so your task is to find out from which version this started the problem and you will be given one api get bad version and you will pass one index of this array and this api will return you whether it's true or false whether it's good or bad so you have to do it minimum number of calls to that function and we will be using binary search approach and we will do it in log n times so let's see uh so here we have a version starting from 1 2 3 4 5 6. you are not even in fact given an array you are just given a number that is what is the current version number and it's bad nth version number is bad not good it's given two things you are given so you will see current is bad so either it started from this current thing or it started from in this part of version from 1 to n so we query the middle one so this is the array we query the middle one and we ask is this bad or not this middle is m and the first one is start last one is end is bad that's given so we query if middle is bad if it returns true that is one or it can return zero that is not mad if the middle is mad that means it's bad and it may have started anywhere before it because if once it's bad everything else will be mad so where do we search we will not search in one minus mid but we will search from till mid because maybe this is the first index which is made so our search will become if original binary search is from 1 to n or start to end then if mid is bad then we will search from start to mid if it's not bad it's good then everything to the left is good so search for bed would be only in this part one after mid but in this case it was including mid because this may be the first one this may be the index we are looking for so here we are strictly more than mid so start index will change we will no longer search in this part so it will be m plus 1 till end will remain same so you see there is no overlap here s2m m plus 1 to e next uh again we will look in whichever part we search again we will look the middle and repeat the same thing and uh when we have s less than e uh we will continue our search and we will stop when s becomes equal to e and you see when we narrow down our search we are hundred percent sure of results we know current version is bad so there is no chance of missing it in general binary search what you do you keep searching and when these indices become equal or cross each other you return minus 1 if you don't find it that is i did not find the number i was searching for that is the typical band research here that case will never happen it's guaranteed that there is a bad that's why we are searching the current one is bad and here whenever we are dividing the problem we are hundred percent sure if mid is bad we are hundred percent sure the first bad occurs in this part including mid if it's good the middle one then we are hundred percent sure that the first bad will occur in this part and for sure this last one is bad uh so when e is less than s is less than e we know that we have to continue our search we have not found yet the exact number and when it becomes equal then again with 100 security we have not narrowed down our search to just one index and we are sure that bad one will lie at this index only so you don't even need to call it you can call it you will get one only if you call this api but if they become equal you straight away return that number so let's implement it first in c plus this then we will modify our solution for java and python so this is the problem you can see that unfortunately the latest version of your product fails the quality check so even if you have just this list is just one length that is just one element in this list then that element will be bad only that cannot be good so there are two approaches for this you can see a recursion happening also here if we call is bad on with two different indices and we can do it iteratively also we can run a loop while s is less than e and keep updating the indices i will show you both the approaches because it's a good starting problem for learning the basics of recursion so first let's look at the recursive solution so this original function does not accept two indices so we will define one helper function let's call it first bad version and we will pass it start and end if s equal to e then we return s else we calculate mid s plus e minus s by 2 and why do we do you should know by now why do we calculate mid like this if we do s plus e divided by 2 mathematically we will get the same result because if you take the common lcm this 2 multiplies to s 2s plus e minus s which is s plus e divided by 2 but we do it like this ways because if s is larger than let's say into max by 2 and then e is also larger than that start so the sum of these two will be larger than into max and you will see some negative value there so that's why we do it this way that way we make sure that we don't exceed the limit of integer is bad version this is the api that they are providing is bad version and that's it we also need to call it here from 1 to n and let's try and it works for this case so let's submit and the solution is accepted now first we will see the iterative approach then in other languages we will modify the iterative approach because that is supposed to be faster than so many recursive calls so let's get rid of everything we will not need a helper function we will need two indices start equal to 1 and end equal to n and we will loop till s is less than e min equal to s plus e minus s by 2. if is bad version mid then equal to mid we are setting shifting the end else s equal to mid plus 1 exactly same logic and once s is not less than e that is s is equal to e then we return s and let's try this solution as well and it's also working let's submit and the solution is accepted so let's try the same thing in other languages in java and python and i don't think we need any change here let's try in java and it works so let's submit and the solution is accepted now we will do the same thing in python 3. and let's try it and it gives correct answer but we see some difference here let's see if it accepts it or not if not we will convert it to int okay so it expects it int so this may be non-int float this may not be exactly non-int float this may not be exactly non-int float this may not be exactly divisible by 2. now this should accept and our solution in python is also accepted so this problem may seem very simple but uh this mind research concept is used again and this may not be a main problem but it may be used as a small utility function in some bigger problems so you should be thorough with how to quickly write a binary search code | First Bad Version | first-bad-version | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1` | null | Binary Search,Interactive | Easy | 34,35,374 |
1,455 | Jhal 208 hai ki Nirmal Singh khele match [ __ ] next hai ki Nirmal Singh khele match [ __ ] next hai ki Nirmal Singh khele match [ __ ] next portion and local bodies like it is canceled that so many security questions now half yes ok half soya Sudesh questions write me too come in filter article will be provided in the restaurants near vs hai wind ids meeting After becoming family price and distance and your fear of using three factors for politics being in the written down and defeated and it's true that you need to take all wars restaurant that happens when friendly and effective for all the best 21st Unfriended Electronics and Recruited In Addition To Get Or Fritters Micromax Price And Distance Of Baroda Maximum Value For Price And Distance DR Destiny * Price And Distance DR Destiny * Price And Distance DR Destiny * Find A Particular Area And Distance Of Maths For A Fight Between Their Written On That Me Restaurant CID Specter Print And Electronic Producers Setting Show What Is The Highest Rating Date Particular Rashes Having Me To Prevent Dubai The First Woman In The World To Have The Same Rate In The 2nd And 12th Date Of Death Toll From The Tourists In Forest Conservation Breeding Gautam Id From High Waist Hips And Fair For Paura Se Dedh Se In The Indian Hero Top Difficult 09 2010 Example Dil Se Sorry Ajay Ko Main Akhilesh Producer Hai And What Is Slide Show Editing Video Condition Improves Vision Neetu Printer Etawah To Z Friend Restaurant Honors List Vichar Video That Air Show And Nurses And Third Index Oye Dissident Karenge That Aam Aadmi Pisi Saunf Bachchan Family Hai Ki And Specification Friends Hai And Sunao It's Printout On The Basis Of Peace And No One Has Made Strike Shiftiness Distances Lab Test 1648 Vs Max Price And Existence Of Want To See The Best All The Best Subscribe 554 But It Doesn't Mean That To The Duck Is Like You Want To Three An Interactive Media In The 500 Index 267 A Slightly Blurry Dish On The Basis Of All The Greeting Cards For Mother Is Waiting Clear Answer Is According To Three Layers Other Rating Is This Food Sudesh Bhai Sentence On Restaurant Total Soya Sauce Unveiled Answer Is Media One And Five Big Boss This Vital Force Applied To 10 Elements In Total Motu Patlu Ki Jodi Anu Wright The Chief Justice Jasbir And Achievements Shopping By Rating Sort By Rating Hai Jhaal Dat Le Tablet Ajay Ko A Sort By Rating And It's Not That Dreams Of Meetings Of Budoni Routine Is Meeting At Maximum And This Hair Oil Then Economists Have Interest In The Midwest Record On The Basis Of Leaders Singh Gautam And Id From High West To Best Fennel Is the highest to and officer and others this lineage will spread till then on this treaty with same but another example is morning that hair hadith a restaurant swiss bank cutting five jhal and national day in the dustbin friends this road show will remove to That idea sindh girlfriend information2media related to zinc dros pinpoint bodh solitaire when they can take you can improve the quality of being known in the big guide channel subscribe now to first meeting and subscribe under secretary dr ki naav ki vacancy mihir to common man 235 india Yashwant Cost Android 4.1 Address ID Spoiled 10 Android 4.1 Address ID Spoiled 10 Android 4.1 Address ID Spoiled 10 Songs Of This Distic With Short Note On The Basis Of ID Election 3072 Chut Udhar Chalenge Second Step States And Crops Seeds Are Given In Russian Model And So Akshay So Let's Check The Same Thing You Can Edit in all it's first hai ya sudhir is one in the 70s hua hai aur sanao aur dr to hearts and ratings wife dhundhili to short toe observe id snow waves page subscribe ke liye pic vishva ki aims arch enemy jasmeet receptors hai jhala soo instituted Of 20 Unmute Nav Bihar Police Result which is language problem only problem points painting and sorting in every bit to line thank you to the basis of the day Yogesh problem regarding tomorrow morning time then you devotee poetry on pen but study. Every hour of the country's icon feeds a pamphlet ka lagna na song kal cricket club kuch aa ki ye log dete he 21 people talking about this the first a statement lockheed pisach electronic shop hai that citric acid mode of anit se but shouldering also again Got Andare Show Ki Biwi Not Like To Eliminating Evil Elements In The Remaining All The Greeting From Different Countries To Elect To Sort By Rating Ok Sweet Will Be Easy And Login Is But Sohni How To Do And Shopping Mall Show And Definitive Oil 100 Black Singh Vikram Mishra And You Will Be Used In Place For Short Term Effect Maz Tak Interview Questions Or Person Grade Kya Expect That We Anand Shandilya Questions And Want To Do And Sudhir Visam Mother And Approach A 107 Companies Have This Problem Difficult Questions That Your Slow Early morning anything discuss like quality k 150 akram and vitamin incomplete 600 what others think who applied in abroad and wakefield institute and pointed out with flying through and shopping hydrated youth into a that i think different easy questions research notes medium these questions on Hussain Drag is done | Check If a Word Occurs As a Prefix of Any Word in a Sentence | filter-restaurants-by-vegan-friendly-price-and-distance | Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`.
Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one word, return the index of the first word **(minimum index)**. If there is no such word return `-1`.
A **prefix** of a string `s` is any leading contiguous substring of `s`.
**Example 1:**
**Input:** sentence = "i love eating burger ", searchWord = "burg "
**Output:** 4
**Explanation:** "burg " is prefix of "burger " which is the 4th word in the sentence.
**Example 2:**
**Input:** sentence = "this problem is an easy problem ", searchWord = "pro "
**Output:** 2
**Explanation:** "pro " is prefix of "problem " which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
**Example 3:**
**Input:** sentence = "i am tired ", searchWord = "you "
**Output:** -1
**Explanation:** "you " is not a prefix of any word in the sentence.
**Constraints:**
* `1 <= sentence.length <= 100`
* `1 <= searchWord.length <= 10`
* `sentence` consists of lowercase English letters and spaces.
* `searchWord` consists of lowercase English letters. | Do the filtering and sort as said. Note that the id may not be the index in the array. | Array,Sorting | Medium | null |
412 | hey guys welcome back to another video and today we're going to be solving the lead code question fizz buzz all right so this question is pretty simple and what we need to do is we write a program that outputs the string representation of numbers from 1 through n so every time there's a multiple of 3 we output fizz every time there's a multiple of only 5 we output buzz but if a number is a multiple of both three and five we output this bus okay so all it is we're given some rules and we just write that into code so the most naive thing we could do is we can type out each and every if condition and do that but we have a better solution which is a slight modification so let's start off by creating a results list and this is what we're going to end up outputting okay so we created that and now we're gonna go inside the for loop so for x in range we're gonna be starting off at the number one and we're going to go all the way up to n since we're going all the way up to n we're gonna do n plus one because uh what this does is it's going to go up to n plus 1 not including n plus 1. so that means it's going to include n in this case okay so now that we have this we're going to have a temporary variable over here and it's going to be an empty string okay so what we're going to do over here we're first going to check if x mod 3 is equal to 0 so if that is the case we're going to add the word buzz sorry fizz to our temporary word so temporary plus equals to fizz sorry and f is capital okay so there so every time it's divisible by three we're going to add the word fizz okay so after this we're gonna check if it's divisible by five so if x mod 5 is equal to 0 then in that case we're going to do temp plus equals to buzz so we're going to add the word buzz and how does this actually make sense so if something is only divisible by three then we're going to add only fifths if it's only divisible by five we're only going to add buzz but if it's divisible by three and five we're first going to add fizz and then we're going to add buzz so that satisfies two of our conditions and now we have every other condition of ours so in this case x mod 3 is not equal to 0 and x mod 5 is also not equal to 0 wait sorry x mod 5 is not equal to zero okay so when it's not divisible by 3 and not divisible by 5 and in that case to our temporary variable we're going to be adding the number we are at and more specifically we're going to add the string of it we're not going to add the number so string x you can either write it like that or you could use f string so you could do f and then you could put curly brackets and x either of them means the same thing okay and now that we have this outside of after we're done with all these loops statements then after that we're going to add that to our results so res dot append and we're going to append the temporary variable and that should be it so at the ending outside of our for loop we're going to end up returning right there we go okay so now we return res so we'll submit this okay and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if this video helped you thank you bye | Fizz Buzz | fizz-buzz | Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_:
* `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`.
* `answer[i] == "Fizz "` if `i` is divisible by `3`.
* `answer[i] == "Buzz "` if `i` is divisible by `5`.
* `answer[i] == i` (as a string) if none of the above conditions are true.
**Example 1:**
**Input:** n = 3
**Output:** \["1","2","Fizz"\]
**Example 2:**
**Input:** n = 5
**Output:** \["1","2","Fizz","4","Buzz"\]
**Example 3:**
**Input:** n = 15
**Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\]
**Constraints:**
* `1 <= n <= 104` | null | Math,String,Simulation | Easy | 1316 |
1,630 | hi everyone welcome back to a new video today's lead code daily challenges arithmetic sub array this is a medium level question although it has been mentioned as medium but after understanding it will be quite easy for us to solve so basically in this question we have been given an array and we have to find that if the given array has a sequence of number which is arithmetic how can we find that a number or a sequence is in arithmetic order the way to find it is the difference between the two consecutive numbers will be same like if we have 1 2 3 so this can be said as an arithmetic sub sequence arithmetic sequence because the difference between one and 2 is one and 2 and three is also one so now we have the basic idea of how to find the uh sequences arithmetic or not so now we have been given two arrays uh namely left and right in the subse uh in the question so in the nums array we have to iterate from left to right and check if that subsequence or that sub array is in arithmetic progression or not or arithmetic sequence or not so if we have nums here as 4 6 and 5 right from 0 to two we have to iterate so 0 1 2 now if we sort it out it will become 4 5 and 6 now we can see that it is an arithmetic sequence right now we have to move forward in the left and right area so we will have 0 to three now in the same where we have we will take 4 6 5 and 9 now after sorting it out we will see that we have four 5 6 and 9 all of them have all of these have the difference one but between 6 and 9 the difference will be three so this is not an arithmetic sequence moving forward we have 2 and five are the as the different indices so we will move from here to here so we have 5 9 3 7 if we sort it out then we have 3 5 7 9 if we see that we have a common difference as two in all between all of them right this is also two and this is also two so this is a arithmetic sequence so let's move on to the approach for this question I will be sharing a very simple solution for this and it will be quite beginner friendly so let's move on to the approach of the question first step what we have to do here is as we can see what we were doing we had a left and right indices right so we have to just iterate between those so we will get the array sub array between the given left and right indices so we will get the sub array between given L and R L of i and r of I after that what we have to do we will sort it out so we will sort the sub array now we have already got the sub array after this what we will do we will simply check for differences so we will check that if difference we will take out the difference for if we have like four 5 6 right so we can get this difference and after that we can compare for all the others so we will get the difference first get the get difference between first two numbers and then we will compare and then we compare what we compare if the difference if difference is not equals to A R of I minus a r of I minus 1 whenever this condition will fail we will directly return false and if out of uh this will be going on in a for Loop right so if NE if this condition never becomes true that means all of them have the same difference therefore at the end of the function we will be returning true so this part will be taking part it will be taking place in a single function so we will create a fun function for this to check if array or sub array is arithmetic or not let's move on to the code so whatever little doubts will be there it will be clear with that let's see the code now so in this code what I'm doing here is I have declared an arror to store the result in the form of true and false now I am iterating on the length of this array right we have L and R both of them will have the same length so I will take the length and now what I'm doing is I am creating a function called is arithmetic to check that if the function is arithmetic or not now after that what I'm doing is I am passing length uh I am passing the aray from here and the AR I am passing here is a kind of sub array which will have only the digits from L to r index okay and I'm also passing L and R from here now what I'm doing here is I will be sorting this array and find I am find actually this is not needed here I can just share the sub array and then I finding the difference here after finding the difference now I have a thing I have a value to compare with so I will keep on comparing with every that if the difference is not equals to I not equals to array of IUS one so if this condition turns out to be true then we will be returning false otherwise we have to return true out of the loop now once this uh function returns a value it will be stored in Val and we will append the value in result after that we will be returning result now let's run the code and see the sample test cases have been accepted let's submit the question so this code has been accepted that's it for today guys thank you for watching if you found this video helpful please like the video and also subscribe to the channel hit the Bell icon to get further notification for the daily lead code challenges | Arithmetic Subarrays | count-odd-numbers-in-an-interval-range | A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.
For example, these are **arithmetic** sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not **arithmetic**:
1, 1, 2, 5, 7
You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.
Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._
**Example 1:**
**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.
**Example 2:**
**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]
**Constraints:**
* `n == nums.length`
* `m == l.length`
* `m == r.length`
* `2 <= n <= 500`
* `1 <= m <= 500`
* `0 <= l[i] < r[i] < n`
* `-105 <= nums[i] <= 105` | If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low. | Math | Easy | null |
1,656 | uh well i think it's recording uh let's jump into the um problem sections um i've tried some of the area problems before and i have some to-do's and i have some to-do's and i have some to-do's and let me see how many problems i've shown you guys i used to solve easy questions first so uh okay acceptance rate is 81.9 what is uh okay acceptance rate is 81.9 what is uh okay acceptance rate is 81.9 what is this designing order system um uh we have given there is in streams of and an id key validators of arriving in an arbitrating order so this value strings have the after a single series the combination of all those charms suit in a list of certain levels implement the auto stream class okay we have the class there yeah that's perfect and then they have to construct you so it takes parameters and empty and means i think in our balance that you're in which we're instantiating our is and the longest so in this case we are first inserting the elements in cccc so it doesn't read anything so in this we return this look at this one and if you insert this relevant a and b and o number is bb and cc after this cc and something and we'll do the same string because we don't have anything up there okay now in the clear explanation view this is the i mean this kind of query strings okay this is the order stream which is instantiating this object and this is passing it as a file and that's we have some five different insert operations queries so at the very least uh we'll just answer this cccc it doesn't return anything yeah that's true if you insert try to insert it the first part this and resulting in smaller before so as you know we have the certain limitations or constants and value is less than a thousand okay that's perfect and id can be any number that's great and less than and id is not going to exit from 1 000 and value that what is fine i mean this length of this value is not going to exceed more than five letters okay it's going to be wanna load the sliders it's called insert will have an unique id exactly and calls will be made okay so i'm gonna move this to this okay so um i never saw this kind of class an object problem before but well we studied in java class right let's just try to implement it okay so what do we need at first this one will get okay switches okay because this is this hasn't written type of list so we're going to create it first so list of now the list it is so it's gonna be alright that's true and um area strings and i'll store these fingers because one thing i need is a string inside i don't know though i have not supposed to i mean the uh output query along with the ids right so i only need okay i'm really going to calculate all those strings i need to originally all these strings s and in index so this index uh will i mean due to minor at which position i'm going to insert these values so let's see so in this one we're getting n that's i'll set the index to be shorter in the first positions in recipient maybe i don't know let's see so is know okay let's try it out and then while i'm checking for why so we will keep him uh we'll keep count this index that race of id key arrest off um index right and then we'll just implement the index this is over there great new stream then i think it's that's really good we're gonna have to try it out let me run first okay so we have a new string which is find the order stream string of rings oh boy i'm such a stupid well that's new string strikes today i don't know um let's see another error id key keys are defined with this case like this there is pretty easy again hopefully okay i'm doing some silly mistakes i don't know why okay that's great at least i'm getting output no this one this so what i'll do is induction zero that's perfect index plus we're incrementing the index and okay i think the problem is the risk of um ivy key or something wow something's i think it's over maybe if it is not melbourne oh my goodness this works oh boy um submit one well it works but the runtime is 68 milliseconds can you just values strings we want to take care of strings we don't need those indexes you know that's good let's go for another problems so what is this we go for problems is there anything to lose there's a lot of questions get subtracted second highest cell acceptance is quite this much i'm going to make this one is higher um something can you do this let's try that let's start with an easy one that's good oh boy oh you guys a lot of dislikes what is the same problem with binary shares yesterday yeah i think it is like it is even an upgrade is divisible by three or four or something or just like this and i also have to pause there okay this is another great coding platform i've found great so what is this facebook yeah i've done this today what is we have given a list of integers one two and accept these things and instead of integer and multiples of five in this pulse free integer is so we're not doing anything here just using initializes ourselves new race so that's already this one and rest of all because press of zero is going to be one because the first chain is one hour is one degrees it's neither is divisible by three or five inches and we'll just uh look through this colors and elements which is fit to be here so it's called the rest of length please we're not going for any um we're creating the uh rest area of string surfboard and this is pretty much something that's going to recognize and if it is i plus one is more 15 because it's going to be indexed always so it's going to be and this race is going to be over so race of i is going to be freeze pass it means if it is divisible by 15 it means if it is either i mean if it is a if okay integers which has multiple of 3 5 if it is multiple of 3 and 5 then it must be multiple of 15 right so with this race of fire this at the index i positions one okay this one and if it is if this will get executed so we'll just try to i mean these strings will get located and store the rest of it so if you first here if n is going to be 15 and we're just creating this string of christmas 15 and if it is one two and three okay then you get this one get executed and if then the value of three ah then this particle is equal to the point we'll just get fizz now you can see one two and three it's gonna be zero one two that's why we're using this plus one two plus one is going to be three right so one and two will be these threes use your by three let's see and all these things and streams s is consisting the value of i plus one which is used to help us the integers values into this string so we're going to just try to uh have a plus one value to the string so we can wait to do this in java i think extreme or some kind of natural restrictions and rays of i is equal to this so this is if all those cases are failed to um satisfy those conditions then it is not divisible three five and even three and five so with this pushing the strings um we're just pushing these indexes right we're just pushing this index one inside the there is five okay so this part will just get if it is i plus one it's if i is one right the rest of i okay because initialize starts with one and initially we have this one and we have i is two right then the rise 2 we're going to i plus 1 that is um what it is it's 1 and 1 plus 1 is going to be 2 and let's see one plus one when we have two if i is one and i plus one is gonna get two and this two if you pass like two at least two so it's meant for an error so i need to convert these two into the we are creating this area of strings and the reason output must be in the form of the stream so if you try running i think it's valid this problem has to do so everything doesn't matter once or as a good um that's it now so i'm gonna name this i'm gonna sleep and that's all for today | Design an Ordered Stream | count-good-triplets | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values.
Implement the `OrderedStream` class:
* `OrderedStream(int n)` Constructs the stream to take `n` values.
* `String[] insert(int idKey, String value)` Inserts the pair `(idKey, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order.
**Example:**
**Input**
\[ "OrderedStream ", "insert ", "insert ", "insert ", "insert ", "insert "\]
\[\[5\], \[3, "ccccc "\], \[1, "aaaaa "\], \[2, "bbbbb "\], \[5, "eeeee "\], \[4, "ddddd "\]\]
**Output**
\[null, \[\], \[ "aaaaa "\], \[ "bbbbb ", "ccccc "\], \[\], \[ "ddddd ", "eeeee "\]\]
**Explanation**
// Note that the values ordered by ID is \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc "); // Inserts (3, "ccccc "), returns \[\].
os.insert(1, "aaaaa "); // Inserts (1, "aaaaa "), returns \[ "aaaaa "\].
os.insert(2, "bbbbb "); // Inserts (2, "bbbbb "), returns \[ "bbbbb ", "ccccc "\].
os.insert(5, "eeeee "); // Inserts (5, "eeeee "), returns \[\].
os.insert(4, "ddddd "); // Inserts (4, "ddddd "), returns \[ "ddddd ", "eeeee "\].
// Concatentating all the chunks returned:
// \[\] + \[ "aaaaa "\] + \[ "bbbbb ", "ccccc "\] + \[\] + \[ "ddddd ", "eeeee "\] = \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\]
// The resulting order is the same as the order above.
**Constraints:**
* `1 <= n <= 1000`
* `1 <= id <= n`
* `value.length == 5`
* `value` consists only of lowercase letters.
* Each call to `insert` will have a unique `id.`
* Exactly `n` calls will be made to `insert`. | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. | Array,Enumeration | Easy | 2122 |
387 | hello and welcome to another video in this video we're going to be doing first unique character in a string and in the problem you're given a string s and you want to find the first non-re repeating want to find the first non-re repeating want to find the first non-re repeating character in it and returns index if it does not exist it return negative one so for elite code we would want to return zero because the L does not repeat for a love leak code we want to return two because the V is the first one that doesn't repeat and then for the third one it's a Ab so every character repeats and this is 10 the 5th so we want a linear time solution so it's a pretty easy one to essentially the boot force would be if we have a string like let's say we have this like leak code string um we would check like okay we're at character L now let's go through the rest of the string and see if we find the L again if we don't then we can just return that index and we do that for every single character and maybe we can Mark characters as we've already looked at them or something right so like for example here we can say like okay well let's look at the L then let's look at the rest of it and then if we've seen the character again um you cannot look through this and I think that would actually pass and basically that would be something like o of 26n so that would pass because for every character you would just look through the rest of the array to see if you find it again so you'd basically do that 26 times which would be o and that would pass now a more efficient way like let's say these characters weren't only lowercase English characters let's say there's like a billion or not a billion but like a lot more the way to do this more efficiently is actually go through the array once get a count of every character which we can store in a hashmap and then we go through the array again and then for every character we just look up its count and if its count as one then we return that index so the first letter we find with a count of one is going to be the letter we're going to have so that's our going to be our solution we're going to go through our string we're going to get a count of every letter pretty easy to do and then we're going to go through it one more time and then for every letter we're going to check is it's count one if it's count one it's not repeating and then we can just return it and if we didn't find anything well we go through the whole thing then we'll just return zero and there's kind of two ways of getting counts um so one is pretty common one with a dictionary right where you just like for every letter you would just update it dictionary another way you could do with an array so you can make an array of 26 of length 26 and then for every character you can actually just get its asky value so because we only have lowercase characters we can get like for example we get the asky value for a let's call it I don't know it is but let's say it's 87 then what you can do is you can take its asky value and subtract the asky value for a from it so you can do 87 minus the asky value for a which would be 87 and that would give us zero so zero would be a here and then let's say Obviously for B the asky value would be whatever it was um for a + 1 right whatever it was um for a + 1 right whatever it was um for a + 1 right because the asky values are like if a is 87 it's not or I don't think it is but regardless whatever that value is B is going to be one bigger C is going to be one bigger and so on cuz if you look at an asky table um all the lowercase characters are one bigger than the one before so the what you can do is you can just get the asky value for the character so we can write this generically so asky for character minus asky for a and that would give you the index in this array where you can increment the count so like if we had C for example C minus a would give us two and so on then we'd go to two and we would increment the count and that's how you can use an array instead of a AR to get the counts which is going to be more performant in some languages in Python it's still pretty easy and it's about the same python dictionary are pretty performant but if you have some Rose language with like where dictionaries are kind of annoying um you can use an array instead and just use asky values so that's kind of like the two ways of doing it so I'll show you in Python how to use a counter and then we could quickly do it with an array as well so in Python it's really easy um to get a hashmap of all of the I think I've done this in a lot of videos uh to get the a dictionary of every character and its count it's very easy you can just say counter and this is imported if you want to know where it's imported it's going to be like this so it's import counter from collections uh it's already Auto Le Port uh Auto um imported Le code so you don't really need to know like you don't really need it but if you actually use it in your own program that it's not Auto imported or if you use like hack rank or some other thing then you are going to import it so anyway so that's where it is um you make a counter and we can actually print counts just to show you and return like zero or something for now so if we run this um yeah so I think oh right it's going to be like the other way so it's going to be um yes it's going to be this way from collections import counter I don't know if this will work on Le code but this is how you use it normally so yeah so basically what it does is um it should give you the uh oh we didn't actually so sorry so when you initialize the counter you want to give it the actual like string or the string that you want to get the count of or you can pass in an array as well so there we go so you can see like now we have every character and it's count so it's super easy so you can just use that so now that we have it we just basically have to Loop through every character so we can just say like for I and range length s um we can just check is it's count one so if counts SI equals 1 then that's the character we want so we can return I otherwise if we don't find anything let's just return negative 1 as the default and that's what they suggested to do now I have to endend this correctly and uh run it so this does work and it's pretty good and so really quickly the other way to do it is we can comment this out so you can make an array as well so you could say counts equals array of Link 26 we'll just make everything zero same thing Loop through every character so for Char n s we don't need the index now we're going to get the asky value minus the asky value of a so we could say counts of or Char minus or a that'll give us a location in the array plus equals 1 so same exact thing as that and now we can take this code again and reuse it so we can say okay let's now let's Loop through it one more time right so we populated our count now let's go through it so this is going to be count and we actually need the same thing so or Char minus or a right because we're using asky values so this is going to be SI so get the asky value for this character subtract the asky value of a to actually get its index if it's one return it otherwise return this and this also works and this will be more performant in some languages depending on the language like I said python dictionaries are pretty good so it's about the same um yeah so these are both ways of doing it and this is going to be end time and space is going to be 01 because you only have 26 characters so even though this word is super big your hashmap or your array are both only 26 so that's why doing this like counseling is very efficient as opposed to like sorting or any other kind of thing um and yeah so I think that is about everything I wanted to cover like I said this counter is very useful so definitely start using it if you program in Python if not um you can use a array or some other thing so yeah that's going to be all for this one if you did like this video please like it and please subscribe to the channel and I'll see you in the next one thanks for watching | First Unique Character in a String | first-unique-character-in-a-string | Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters. | null | Hash Table,String,Queue,Counting | Easy | 451 |
496 | welcome to day 19th of october lead code challenge and today's question is next greater element one the question is an easy question on lead code but it has a very important underlying message or concept which is monotonic stack i'll be talking about it as we go through the presentation let's try and understand the question first in this question we are given two rs of type integer nums one and nums two for all those elements that exist in nums one also exists in numbers too we need to tell the next higher element for these set of elements that exist in num2 for example let's go case by case basis for 4 there is no next higher element so minus 1 is assigned to it the next element is 1 for 1 the next higher element is 3 so 3 gets assigned to it for 2 let's try and identify the position of 2 in nums 2. it is here and there is no next higher element with respect to 2 therefore we will assign minus 1 to it we need to search for next higher element on its right in nums to array we need to up return the results that we computed after searching for next higher element on right for the complete data set that is given to us in nums one now let's look at the presentation that i have created for this and let's start with the ppt next higher element 1 lead code 496 and let's take the same example that was specified in the question let's reiterate it for better understanding this is the number one input array that is given to us this is nums two input array that is given to us for each element that exists in nums one added we need to search for the corresponding higher element in nums to array for 4 there is no higher element to its right we assign minus 1 to it for 1 there's next higher element which is 3 we assign 3 to it next element is 2 there's no higher element on its right with respect to 2 we assign minus 1 to it so the basic or the naive approach that comes to everybody's mind is for each element you search on its right the immediate next higher element and as soon as you find that you bought the process and update your result array the time complexity for this approach would be order of n square because for each element that exists in your input array nums one you are searching for an element by iterating through all the elements that in the input array nums to find out the higher element on its right this complexity is quite high and we want to reduce this complexity through something better we'll use monotonic stacks to solve this questions and using monotonic starch the time complexity would be reduced to order of n we want to know how let's look at the second approach let me just expand the test case to a slightly bigger one so that you get a better hold of the concept let's start the iteration and let's assume the first element that we have is seven so i'll create a new stack and i'll add seven to it let's move ahead next ic is eight so as soon as you see eight what you're gonna do since 8 is higher than the peak most element of the stack you will update and remove 7 from the stack and add 8 to it also you will add an entry in your map that for seven element we have the next higher element as eight this can be done addition this is done additionally let's continue the process next we see is five for 5 we see that the top most element is 8 in this stack which is higher than 5 what we can't remove we won't remove it we'll simply add 5 to it let's move ahead because uh 5 is lower than 8 next element that we see is 2 so 2 is also lower than the peak most element of the stack we'll go and add it into the stack let's continue the process next we see is 1 is lower than 2 the top most element of the stack will add it to this stack let's move ahead next we see is 6 so 6 is higher than 1 what we're going to do we'll delete one from the stack and add one into our map telling that for one the next higher element is six now what is the current state of the stack has 2 at its peak most element 2 is lower than 6 that means we still can remove 2 from the stack so 2 gets removed and for 2 the next higher element also turns out to be equal to six so we'll add a new entry in our map telling that for two the next higher element is six what is the current state of the stack the topmost element of the stack is five now since we remove 2 5 is also lower than 6 so we'll again remove this and we'll add a new entry 5 comma 6 into our map for 5 the next higher element is also 6. now what is the state of the stack only has one element eight is greater than six so you can't pull it out because the value is higher than six what we're going to do we'll dump six onto the stack so stack gets updated with six now so this is the state of the stack the bottom element is eight the top most element is six let's continue the process next we four c is ten so 10 is higher than 6 the top most element of the stack a new entry gets added into the map that says 4 6 the next higher element is 10 also we will remove this from the stack next element that we foresee is eight in this stack eight is lower than ten what we can do we can remove this element on the stack and add a new enter in the map telling that for eight the next higher element is 10 and let's continue the process we'll add 10 to the stack so 10 gets added next before c is 4 so 4 is lower than 10 the top most element of the stack we will add 4 to the stack now the stack is left with only two elements 4 and 10. what we should do we should pull these out till the time the stack is not empty and add new entries in the map for four the next higher element is minus one it doesn't exist and for 10 also a similar kind of thing we added a new entry in the map telling for 10 the next higher element is -1 for 10 the next higher element is -1 for 10 the next higher element is -1 so in this way while iterating through the input array only once we are able to identify the next higher element for each element of the input array and now whatever nums one input r is given to us there will be a subset of elements from this input array we can iterate over this map extract the values that have been set at these keys and we can create the answer set and dump the result i hope this is clear to you just for the sake of completeness let's take a hypothetical case where we are given 8 6 and 4 in our num1 array and what we are going to do we will search for each element in our map corresponding to eight does exist in the map and the next higher its value in the map is ten so the answer will have ten at the first index next is six do we have six in the map yes it has we have and the value is 10 so again we will have 10 and next we have 4 for at 4 we have minus 1 so the answer would be this 10 comma minus 1 this is what we need to return for the input data set 8 6 and 4 you can create as many permutations as you want and calculate the final result accordingly now let's look on to the coding section the first thing that i've done is to define a map of integer comma integer and also have created a new stack of type integer that will store the element the current element into consideration in the stack let's iterate through the nums to input array till the time my stack is not empty and my current element happens to be higher than the topmost element of the stack i extract the topmost element and put it in the map against the current element because the current element is higher than the top most element of the stack i'll continue this till the time this condition is met with each iteration in the while loop the topmost element of the stack will be popped out otherwise i go and update the stack with the current element into consideration stack dot push el let's now build the answer the final answer i created a new array of size nums one dot length for each element in the nums one array extract the value that is present in the map and if it is not there i assign minus one evaluate to it and once i have built my answer area simply return the result let's try and submit it up where do i see status accepted five microseconds milliseconds and this brings me to the end of today's session if you are interested in more such questions we have solved couple of them in the past i am attaching the links and references to those questions it will be a great revision opportunity to build in this monotonic stack concept i hope you liked it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye | Next Greater Element I | next-greater-element-i | The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution? | null | Array,Hash Table,Stack,Monotonic Stack | Easy | 503,556,739,2227 |
230 | okay hello everybody uh today i'm going to solve lead code problem number 230 kth smallest element in a binary search tree and in the description it says given the root of a binary search tree and an integer k return the k smallest value of all the values of the nod in the tree so let's see what we have here in the example one we have root of three with child knowledge of one four and if two as a right child nod of not one so we're looking for the first smallest value of all the values so we have one two three four so of course the smallest value among those values are one and we have one two three four five six and we're looking for a third smallest volume which is three yes and uh we can see since it is binary search tree um as you go left you get smaller volume as you go right you'll get higher volume so left not is always less than right uh right child not so how should we do this um we can have like df s in order and you can put it into a list and you can just simply return um kf uh the element in k minus one in that list or uh we can use a stack and first we will um add all the knowledge in the left side to the stack and once we hit the left very left bottom node we will start to check and compare if it is cave smallest volume so in order to do that every time i pop the value or the nod um i'm going to decrement k by 1 so when k equals to 0 that is the nod we're looking for and also we gotta take care of also considered not on the right after checking if k is not zero i'll just have root and becomes the root that right and okay let's code it out so let's have a base case if um k equals to zero let's return root.volume root.volume root.volume and as i said i'm gonna have us attack and i want to have a while loop that goes infinitely which is pretty simple a while one and also i want to go all the way to the bottom left so while root and i will put that into our stack and i want to go left so let's have root equals to root.that um when we hit the very bottom left nod we will get out of that while loop and i'll assign we declare root equals to the stack dot pop so in here we have three and one so the stack will have elements three and one in node the value of the nodes are three and one so if we pop it we're gonna have one and as i said i'm going to decrement k by 1 so that we keep track keeps track of k also want to keep track okay if okay becomes a zero this will return simply return root there's a trick here so here we're gonna have five three two one and once we pop an element from the root we're going to have one and that's not and k decrements by one k becomes two but that doesn't solve anything we got to go to um node 2. so b in the while loop inner while loop we have while root is not equal to 9. if we have root equals to that right we have null and it's gonna pass through it will pop two then it's also nine we're gonna go pop three and we'll have the volume and if there's if there were a right trial value of two it's gonna go here and it's gonna check this volume and even if it's not the volume that we're looking for yeah it's gonna go through here pass through here and we're gonna pop number three that makes sense yeah okay so we run the code it's taking forever oh there's a little typo come on all right we passed the test case okay the run time is 52 millisecond and memory usage is 18 megabytes so um i believe the time complexity would be the height of the tree because we go all the way down to the root and we also keep track of k we're gonna spend some time until k becomes zero so time complexity would be big o of height of three plus k and for the space complexity is gonna be big o of n because we might have to go search for um we might have to add all the nodes in our stack so that's our worst case all right thank you everybody and let's see you tomorrow | Kth Smallest Element in a BST | kth-smallest-element-in-a-bst | Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
**Example 1:**
**Input:** root = \[3,1,4,null,2\], k = 1
**Output:** 1
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], k = 3
**Output:** 3
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 104`
* `0 <= Node.val <= 104`
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize? | Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST). | Tree,Depth-First Search,Binary Search Tree,Binary Tree | Medium | 94,671 |
170 | YouTube welcome back today we have this problem it's uh two sum it's a data structure design problem actually the data structure design are becoming quite popular reason they actually I and I did like you know fuse uh in the last three months and I found tons of data structure design instead of just the function and an algorithmic thing but just the test structure design and in this one they will force you to build a uh what we could like to do to put that like an algorithm solution so basically let's just uh find this one we have design a data structure that accepts a stream of integers and check if the uh if it um if it has a pair of integers that sum up to a particular value Implement uh two sum class we have a two sum initialize the uh to some object with an empty array initially uh avoid the add avoid that integer and number okay so we have and we have find we have valued return true if there exist okay so basically we have a function and we should have two methods with this function and basically we have the function called two sums that we create the objects based on this function and in the function has two methods one called add and one called find and the add Returns the data structure and return and the find returns if there exists any pair of okay so we have hmm so let's say that we will have an array okay wait a minute we will have an array okay because I guess adding is not it's not hard actually but let's talk about the uh the find politically so we have array like one four uh zero and maybe like three and we want to add first so basically let's say that I am we're going to add uh two we're going to add two so basically the array will equal 1 4 0 3 and 2. and let's see that we want to find so basically we have this is what becomes quite interesting because basically we want to find um we want to find basically you find uh zero so if we want to find zero we can do two things we can just to compare 0 to 1 compare it to four compare it to zero and we'll find zero we return zero or we can do something different first of all that we could uh sort this one zero one two and three and four and use um binary search basically so basically we start low and high and try to find the middle if and for this example we find 0 and 4 the middle will be two we can build the middle to zero if the middle bigger than zero so there is no need to go to search in this one and we search in this one we have zero and one it will be the middle will be zero and we will return zero directly so I guess by this way it will be way more better and I guess the solution of it will be quite interesting and let's see okay um so basically um okay let's just delete that okay I will have um let's say that I will have um sorry I deleted them okay just open it I will have um the function uh function called find and I have function called add this what I'm getting uh I'll just delete these two things there's no need to help them and we will have some constant Norms equals empty array and let's see that we have let's say that it will be a lit is sorted because basically we want to sort the them with the find and maybe not sold them with the eight so basically we just made this true false and I will show you what is the um that will Co that will benefit us so basically in the function I'll have Val and I will say nums the push well and is sorted pulley equals to be false and yeah and the find also I will send the Vel and I will say the uh um if not is sorted sort this for me so it will be nums dot sort uh A and B and just select that and it will be a minus B and is sorted will be true and I will say um and let's do equal zero and I will say because we are sorting it so we can do when research let's Lin -1 Lin -1 Lin -1 and I'm saying a while uh low less than high if I will say first of all const the um to sum will equals um Norms of a low gloss nums of High and I will say if the um if the two sum uh less than value less than the value that we actually have um low will loss and equals one and I guess oh I did something wrong I and I guess oh I did something wrong when I described we don't want to find the specific one we want to find um two uh I just I don't know why I describe it like that but it will be the same solution basically we want to find basically let's say that five we have five here so we want to find anyone that equals five so we'll just all have zero a low and high and physically when we find a any numbers equals like low and like right now it's zero and four if zero and four lists then uh five I will increment the four the Low by one so it will be zero uh one and four so it will be equals five so I will return them directly I sorry I just descripted this one I don't know why I just um my mind was in other way so I say else um else if um the two sum is bigger that means that we should um it will be high Plus equals one I will say a high not height I will say else I guess it's mean the equal so return true and therefore the while finish I guess that's it right uh add is not a function what ah oh sorry I'm not returning them we turn uh add and find I guess this will work everything was no why everything was no just uh see why what's wrong physically it says let's just say that is sorted is false we have Norms equals empty array is sorted equals false so it equals false I am approaching the value and the find if it's not sorted I'm going to sort it so it will be nums dot sort it will be a b a minus B and um and is sorted equals true and I'm saying the let low equals zero and high equals Norms dot length minus one I'm saying while low is less than High and I'm saying that Corners two sum it's equals numbers of flow Plus numbers of high if two of some Let's uh to some less than the value low plus equal one else F to some oh I just um sorry for that I know everything 90 60 okay so let's talk about how this works basically so for example I guess for 48 and push does it does I guess it's a pretty straightforward I am just getting the value of the this method this function getting the value and just push it to the array but let's talk about what a user is sorted so basically I use it's sorted because I only sort when I add a function because right now let's say that I added a 2 to the array so basically our array right now we will have two elements so basically it's not sorted and sorted again but if I didn't run the ad we don't have to sort each line so basically this again this is some sort of optimization we can sort out of the box I can delete that is sorted and we can delete this but it's the why we put this sorted to make sure that we are um we basically it's some sort of performance we're adding performance to it just improves the performance we have low and high basically we want to get the two numbers that when you add to them they will equals this value so basically what we're going to do because we can start from low and high and we start to just find the comparison with them so for example let's say a well equals let's say 10 and basically we have this array uh five let's say 0 1 2 4 5 let six let seven and uh do you have any numbers that equal equals to ten um let's say that like 10 and 11 and 12. okay so what we're going to do first of all the low will equal zero and low will equals zero and I guess uh high will equals one two three four five six seven eight nine so it a high will equal length minus one so I guess yo equals eight so basically the two of some the two sum here basically the two sum will equals the index of flow and the index of high so it will equal zero Plus 12. which will equals 12. so we are well while we were saying that basically if the two of some 12 it's smaller than value no it's bigger physically so it's no this okay so if it bigger yeah it's bigger so the high uh decrease it by one because it's just assorted so if it's bigger okay let's just try to find someone's a smaller number so basically we start so basically the how it would be seven right now so basically the two of some would be equals um eleven plus zero so it will equal eleven so we will ask ourselves again okay if two of some less no actually two of some is bigger so okay let's the high by one so basically the high the higher it will equal six right now so basically the two of something tool equals zero uh that's the first element of nums and uh the seventh elements of um of not so it will be thin so I'm saying okay to equal sign so if not two phenoms less than value no if two of nums bigger than value no also so if it's not bigger and it's not small that means you're only equal to it so we'll just return true and yeah that's it basically and we can just make uh make a clue and just to try to add each one and just try to make some comparison but I guess it will take a lot of time and this one time complexity make it way more easy and basically that's it for this video and if you like this solution make sure to subscribe and hit the notification Bell so you will never miss a video | Two Sum III - Data structure design | two-sum-iii-data-structure-design | Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.
Implement the `TwoSum` class:
* `TwoSum()` Initializes the `TwoSum` object, with an empty array initially.
* `void add(int number)` Adds `number` to the data structure.
* `boolean find(int value)` Returns `true` if there exists any pair of numbers whose sum is equal to `value`, otherwise, it returns `false`.
**Example 1:**
**Input**
\[ "TwoSum ", "add ", "add ", "add ", "find ", "find "\]
\[\[\], \[1\], \[3\], \[5\], \[4\], \[7\]\]
**Output**
\[null, null, null, null, true, false\]
**Explanation**
TwoSum twoSum = new TwoSum();
twoSum.add(1); // \[\] --> \[1\]
twoSum.add(3); // \[1\] --> \[1,3\]
twoSum.add(5); // \[1,3\] --> \[1,3,5\]
twoSum.find(4); // 1 + 3 = 4, return true
twoSum.find(7); // No two integers sum up to 7, return false
**Constraints:**
* `-105 <= number <= 105`
* `-231 <= value <= 231 - 1`
* At most `104` calls will be made to `add` and `find`. | null | Array,Hash Table,Two Pointers,Design,Data Stream | Easy | 1,288,653 |
268 | hey guys welcome to a new video in today's video we're going to look at lead code problem and the problem's name is missing number so in this question we given a integer array called nums consisting of n District numbers in the range 0 through n both inclusives and our task is to return the only number in that range that is missing from the array so this is the input array given to us what is n is the length of the array is three so the numbers should be present within the range 0 to 3 both inclusive so the numbers are 0 1 2 and 3 but inside the input we have only three we have zero and we have one we don't have two so two is the missing number so 2 will be your output which is the expected output here similarly here n is equal to 2 what is the range it should be 0 to 2 which is given here so 0 to 2 the numbers are 0 1 and 2 now compare it with the input we have 0 we have zero we have 1 we have one so again two is missing so two will be your output in this case n is equal to 9 so the numbers are between 0 8 and 9 we have 9 here there's six there is four there is 2 there is three there is 5 there is 7 there is 0o there is 1 so what is the missing number is eight so8 will be your output so to solve this question you might observe that first we have to find the sum of all the numbers present inside the input the sum of all the numbers here is 3 + 0 + 1 which is equal numbers here is 3 + 0 + 1 which is equal numbers here is 3 + 0 + 1 which is equal to 4 so this is the sum without the missing number and we know the sum of N natural numbers is equal to n into n + 1 by 2 where n is equal to n into n + 1 by 2 where n is equal to n into n + 1 by 2 where n is the input given to us n is where n is the length of the array so 3 into 4 by 2 which is equal to 6 so actually the entire array should have sum equal to 6 but here we have the sum equal to 4 so if you do 6 - 4 6 - 4 sum equal to 4 so if you do 6 - 4 6 - 4 sum equal to 4 so if you do 6 - 4 6 - 4 is = 2 so this number will be your is = 2 so this number will be your is = 2 so this number will be your output that will be your missing number which is expected here so this is the formula we have to check n into n + 1 by formula we have to check n into n + 1 by formula we have to check n into n + 1 by 2 this will give you the total sum and from that sum we have to subtract the sum of the input array given to us and the difference will be the missing number now let's take a look at the code so here we're finding the input length so this is the input array so n is the length of the input array and I'm creating a variable sum without missing which is the sum of the input array and this is the sum n into n + 1 by 2 this is the sum n into n + 1 by 2 this is the sum n into n + 1 by 2 this will give you the total sum so if you subtract the total sum minus the sum of the array you will get the missing number and that missing number you will return it as the output so the time complexity of this approach is of n where n is the length of the input AR nums and the space complexity is of one because we're not using any extra space to all this question that's it guys thank you for watching and I'll see you in the next video | Missing Number | missing-number | Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._
**Example 1:**
**Input:** nums = \[3,0,1\]
**Output:** 2
**Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums.
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums.
**Example 3:**
**Input:** nums = \[9,6,4,2,3,5,7,0,1\]
**Output:** 8
**Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `0 <= nums[i] <= n`
* All the numbers of `nums` are **unique**.
**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity? | null | Array,Hash Table,Math,Bit Manipulation,Sorting | Easy | 41,136,287,770,2107 |
155 | in this video we're going to take a look at a legal problem called min stack so we want to design a stack that supports push pop top and retrieving the minimum element in constant time so implement the min stack class so basically we have a couple methods here so min stack basically initialize the stack object and push method basically push items onto the stack pop pops the top album that we have on our stack and the top which retrieves the top album that we have on our stack but this get min method would retrieve the uh retrieves the minimum element that we have in our stack so far right so in this case you can see here we basically initialize this method this class create an instance of this class and then we push items in we pop a top item that we have on our stack off and then we can also retrieve the top element as well as we can be able to get the minimum right so we want to do this all in constant time right so what we can do is we can use a stack data structure and inside here and basically when we push remove we can use a stack to do that but if we were to get the minimum element then in this case we have to iterate the entire stack to get a minimal element right so in this case this will now give us a constant time complexity to do that so what we can do instead is we can use a cache right so to store the minimum element that we have for each insertion and each removal right so basically for example if i have a cache like this for the current position right when we have let's say we want to insert those elements right here so two three one three right when we insert two onto the stack we basically know that the minimum element that we have is gonna be two so we put it here and uh then we insert three so three the minimum element that we have so far in this case is gonna be two so we insert two onto the cache right because the cache is that we for this current position right for this current position the minimum element that we have so far is either the top element that we have in our cache right before we insert two or it's gonna be this element right here that we're gonna insert onto the stack so in this case it's two is smaller so we just add two onto the cache because in this case um we want to keep track of the minimal element right and let's say if i want to remove the top element that we have right in this case the top element's three so in this case we remove it then we also have to remove it in our cache as well so the minimum element that we have so far in this case is going to be two right so if i were to insert one the minimum element that we have at this current position is going to be one if i were to insert three then the minimum element that we have so far is going to be one right we're going to compare one with three the top element that we have in our cache with element three is it smaller if it's smaller then we're gonna get this element to be the top right if it's not then we're gonna add one onto the cache that's the smallest element that we have so far so let's take a look at how we can do this in code so first we're gonna use a stack and we're also going to use a cache stack to cache the result for each insertion that we have right where each removal we want to make sure we get we keep track of the top element right the minimum element that we have and then for when we push an element first we're going to add the vowel onto the stack okay and then we check to see if the cache stack is empty right if it's empty that means we can that means the smallest element that we have at this current position in this case is going to be um vowel right so let's stick to push instead of ah so then what we're gonna do is we're going to first we have to give the top element that we have so in this case the top element that we have is the minimum element that we have so far right so the minimum element is equal to cash dot pop right we yeah we basically uh sorry peak by math so we retrieve the top element that we have in our cache and we check to see if min is actually smaller sorry it's actually bigger than about right if it's bigger than vowel then we're going to say cache.push vowel then we're going to say cache.push vowel then we're going to say cache.push we're going to push val as the smallest element that we have for the current position right otherwise if the min is in this case is let's say is smaller than the valve or smaller than or equal to then we just say cash dot push min right so basically that's how we add uh elements onto this min stack in constant time and now to pop elements pretty simple we just say um in this case stack dot pop right so we pop the top element that we have uh off our stack and return it right and then in this case uh because we're returning void so we don't have to return this element and then another thing that we also have to do is we have to remove that element off the cache as well because that cache is only track of the minimum element at that current position right so we uh we remove both of them okay and for peak is the same thing we basically just remove sorry we just returned the top element that we have on our stack and for getting the minimum element we just retrieve the top um the top element that we have on our cache so it's going to be cache dot peak and if we were to run the code and submit and you can see we have our success so this is basically how we solve this problem and a constant time complexity for all those methods | Min Stack | min-stack | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the `MinStack` class:
* `MinStack()` initializes the stack object.
* `void push(int val)` pushes the element `val` onto the stack.
* `void pop()` removes the element on the top of the stack.
* `int top()` gets the top element of the stack.
* `int getMin()` retrieves the minimum element in the stack.
You must implement a solution with `O(1)` time complexity for each function.
**Example 1:**
**Input**
\[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\]
\[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,null,-3,null,0,-2\]
**Explanation**
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
**Constraints:**
* `-231 <= val <= 231 - 1`
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
* At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`. | Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan) | Stack,Design | Easy | 239,716 |
1,720 | Shri Ram Liquid Problem Hum 720 Decoded During Bihar Government And Thursday Appointed Sexual Subscribe Video To Secure Property And Now In The Property Of Yes This Video Stretch Returns The Amazing Yes Yaar And Five Plus One Acid Hour Holare That Day Su And Use It Pain and agree to terms with five plus one cold here and according to in old age I just bteup and sentences are here five plus one vihar and order cancel hai Saurav states for all in this question a fog to draw in doing in your dealings in two hai Hey limit expressed turn off size in plus one and it's been given back first element 15210 is equal to a the first hua hai kar do ki aishwarya 20 clear not done for lu samay khul 208 electronic plus app e want It is being towed that now I plus one is equal to hair oil obscene that these folds are there I am finally well written yes friend now it is required Hey friend you come that Vijendra through all the way can no longer be sample questions for others And In Every Day With Tamil Element 60 And The First President Of The Year And 1104 Find The Meaning Of I English Joe Condition I English Joe Condition I English Joe Condition Middle Age 25000 Man And 101 More 512 Arrested 21 Fix And Power To 9 A Painted 21 Fennel 125 1200 10 Located In Laser Valley Finally She Gets All With Trivandrum Allegro And Afton Adheen Are With U | 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 |
337 | house rubber 3 is again a slight modification from house driver 1. where we remember in house driver 1 we have houses on a straight street and we use a integer number to represent how much money is in each house and the goal is to rob as much as money without robbing houses that are next to each other however in house rubber 3 the houses are no longer in the formation of a straight line instead it forms a binary tree for example here we have a banner tree rooted at number three and three has two child which is eight and five and eight has a chart of six five has chart of two and three so the constraint in house driver 3 is same as the constraint in house driver 1 where the robber cannot rob houses that are next to each other so in house driver 3 the houses are next to each other only when they are directly connected for example 3 and 8 are directly connected and 3 and 6 they are not directly connected so in this particular binary tree we could rob node 3 and since we already wrap node 3 we can no longer wrap its child nodes we can wrap node 6 node 2 and node 3 which gives us total money of 14. optionally we can skip node 3 and wrap node 8 and 5 gives us total money of 13. in this particular example 14 is the maximum number so let's derive the inference function for this dynamic programming problem let's first index each node in this example from zero so node three will have index of zero eight was one two let's use ri to denote the maximum amount you can rob from substrate rooted at node i for example r2 is the substrate rooted at node number two and r1 is the substrate rooted at node number one and r0 is actually the final answer we want to give r0 equals to max of the value of node 0 which is 3 plus node 3 and node 4 and node 5. since we already dropped node 0 we can no longer rob node 1 and node 2. so we'll have to look one step further from node 0's child nodes alternatively we can skip node 0 instead we can rob node 1 and node 2 and the max value between these two options would give us the final answer which leads us to the final inference function note here that we use the vowel to indicate the value of node i and l to indicate the left child and r to indicate the write out therefore the first option would be to rob the node i and since we wrap node i we have to skip its child nodes and instead we rob its grandchild node which includes the left node left right and right left of node i note here to simplify we use the i points to l and l to indicate the index of the left most grandchild node of node i so the second option will be to skip node i and instead we rob its child node which is the left node and the red node of node i similarly we use the i points to l to indicate the index of the left node and the value of i can be computed by recursively traversing down the binary tree so let's look at the final code here we have the three node definition where each node contains a value which represents the money in each house essentially and each node points to a left and right three node so here we have our main rob function which it takes in a root node and we have the helper function that takes in two additional integers which represent the maximum money can be robbed from the left and the right child node from the root node and in the helper function we have our base case where we check if the root node is null if it is null which is return 0 meaning no money can be robbed and if the root is not null we recursively trying to rob the left and the right child nodes note that while we recursively calling the left child node we define two integers left and left right to get the maximum money to drop from its grandchild nodes and similarly when we're recursively calling on the right child node and by traversing the tree in a post order we compute the maximum money can be wrought from each root node bottom up at each level of the tree traversal we can compute the maximum money can be robbed from its child node and have access to the maximum money from its grandchild nodes which enables us to take the maximum value out of the two options while we deriving the inference function in summary in this problem we have houses laid out in the formation of a binary tree where we cannot rub houses that are directly connected to each other while deriving the inference function we consider two options one is to wrap the current node and skip its child nodes and instead consider its grandchild nodes and the other option is to simply skip the current node and only consider its child nodes with the property of the binary tree we can recursively compute the maximum running can be robbed from each root node from bottom up till we backtrack to the root node with the final answer | House Robber III | house-robber-iii | The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**.
Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_.
**Example 1:**
**Input:** root = \[3,2,3,null,3,null,1\]
**Output:** 7
**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
**Example 2:**
**Input:** root = \[3,4,5,1,3,null,1\]
**Output:** 9
**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104` | null | Dynamic Programming,Tree,Depth-First Search,Binary Tree | Medium | 198,213 |
724 | all right let's talk about fine privilege in this so given array of integer numbers calculate the previous index of this array the favorite index is the index for the sum of all the numbers strictly to the left of the index is equal to the sum of all numbers repeated to index right so uh for example uh a b c b e f g right so at this index b d index right uh hold on and this index a plus b plus c is equal to e plus f plus q so you don't worry about the d index right this thing that is ignore so the idea is straight forward you just add a value uh all the value together and then you have to find the sum and then when you add the sum then just for each index you just minus the current value and the previous sum so the previous sign is whatever you try various right wherever you're traversing there so they just upload it so inside say zero for in num noms so some plus different norms and in previous song zero lens number lens i plus and then so previously is the you traverse right so plus equal to the num i and if previous line is equal to the all the value minus yourself minus the previous sum which is the left value then you know this is the index that you need to return so just return negative one if everything's not happening so for negative numbs is actually what i mean you don't want to a plus a b c d e f g right you don't want to add the value on the b so this is ignored so you have to subtract the d and also the value for a and b and c so you get the e f g value for the rest and that is equal to the previous sum which is the sum you have and this is how it is 173 is 11 5 6 is 11 right and this will be the solution and they just run a code and let's see okay and the timing space complexity for this one is actually really easy time is all open i use traverse every single element is all of them and this is all of them as well right so all of them plus all the things all over time is all the button space is constant it's local value you don't need any space please so space is constant which is all of one time is open and this will be the solution and if you feel helpful subscribe like if you want it and comment if you have any questions and problem and i will see you next time bye | Find Pivot Index | find-pivot-index | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. | Array,Prefix Sum | Easy | 560,2102,2369 |
1,962 | hello guys welcome to code enzyme and in this video we are going to discuss the problem 1960 of lead code uh remove stones to minimize the total in this playlist I make daily videos on lead code problems so if you like my content you can subscribe right now okay so the problem statement goes like you are given a zero index array piles where piles I represent the total number of stones in the ith file and an integer K you should apply the following operation exactly K times choose any piles I and remove floor of pulse I by two stones from it notice that you can apply the operation on the same pile more than once return the minimum possible number of stones after applying the K operations and flow X represents the floor and that is the GIF of the number greatest integer fact okay now let's try to understand it with an example so example one we have 549 so we have 5 4 and 9. this is an easy medium level problem okay you should have some knowledge of data structures otherwise you may not be able to solve it so for k equal to 2 so we need to apply this operation two times so first I am going to select 9 because it is the greatest number and so I will be able to remove more number of stones using Operation Red so this will become 5 4 and 5. and next time I can choose either of the fives so I will choose this and this will become three four five okay now I can just take the sum of this and it will give me 12 and this is my answer so to get this largest number if I try to sort this array in the reverse order for each time we sorted we will take an login time right and so let's just analyze the code for this approach so here is the code and if you are trying to use sorting to solve this problem so first you are going to sort it in reverse order and next you are always checking the zeroth index and replacing replace it by this and then you have to sort it again so it is going to go for n Square login time which is very uh unpleasant for this problem right it will for sure it will give you a tle uh we need to somewhere to some way to make sure to get this in O of one time if we are if you want to solve it in uh of n time right so uh what kind of data structure stores the largest element at the zeroth index it is Heap right so we can use a Max Heap to solve this problem so now let's see the code so first I'm going to import the necessary module hip hop ep5 so now I am making a heap and I'm converting into it into a heap okay this step might not be a necessary now for every I in piles I am going to push it and multiply it with a minus sign because in Python we don't have Max CP only up Heap now if I multiply it negative with negative in the largest number will come to the zeroth index with a negative sign so I have so at each step I have to multiply it with a minus sign to get the maximum of the Heap and now I can do this and now I will have to keep push it again with a negative sign multiplied with it okay and in the end I can return the sum of the Heap with a minus 1. so this is the solution for this code I hope I was able to explain it properly and thank you guys for watching this I will see you guys next time with another problem thank you | Remove Stones to Minimize the Total | single-threaded-cpu | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the operation on the **same** pile more than once.
Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_.
`floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down).
**Example 1:**
**Input:** piles = \[5,4,9\], k = 2
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[5,4,5\].
- Apply the operation on pile 0. The resulting piles are \[3,4,5\].
The total number of stones in \[3,4,5\] is 12.
**Example 2:**
**Input:** piles = \[4,3,6,7\], k = 3
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[4,3,3,7\].
- Apply the operation on pile 3. The resulting piles are \[4,3,3,4\].
- Apply the operation on pile 0. The resulting piles are \[2,3,3,4\].
The total number of stones in \[2,3,3,4\] is 12.
**Constraints:**
* `1 <= piles.length <= 105`
* `1 <= piles[i] <= 104`
* `1 <= k <= 105` | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks | Array,Sorting,Heap (Priority Queue) | Medium | 2176 |
257 | to return the path from root to leaf okay so the path from left subtree is one two and five and in right subtree one and three so suppose that there was here one more node in the four then the path would be one three and four okay right let and how you will tackle this problem let me take into the demo board so you get the further an understanding if you know about in order triversal then you will tackle this problem very easily let me tell let me give a little description about in order traversal in on order triversal is the first root come okay first root come then left and then right okay so we will use that concept we will use this you will use this concept first we will make a empty list this let me raise this and i think i'm not good at drawing so you guys understand that okay we will make this empty list okay now we will use the recursion uh to tackle this problem so what the in order traversal says in order to travel says first left tree then after first root then left right then right tree so we will use recursion so first we will uh tackle this node okay we will print this where we will add this value into htr okay so this is our hdr and after this and we will then after we will give space and this is space okay after that we will come in to recursively call the function and we will come into this node and we will append this node into this okay after that we will again record silicon on the left sub so there is no left safety then it will call on the right sub tree and the right subtree is a node exists as is five and okay it will happen five and after this we will make a condition that if left child or not on light child exist then in this uh this result will be appended to our in globe in this array okay so it will look like this two okay two and five okay after that after this the pointer will come here after this pointer will come here and we will call the recursive function in the left right sub tree and again arias will be one space after that two and when the left child and right child doesn't exist then this res will be appended to our this list and this will be our answer right this is a basically question is asking so let's jump into coding then you will get the further understanding what we are trying to say so left first we will make empty list equal lsd list and we will after that what we will do we will make a helper function that will help our helper function and it will take a root and empty string okay after that we will check if node exist if node if not node if there is no root node so we will return none if root adjust then we will do we will append we will add this uh root the root dot value the we will have add this value to this okay first we will so we will do we will make it a string in integer we will make it into a string and after that we will append and add it to row dot value and we then we will give a space the that we have done here right okay so it pretty look like first it will look like one then space there was space between them okay then two then space then five right this will be our string okay this will lower string and after that when the left child and right side doesn't exist then we will split this string based on like this okay two three and unlock sorry and then because it will become this and we will then we will append in our uh in our array and we will append this into our area that's the concept okay then if not left root dot left and not right okay not root right then we will append this to our this list okay so we will do that self dot list and we will append and how we will append up we have to written answer in this format see in this format so we will make you make use of join function okay join in and what and first we will split that and that on the basis of this okay where whenever it sees the space it will put that this into in the space okay here let's and so basically here was space it was filled with this it was filled with hair was space it was filled with this okay so split after that what it will do it will recursively call until with a uh until we doesn't reach to left and then leave note okay it will recursively call it helper and we will supply left first we will have supply left after that okay sorry after that we will supply we will call on the right subtree and then we will call from the out helper and we will give an empty in string okay so we and we then after that we will return our self dot list i hope you guys get the concept it doesn't get then please type in the comment box oh something went wrong what was that if left no left not and right okay oh sorry i'm not okay it's working fine let me submit it yeah it is pretty efficient okay it took 57 ms it okay pretty efficient then the previous i have submitted and thank you guys for watching | Binary Tree Paths | binary-tree-paths | Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100` | null | String,Backtracking,Tree,Depth-First Search,Binary Tree | Easy | 113,1030,2217 |
331 | today i'm gonna be working only at code question number 331 um verify pre-order serialization of a um verify pre-order serialization of a um verify pre-order serialization of a binary tree so one way to serialize a binary is to use pre-order traversal binary is to use pre-order traversal binary is to use pre-order traversal when you we encounter a non-null node when you we encounter a non-null node when you we encounter a non-null node uh we erect uh we record the nodes value so if it is a null node we record using a senate centennial sorry sentinel value such as hash so basically he's going to be providing us a string or a comma separated characters in a string and either they're going to be numbers or hash representing a uh a null value and then we're going to look into it and see if it is a valid representation of the binary tree so an example where it would be false would be one hash and the reason for that is that we need to have if there is only one node in it needed uh needed to have uh two hashes so that every because that's the proper representation this is also false nine hash because once we declare that it has nine has two childs which are both uh null we cannot have another node in that tree so for this one what we're going to be doing is basically looking at a node and calculating the basically calculating how many are the out degrees and an in degree for that for every node so for every node which is not null you will have two out degrees meaning you will have two children and one in degree which means that one parent except the root so in that being said uh we're gonna start our difference with one because the root is gonna have only one basically it's not going to have any parent so we're going to start with one and before even doing that we need to split our string so let's just call it the nodes and we're gonna take this pre ordered or split using a comma so we're gonna go through uh all the strings right and this which are gonna be represented as node like uh as node yes uh so we're gonna go through it and every single time we're gonna decrement the difference and if we ever at any point if we are less than the difference is less than zero that means uh this is wrong the serial uh the string representation of the tree is uh is not a valid one so we're gonna return false okay other uh and the second thing which we're gonna do is to check that node is equal to that hash if not if it is not a null node so if it is not equal to a hash what we're going to be doing is to like add 2 to the difference this is because every node is going to have 2 every non null node is going to have 2 out degrees so that's why we're gonna have uh we're gonna increase the difference by two and in then we just need to check one thing we wanted to make sure that the difference never goes uh below zero and the last thing we wanted to do is uh was that if the difference is equal to zero that means it's a very let's see realize uh serialization of the binary tree node equals looking good and it works | Verify Preorder Serialization of a Binary Tree | verify-preorder-serialization-of-a-binary-tree | One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`.
For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,# "`, where `'#'` represents a null node.
Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree.
It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer.
You may assume that the input format is always valid.
* For example, it could never contain two consecutive commas, such as `"1,,3 "`.
**Note:** You are not allowed to reconstruct the tree.
**Example 1:**
**Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
**Output:** true
**Example 2:**
**Input:** preorder = "1,#"
**Output:** false
**Example 3:**
**Input:** preorder = "9,#,#,1"
**Output:** false
**Constraints:**
* `1 <= preorder.length <= 104`
* `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`. | null | String,Stack,Tree,Binary Tree | Medium | null |
1,354 | hey what's up guys uh this is sean here so today at today's daily challenge problem right number 1354 construct target array with multiple sums um so this one is a very tricky problem yeah to be honest okay so you're giving like array of integers target okay and from a starting array uh so which is consisting of all ones you can conform or perform the following procedures so first you know x will be the sum right sum of all the elements in the current array and then you can choose any number inside the current array and update that number into this sum and you can do this procedures as many times as you need it and you need to check return true if it's possible to construct target from a which is one they're all one inside the set a otherwise false okay so for example right we have this uh nine three and five so we start from one so at the beginning the sum is three right and then we update one of the number into three that's why we have one three one so now the sum becomes a five right and now we update uh this five oh sorry this one into five and in the end so now the new sum is nine then we update nine uh at the first one that's why we have this knight three five okay as you guys can see uh the second one actually this one two actually there's no way we can update it from this one because obviously the sum is four already right and then that's why we can now get two yeah and so here are like some constraints here right okay so a naive idea approach not an approach a naive thinking process will be uh you know we'll be we'll try to update any numbers uh any uh a value here you know basically at the beginning we have all one right i mean so we just try to update and any ones to the sum right and then we try to update them one by one let's say here we have one two three four five six seven and then we pick any one we update into seven right now we have like another sum and we just pick an another one but how can we pick that i mean basically i mean we could try to check if the seven has already exist in the target if it is and then we simply just uh update the other numbers but you know that will not lead to an answer because for some cases you know maybe keep out updating this seven could be an uh could lead us to the final answer you know and there are like different like examples i'm not going to show you guys that basically what i'm trying to say here is that you know if you try to follow uh if you do it in the order that we try to find a one right and then update into seven okay then it will not basically there is no uh greedy approach for this one basically if you want to do it i mean basically you have to try to update all the numbers uh each numbers with the current sum and then you just keep going and going right but obviously with this kind of length here it will definitely tl because every time you have to do this like 10 to the power of knight 10 to the power of five possibilities possible branches right so if that's not going to work how can we do this kind of problem right i mean we need to think it in a reverse order basically if we cannot if it is hard for us to get from 1 2 knight three five how about you how about we try to get you we try to check if the target can be changed into this one right if that's the case and then we also have the answer right so if we take this one 935 right as an example right how can we change it back basically that this is the final step the final state we already know that right and how about the previous state right because you know now i think we have we might already find a pattern because you know from the starting state to the next state we have all we have many options here right we could update any of the numbers but if we're going backwards from this from current state there's only one path to the previous state why is that because remember know the sum is always increasing okay so that's why you know so the current step will always have the bigger step a bigger sum than the previous step which means that you know the last number we updated must be the greatest number among all the numbers here that's why you know that since you know the 9 is the greatest number at here you know we know that you know the number got updated in the previous step must be this one right and now you know with this kind of if it's this two arrays it's it'll be easy for us to calculate this number x here right so it's what's going to be the number here so basically this nine equals to what equals to x plus three plus five right because you know this nine how do we get nine the knight equals to the sum of the previous state and obviously x equals to one okay so now so that's why we have a the previous state we already find it so then the one this is one and what's next of course we're going to follow the same pattern here right so from this state here 5 will be the number got updated in the end because 5 is the biggest number among all these numbers that's why we're going to use the same formula to going to keep going back forward so now we have this word 1 3 and x okay now we have 5 equals to 1 sorry equals to x plus 1 plus 3 right that's why x equals 1. okay and that's why this is 1. and so in the lastly right we have 1 x and one okay now we have three equals to x plus one now the x is equal to one now everything is one right that's how we get the uh get the answer cool and yeah that's basically the idea here and how can we uh implement this uh this solution here you know since we're going to get we need to maintain basically the biggest number of the current array you know and we can use like a priority queue right to help us maintain that and so when we stop basically when the biggest one in the uh in the priority queue is one then we know everyone is one right i mean of course assuming there's no zero right and that's it right i mean that's gonna basically be our first approach here and we'll and the and there and actually there's the issue here because uh and we need to do some uh optimization on it but let's try to implement the first one first at least we you guys can get the idea and then we can work on the up optimization on top of that okay so the first version right so we're gonna have like the uh the priority queue right so at the beginning right priority queue we have this number and since we're going to get the biggest number we need an active version of the number right since the in python the product queue is a mini cube okay so that's that and then let's hipify right we let's convert this uh prodigy into a into real prodigy okay and so what's next uh oh and since you know we need to get the you know nine equals to x plus three plus five right and we need this three and five right and since we and we don't want to calculate three and five every time right that's why you know we can maintain like a total of numbers uh i mean the current total numbers and then we can subtract the nine from the total and then we can get this three and five right so yeah otherwise we have to loop through the entire array which will be too slow so okay that's why i'm going to have like total at the beginning it's going to be this one right uh sum of target okay cool and now while the priority queue of zero is greater than one right so again this one is since you're restoring the negative number so as long as the biggest one is still greater than one then we know okay we haven't finished that right which means there's still like number which is greater than one which means we still have to go keep going back to the earned uh in the start state okay so and that p code p product zero will be the biggest one uh for the current array right so we'll have like max equals to the this one right i'm going to pop that out okay and then uh so now we need to get the remaining part right so what's the remaining part like i said the remaining part this is the remaining okay the cards are remaining that's one remaining equals to the total minus max right so this nine is the max right and the total is this the array and the remaining part is three and three plus five right and now we can get the uh the x right this x here where i mean this x is the is what is the uh you know this one is likely to be consumed confusing you know this x means the sum but you know here maybe i should call it so that's why i call the pre how about the pre i carry the pre number of this current max so the three will be what pre will be the uh the max right minus the remaining right so that's how we get this pre here pretty okay and here we can get uh do a like simple check right so if the pre is smaller than one then we return false right which means that you know if we get like a pre number which is not a valid number then we know okay there's no way we can uh going back to the initial state just like this one right we have a one two right so for this one okay uh yeah it's all right so for this one i mean the uh the sum is five right and the two right so and the remaining is five minus two is three right that's the remaining and the max one is two so two minus three is why it's minus one it's pre right so pre if as long as the pre is not it's either equal smaller sorry it's smaller than one then we know okay it's impossible for us to going back because this prison is an invalid number in that case all right otherwise right uh otherwise uh yeah otherwise we just uh push that the new number back to the priority queue right so that we can continue our traversing remember it's going to do a an active number right so and the la one last things that you know we also need to update the total here right because we're going to need this total to calculate the next round and the total is updated so what's the updated total here uh we okay so we add the pre right so this is the new numbers but we subtract the max right that's the new total of the kernel array and then return true okay yeah i think that's the basic idea here you know but if you run this one this will it'll work for most of the cases but it will tle for a big case you know let's submit this one here this will tle because you know if there's like a case the first the number is one and the other one is like one yes as you guys can see we have a this is a format this version no so if we have like a huge number here you know as you guys can see here you know um the pre uh the pre will always be decreasing by one at a time right because the max is it's like you know let's just do a one two to what one thousand right so the max is one thousand right and then the total is one so basically this remains this remain will be one right because the total minus the max will be one so this one will equals to one and the price what the price like one thousand the minus remain which is what that's why it's 999 and as you guys can see if that's the case you know we have a while loop but we're going to only decrease one at a time that's why in this in when this number is pretty big we're going to have a tle in this case right and yeah so how can we solve it right i mean it's not that hard actually you know so for example if we have like one uh three and then like a one thousand right so the first time we have what we have one three what uh this is going to be a 996 right yeah and second time again right one three and then we have a 992 and so on and so forth right 3 988 right now you have seen the pattern so basically every time we're decreasing this ring this remaining number okay until we have reached the uh a smaller number right that's why a simple improvement will be instead of like uh only decreasing the remaining we can do a modular of the remaining so that we can quickly decrease this one down to the level of the of this uh the next of next available number okay but you know since we're changing this subtraction to a modular you know there are a few things we have to be careful okay so let's take a look what do we need to change here um so this one still holds right so which means that we're gonna do this pre it's gonna be uh this one do a modular of the remain right so that's our intention okay but if we change that something has to be changed as well first thing is that you know first one is this basically the condition here you know and you know for the case of 1 to thousand right if we do a if we do this kind of uh modular here like i said the remain will be equals to one if we do this one the remain is what so if the remain is one you know we do a max modular one we'll so the pre will be the same as uh the pre will be equals to zero in this case right and then we'll return false but actually if the remaining is one then we know okay this one will certainly be able to reduce uh to reduce to the initial state right because every time we will be reducing one at reducing one and in the end we'll have like one and one right in the end that's why you know the first thing we need to change here you know is this one basically if the remaining is equal to one right and then we can simply return true because then we know okay this the current the max number will certainly be able to reduce to uh to one at a time that's why you know we can we don't need we shouldn't use this pre uh this condition here right so that's the first thing and what's the second one so the second one is this one basically here we're only checking if the price smaller than one but there's like another case you know for example the this one two case right in this case you know the maximum is smaller than remaining in this case right so which means that this pre will be the same as this max so that's why you know here uh besides this one we also need to check if the pre is equal to the max we also return fast yeah i think that's it right i mean the uh that's the two changes we need to make here and if i run the code okay accept it right if i run this again oh i see uh yeah actually there's like a special case we haven't covered here which is the single number case you know because let's say if we have like a three in the uh only one number here you know if there's only one number uh what's going to be the answer for this one actually for the three number you know the only possible answer here with a single number is one because you know the number itself will be the uh the number itself will be the total right so which means that you know if the target is three and since we're starting from one right if the starting point is one so which means that we'll never be able to increase this sum that's why i know this one will always be one no matter how many times we have done these procedures that's why you know the only possible va valid case for a single letter is one okay and why this one failed it's because you know if we have three here right and three is greater than one and we just uh yeah we what we pop this three out right now the remaining is what remaining zero okay and we try to do a modular with zero that's why we throw the exception right that's why you know we can simply we can do a simple check at the beginning basically if the uh if the length of target is equal to one right and then we simply need to check we check if the target is equal to this one or not okay and yeah so if i run this code again so now it passed right oh and one last thing you know maybe someone attempting to use a condition here like the if the maximum is either equal smaller than remain if this one is the case you know then we return fast right because you know if you read this one someone may have thought okay can we use this condition to check the force no because you know even when the maximum is greater than remaining as long as it can the modular is equal to zero then we also need to return zero we also need to re return uh fast right for example you know the maximum is pretty big let's say it's like uh it's nine zero two and the remaining is two okay in this case i mean the maximum is greater than the remaining but we still need to return false because if we do this one right return uh do module of two what we will get we'll get zero the pre is zero which is not a valid number that's why we cannot use this one to check everything we have to use this one and oh that the time complexity right i mean pretty straightforward we have a uh priority queue right and the number is like the uh the length of numbers so that's why i think time complexity will be unlocked right in this case yeah i mean that's it right this one pretty tricky problem you know the first one is that you have to be able to figure out we need to instead of uh going forward we have to go back go backward right and well going back forward or going backwards uh we have first we need to have like priority queue i think this part is not that difficult to get right but second one is that you know how can we uh improve this uh this special case by instead of doing the subtraction we need to do the modular but if we do a modular it adds a lit it says a little more complication here because um this module i mean we might end up uh stacking at an infinite loop here for this one for in the case of this one because the pre may not be smaller it might not be becomes becoming smaller that's why we have to add a few other checks here and also plus this one right cool i'll just stop here and thank you for watching this video guys stay tuned see you guys soon bye | Construct Target Array With Multiple Sums | find-players-with-zero-or-one-losses | You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure :
* let `x` be the sum of all elements currently in your array.
* choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`.
* You may repeat this procedure as many times as needed.
Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`.
**Example 1:**
**Input:** target = \[9,3,5\]
**Output:** true
**Explanation:** Start with arr = \[1, 1, 1\]
\[1, 1, 1\], sum = 3 choose index 1
\[1, 3, 1\], sum = 5 choose index 2
\[1, 3, 5\], sum = 9 choose index 0
\[9, 3, 5\] Done
**Example 2:**
**Input:** target = \[1,1,1,2\]
**Output:** false
**Explanation:** Impossible to create target array from \[1,1,1,1\].
**Example 3:**
**Input:** target = \[8,5\]
**Output:** true
**Constraints:**
* `n == target.length`
* `1 <= n <= 5 * 104`
* `1 <= target[i] <= 109` | Count the number of times a player loses while iterating through the matches. | Array,Hash Table,Sorting,Counting | Medium | 236 |
698 | everyone welcome back and let's write some more neat code today so today let's solve the problem partition to k equal subset sum so this is definitely a challenging problem especially for a medium but it is a very good problem to understand you can definitely learn a lot we're given an integer array of nums and we're given a single integer k we want to return true if it's possible to divide this array of nums into k non-empty subsets such that the sum of non-empty subsets such that the sum of non-empty subsets such that the sum of all of the subsets are equal in other words what is the sum of those subsets going to be it's going to be nums or rather the sum of all of the numbers in the array divided by k right so of course it has to be divisible by k right so suppose our sum of integers is 10 and k happens to be 2 then we have 10 divided by 2 that means each subset is going to have a sum of 5. but if we had a total of 11 and we had two subsets this does not divide so it's clearly impossible right so that's one check that we can do but in the generic case uh it's going to be pretty difficult to solve this problem it's not going to be a super efficient solution but let's just try to understand how we can even get a working solution at all and the easiest way to start is to try to understand one of the examples so here you can see that this is the input that we're given it has about seven integers and it doesn't really matter how many integers we have because we are guaranteed that we're going to have at least k integers which makes sense if we're going to divide this into k different groups the sum of all of these integers happens to be i think it's about 20. we need to divide 20 into four equal groups of uh a total sum of five each and is it possible to do that there's one way that they explain to us here if we just take five and put it in its own group if we take four and one put them in their own group if we take a three and two from here and you can see we have another three and two over here so it's possible these are going to be the four groups so in that case we can return true but how exactly can we come up with what the solution is it's not easy in the worst case we're gonna kind of have to check every single possible combination and even doing that itself uh you know checking every possible combination is called backtracking that's the technique that we're going to be using and even doing it this way there's multiple backtracking solutions you can do so the important thing here is to really understand the time complexity of each of them so we can figure out which one is the most efficient even though in my opinion if you can come up with any of them at all you should pass your interview but you never know so let's try to understand the most efficient way to do this so like i mentioned there's multiple ways to solve this problem with backtracking first let me explain to you one of the slightly less efficient ways and the time complexity of this solution is actually going to be k the input k to the power of n where n is actually going to be the size of this nums array so one way to think about this is we have we want k uh equal size groups right so it's almost like we want k buckets right k is four so we have like uh four buckets right each of them is going to be initially zero we want to fill each of these buckets with the integer uh the sum of nums divided by k right this is our target that we're looking for each of these buckets right and the general idea here is we're going to iterate through this list of nums and each time we get to one of these integers we have a decision what is our decision well we can put this four value in the first bucket or the second bucket or the third bucket or the fourth bucket and we're going to have that choice for every single value in this input array so you can see that if we drew the decision tree it would look something like this we'd have four decisions in other words k decisions each time and you know then we would continue to do that and we do that for every single integer you can already tell how huge this tree is going to be the height of the tree is going to be n because we have n integers in the input array so that's where i'm getting this time complexity k to the power of n from and this isn't really a bad solution in my opinion but it's hard to get this to actually pass on leak code because there is a slightly more efficient solution that i'm going to show you and just to kind of skip ahead let me actually tell you what the time complexity of that solution is before we even implement the solution so i so you can kind of understand why it's better it's actually going to be 2 to the power of n and you can see that 2 to the power of n is usually going to be smaller than k could be a really big integer even if k was 3 to the power of n 2 to the power of n is actually a lot smaller than this value it might not seem like it but it's a lot smaller so this is a very much more efficient solution there's actually going to be one more constant in it k times 2 to the power of n let me actually explain to you this solution and how we can code it up as well so the idea is pretty similar because we are going to have a the target value which is going to be the exact same the sum of the nums divided by k but in this case uh for each value we have we're going to only have two decisions we're going to say either we include this number in our sum or we don't include this number in our sum and rather than trying to create all k of the buckets at once we're gonna start just creating a single bucket we know that the sum the target value of a bucket is in this case five right so we're going to try to get this target value of 5 from any of the values in this input array so doing it like this you can see we have two decisions rather than k so for each value suppose 4 either we include 4 or we don't include four which would give us a zero we go to the next value now three either we include the three which will put us at seven or we don't include the three which will leave us at four similarly on the right side of the tree we include the three or we don't include the three which will leave us at zero now one thing you can already tell in one of the cases we went over our target value so of course this is not one of the ways we can sum up to this target so we're not going to continue down this path there's no need we're going to continue doing this for every single value in the array it's going to be a big tree so i'm not going to draw it out but our goal here is remember to get to the target value so right so suppose you know we skipped a few integers ahead and down this path we chose a one integer which is actually the last integer in the input you can see up above right uh in that case if we did that we'd have a sum of five so this is good we found one of the ways that we could get the target value right so just finding a single one right remember we're trying to find all four uh of the subsets but so far we only found a single subset how hard was it to find a single subset well the height of this tree could be n because again we're going to have to iterate through the entire list of nums and the number of decisions we have is 2 so you can see how i'm getting the 2 to the power of n from but remember the time complexity of this solution is actually k times 2 to the power of n so what more do we need to do here well it's actually pretty simple we need to now get the next three subsets we found one of them now we need to do the next ones right so now we're at a point where k is no longer equal to four it's actually equal to three but it's not only that simple because remember we uh to build a single one of the subsets we had to use a couple integers right which integers did we have to use we first used the four value that you can see up above and we also used a one value so pretty much we're gonna have to say okay the next three subsets that we create we're not allowed to use these two integers that we already used before so we have to keep track of that and it's not going to be too difficult we can just use an array to keep track of which ones we're no longer allowed to use anymore but that's the main logic of this problem right so just to give you an idea this tree is not complete yet now uh you know we found one of the subsets next we're gonna create another decision tree uh to find the second subset and then we'd do the same to find the third and fourth subsets as well and we might not only go down this path it could have been from here this is a 3 value but if we chose a 2 then we would have had a sum of 5 and then we can go down this path as well to find the following subsets so it's definitely not simple to arrive at this solution it's one of the harder backtracking problems but i hope it's starting to make sense to you and i hope you understand why the time complexity is what it is because one of these trees is two to the power of n and we're gonna have four of these trees stacked on top of each other or not just four it could be a generic value like k so k times this is gonna be the overall time complexity so after all that's said and done we can finally jump into the code now so now let's finally code it up and remember we are going to have a target value which is what we want each of these subsets to sum up to and that target value is just going to be uh the sum divided by k and we're also going to keep track of which values from the list of nums that we've already used before initially we can just populate this list of all falses and it's going to be the same length as the length of the input array nums so we can do it just like that and after we use one of these we're going to end up setting it to true so now to actually implement the back tracking and if you've seen any of my videos before you probably know i like to nest my functions inside of the root function so we don't have to pass in these two parameters or even these parameters but we are going to keep track of three values one is what index are we at in nums currently second how many k partitions are left that we need to build initially it could be four it could be five it could be whatever but we want to know how many partitions do we still have left to build of the current subset that we're building we want to know what is the sum of that subset currently and is it getting close to the target sub uh subset value that we want it to get close to so this is the backtracking now what's going to be the ultimate base case well if k was equal to 0 right meaning we don't have to do any subsets anymore we've already built the subsets we want to do and we were successful in doing that so if k is n is equal to zero we can just return true meaning it is possible we achieved it and we can return true if k is not equal to zero then we still have to do our backtracking but there's actually one other base case what happens when the subset sum ends up becoming the target value then what do we do well it doesn't mean we can immediately stop just yet because we still might have more subsets to build but what that means is if the subset sum is equal to the target value that means we're done building this subset that we're currently at so now what are we going to do well we're going to call backtracking again recursively and for i the value we're going to pass for index i is going to be the beginning of the nums array because now we're building a new subset so we're allowed to start back at the beginning of the nums array we might not be able to use the first value that'll depend on which values we used previously we can figure that out from this array for the index i we can pass in 0 for the k value we're going to pass k minus 1 because we already built one of the subsets so now we need to build k minus 1 additional subsets for the subset sum since we're now going to be building a new subset we can pass in 0 because currently it's an empty subset right so this is what we're going to end up returning now you can see that if k was equal to 1 in this case and we're passing in k minus 1 then recursively this function is going to execute the first base case which is going to return true so you can see that this is kind of going to work out but now we actually need to implement the main logic of this function the recursive calls so i'm going to use a second pointer j to iterate through all of the values in the array starting at index i because that's where we're starting at going up until the end of the nums array now for each of these values what are we saying for each value in nums we can either choose it or we cannot choose it but we can only choose the value if it's available so if not used at index j if this value is not used and if we you know take our current subset sum and add to it the value that we're about to use which is that index j nums at index j we don't want this to exceed the target value so if it's greater than the target value then we're going to continue to the next iteration of the loop basically we're going to skip this value because we know it's not going to lead us down a valid path so if the value has already been used and actually we can get rid of this not so if the value has already been used or it exceeds the target then we can continue if not though then we're actually going to get into our recursive case we're going to end up using this value so we're going to set used equal to true then we're going to do our recursive call backtrack let me just write out the function call and then after we've done the backtracking we're going to clean up basically reverse our decision which you commonly do in backtracking problems say okay we use this value now after the call we're no longer going to be using it so we're going to set this back equal to false now what are we going to pass in for backtracking if we use this value we're currently at index j so we're going to pass in to this j plus one so when we call recursively the backtracking it's going to start at j plus one that's what we want it to do for k is going to stay the same we're only going to be decrementing k if we've successfully completed a subset sum and lastly the actual subset sum itself uh we can set to subset sum plus nums of j and what do we actually care about this function call well we only care about it if it returns true because if this returns true that must mean we found a valid way to do this so then we can immediately return true we don't have to do anything else so let's uh write that but yeah so that's the main recursive portion of this function you know maybe it's easier than you thought maybe it's even more difficult than you thought but if we don't end up returning true in this case and our entire loop executes we go through every possible decision then we just want to return false because that means we did not find a successful way and remember don't forget to actually call your function so let's call backtrack for the initial index we're of course going to pass zero for k we're gonna pass in the input parameter k and for the initial subset sum we're also gonna pass in zero so let's return the solution and believe it or not that's the entire code now let's run it to make sure that it actually works that's very important okay so i actually had a small typo over here we don't want the condition and we actually want or because if either of these is true then we don't want to execute the back tracking you can see how hard these problems are a small mistake like that will cost you so now let's actually try running it again and as you can see on the left yes the solution works and it's pretty efficient and actually if you want to make it even more efficient there's a couple lines you can actually paste in let me just quickly do that to save time so like we talked about at the beginning if the sum of nums isn't divisible by k meaning that there's a remainder if we try to divide it by k that's what you can do with the mod operator then we want to immediately return false that'll save us a little bit of time and also we want if we sort the input array nums in reverse order so biggest to smallest that will also save us a little bit of time because that'll that will make our base case execute a little bit faster not our base case but in this case here that you can see if the val if the sum becomes greater than our target so we won't end up executing unnecessary backtracking calls so a couple things you can do let me just see how much faster it runs by doing that so you can see actually it made it run quite a lot faster 36 milliseconds faster than 95 or 94 so i really hope this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching | Partition to K Equal Sum Subsets | partition-to-k-equal-sum-subsets | Given an integer array `nums` and an integer `k`, return `true` if it is possible to divide this array into `k` non-empty subsets whose sums are all equal.
**Example 1:**
**Input:** nums = \[4,3,2,3,5,2,1\], k = 4
**Output:** true
**Explanation:** It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
**Example 2:**
**Input:** nums = \[1,2,3,4\], k = 3
**Output:** false
**Constraints:**
* `1 <= k <= nums.length <= 16`
* `1 <= nums[i] <= 104`
* The frequency of each element is in the range `[1, 4]`. | We can figure out what target each subset must sum to. Then, let's recursively search, where at each call to our function, we choose which of k subsets the next value will join. | Array,Dynamic Programming,Backtracking,Bit Manipulation,Memoization,Bitmask | Medium | 416,2135 |
240 | foreign challenge the problem that we have in today is search a 2d Matrix 2. here in this question we are given a matrix a size M cross n wherein the elements are sorted along the rows and across the columns what we need to do we need to tell whether a particular Target element exists in this Matrix or not if it does then we need to return true if it doesn't then we need to return false for all those who have been following along we've already solved a very similar kind of a question which is search a 2d Matrix and if you go and check out the constraints they're almost the same so here is the video I'll be using the same concept that I have highlighted in this video as well and if I go and check out the Java solution that is mentioned over here then the same solution will get accepted so for those who are not aware of the algorithm behind it let's walk through the presentation and I'll be explaining it there search a 2d Matrix to lead code 240. it's a medium level question and I also feel the same also in case if you have any doubt understanding this question or if you want to ask anything from me in general please feel free to drop a message on your telegram group or the Discord server both the links are stated below now let's get back to the same example that was specified in the question we have a 2d Matrix and we need to search for a particular element and here the element in this case happens to be 5. we're also told that all the elements are sorted across rows and columns so if you pick out pick up any row then you will see that the row is sorted and if you pick up any column for example this one again the elements would be sorted what do we do in such problems we either start from the top right corner which is 15 or bottom left corner which is 18 and let's hypothetically assume that the target element happens to be 5 and we will create two pointers which is basically acting as the identity of a cell here the row pointer is pointing to the last row and column pointer is pointing to the First Column We compare this value with 5 so if You observe then 18 is greater than 5 as a result of which we can simply discard all the elements towards the right of 18 so this entire row can be discarded we simply reduce the row pointer by one unit and now row pointer points over here again we compare 10 with 5 10 is much greater than 5 as a result of it we can simply discard all the elements towards let's write let's simply reduce the row pointer now points over here and column pointer is still at the zeroth index now we get three add three we can make a comparison with five since 3 is lower than 5 there is a possibility that 5 May lie towards the right of three therefore we will be incrementing the column pointer this time the column pointer gets incremented over here again we check whether this current value which is 6 is greater than equal to or less than 5 since it is greater than 5 what do we do all the elements towards the right of the current element can't be equal to 5 because it would be greater than 6 as a result of which we simply reduce the row count when we reduce the row count where we land at this particular position and then we can make a compa we again make a comparison with five since both of them turns out to be equal we simply return true from there and then itself this is what I told in search in a 2d Matrix a 74 lead code 74 and I have exactly explained the same algorithm over here as well now let's quickly move on to the coding section and conclude it up the time complexity of this particular approach is order of row count plus column count because in the worst case what could happen UI trade along all the rows one by one and then you iterate along all the columns that we have so there could be possibility that you start from over this particular element and you find that vertical the target element over here therefore in the worst case the time complexity would be the number of rows that you have and the number of columns that you have without further Ado let's quickly walk through the coding section here I've created two pointers one for the number of rows that we have other one for the number of columns that we have and uh these are like few Corner cases in case my row index the total number of rows that we have is zero or total number of column that we I have is zero then I should return false in those cases otherwise I go ahead and create two pointers i signifies the last row index do index and J signifies the column index that we are currently at and I have initialized J2 0 and I2 M minus 1 this signifies that I am starting from the bottom uh left index left element and while I is greater than 0 J is less than n i extract the current element I compare it with the target if it is equal then I return true otherwise if it is greater than Target I simply reduce the ith pointer otherwise I increment the JS pointer and J signifies the column index once I am out of the loop in case this screw condition was never met I simply return false so let's try this up why is it taking so much time so it is 50 faster and which is pretty good uh probably I'm on a slower Network I am connected to VPN right now uh so let's ignore that as I talked about the time complexity of this approach to the order of R plus c and space complexity is again constantly with this let's wrap up today's session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel also in case you are interested in more solutions more problems on the concept of matrices then you can check out coding decoded SD preparation sheet and here I have provided the most critical questions from interviews perspective on the topic of matrices so do check this revision sheet out and here you will find questions which are there in the increasing order of complexities easy medium and hard and you'll find some of the interesting questions as well so do try those that are specified with double asterisk signs because they are highly likely to be asked an interview over to you guys take care I'll see you tomorrow with another fresh question foreign | Search a 2D Matrix II | search-a-2d-matrix-ii | Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:
* Integers in each row are sorted in ascending from left to right.
* Integers in each column are sorted in ascending from top to bottom.
**Example 1:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= n, m <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the integers in each row are **sorted** in ascending order.
* All the integers in each column are **sorted** in ascending order.
* `-109 <= target <= 109` | null | Array,Binary Search,Divide and Conquer,Matrix | Medium | 74 |
877 | uh hey juno okay hey everybody this is larry this is the may 5th of the league code may 5th this is the fifth day of august the code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom so yeah so that i had to edit it but hopefully you enjoy seeing the doggo uh i don't know why this isn't loading stone game seems like pretty straightforward but yeah so i usually stop this live so if it's a little bit slow um you know fast forward whatever you need to do um because you know just get to whatever's important to you i'm refreshing right now so we'll see um yeah juno needs to sleep so i don't know how diverse okay anyway today's problem is stone game so alex and he plays a game uh even number piles in the world has a problem objective most domes the total and the total number of strongest odds so there are no ties okay take turns each time they take a pass from beginning or the end of the world okay oh okay so basically alex can take the top and the beginning and the end um so there's a straightforward dynamic programming one that i would do for this one i'm trying to think whether i could be smarter but yeah but the kind of you know one thing that i would say about dynamic programming is that it is often um not often depends it's often like a clever way to doing brute force uh and what i mean by that is just that you're trying everything but you're doing everything in a way that um that tries every possibility and but in a way that you reuse states and what that means is that basically you do because you're doing something again you can save it up so that you don't recalculate it for the next time right um and because of that uh i think this one there's a very innate brute force algorithm with respect to okay for example the first person alex can only take i mean it has two moves right beginning or the end the beginning the end and so forth blah and you kind of get the score that way um yeah and you know with a naive algorithm you may write something like um score let's just say best score um you know maybe you have a pile that's you know um you remove the beginning or the end but notice that if you had something like this because this is a new current pile um which is different from this one say but notice that this input it's always going to have be a sub array of the original input right and what i mean by that means that this is always going to be some sub array so it's going to be either a left point and a right pointer so from that you can what is commonly done is that because of that you can actually just keep track of you know because how do you represent a sub array right from a beginning point and a uh and an ending point so that's so we can set that up by yeah by just keeping track of the left and right and in this case we want to be explicit because if you don't that's where mistakes happen so left right is inclusive of the numbers of the piles that we consider and in that case yeah and let's see if there's one pile left that would be our base case if there's one pile left and in this case we actually want to get oh actually we want to see whether alex wins or lee wins okay so the first pla so we so there are a couple of things that is game theory and kind of tricky uh or at least like i don't know if it's easy to make an observation on um for me i know these things because of experience and i've done game three problems and so forth but the idea about this is i would look up a couple of things the big one is mini max meaning that you're minimizing the other person's score while maximizing your score um and in this case this is a symmetric game meaning that given a uh given a state your moves um your moves are the same as their moves otherwise you can imagine this is like maybe alex score and this and then you there's another function that's like least score or something like that but in this case you can use one func one function because it's a symmetric game so okay so now there's one score left what is the score here right our best score is just powers of left because that's all we have left um and then if that is not the case then what happens well this current person can either take the left or the right so in a way like i said it's going to be brute force and you just calculate the score so best is equal to let's just say you go to negative infinity and we could set infinity to various things but let's just say was it full i know that people give me comments about what i should use for infinity so let's play around this one for tonight but yeah and then now we take left right what does that mean is that so when we take the left it means that well we take the best score of left plus one right because now this is the sub array that we're using except for that this is now the other person's turn so you and your score um you know when you're trying to maximize in this particular case um you're trying to maximize the difference between your score and their score and that in a greedy kind of way so in that case this is going to be powers of left which is the score that you just got minus to score that the best score that your opponent can have um it's a little bit weird it's a little bit tricky this mini max i definitely recommend if you're interested in this really reading up on mini max um in game theory um that said these things are at least in america uh really in interviews so yeah um anyway so this is where we take right um this also follows the same logic of okay now you array shrink by one which is the one on the right and then now at the very end we can return best of course i didn't do any memorization don't worry we'll get to it but yeah so because there are no ties alex can win if alex has more stone than lee so how do you represent that well alex has more stone than lee if best score of zero n minus one if this is greater than zero because what does that mean if this is greater than zero if um yeah if the current person has a positive delta that means it has more score so in this case we return true because the first person wins otherwise will return false and there's no ties so we don't have to check for it um a fun thing to know in this particular type of problem or this particular problem anyway is that the total number is sum of piles right of stones so from this math you know that uh alex score plus least score is equal to total so you can kind of back out and then alex minus lee is equal to this thing that we have which we'll just put as delta um so this is not actually relevant to solving this particular problem we're just kind of giving an example and then you add them two together you have um this thing right so basically and so from here this is just how you if you face a problem where you need to score this is alex's best score um yeah anyway so of so as we said um let's memorize this because well what is left and what is right uh left can be z oops left can be zero to n right can be also zero to n but roughly speaking left to n but we can generalize it to 0 to n just for lazy com proxy analysis so they're all n square total inputs right um and for each input we do all of one work assuming that we memorize so all one work per input so total time complexity will be or with n squared and total space complexity will also be o of n squared because we have all this thing o of one space per input um yeah otherwise this is exponential because you're doing two moves on every recursion and there's just a lot of recursions so here then let's set up the recursion so here the way that i like to do it and you might see other things is that i just like to be explicit about it uh let's also just be consistent about the casing uh times and this is that doesn't really matter because we have two things so in this case you have left physical the right return pause otherwise we check whether this is cached if this is catch we return cash otherwise we do the expensive calculation of recursion and then at the very end we set up the cash right um oops uh now let's test i think i use very often no well there's only one test that's weird uh this is kind of tricky thing to verify as well because as you can tell um because this has the worst combination of this is a boolean answer and they only give you one example so maybe from that i'm a little bit not confident of some must be odd i didn't really do the math uh this is a six and this is four say it should be okay um yeah right so okay i don't know i'm a little bit lazy today so i'm just gonna give it a submit but i would also advocate just writing more test cases and so forth and this is good accepted yeah um yeah so i think the part that people get i get questions a lot with respect to these kind of game theory problems is that why do you do the subtraction here um i think the adding the score makes sense the subtraction is trying because you're trying to minimize this um the opponent's score but it may not be a sufficient explanation so i definitely recommend reading up on mini max and game theory um the principles there kind of makes sense there in terms of caching um yeah i think this is good um i think this is actually so this is top-down uh memorization so this is top-down uh memorization so this is top-down uh memorization but i definitely advocate practicing the bottom sub dynamic programming as well because especially in this case it's not as trivial to figuring out the order to do this in um so it'll be a good exercise for you and i and yeah um okay that's all i have for this farm uh i'll see you out tomorrow stay good stay healthy take your mental health i'll see you later bye | Stone Game | shortest-path-visiting-all-nodes | Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**. | null | Dynamic Programming,Bit Manipulation,Breadth-First Search,Graph,Bitmask | Hard | null |
459 | Hello hello everybody welcome to my channel it's all no problem repeated after giving one teaspoon check if i can be constructed by taking a sub spring of wheat and pending multiple copies of serving to the u majumdar giving consists of lower case english letters only and friends Will Not Exceed Shyam Whose Example In Chief Vice Chief Can Divide subscribe to the Video then subscribe to the Page if you liked The Video then pattern in the same way ki hai pattern ABCD penis up and four times will get subscribe my channel and also like big B C D A B C End Subscribe Sach Difficult Times End Tours Subscribe Problem Solve This Point Subscribe To That And Will Start From Foreign Lands And Right To Life But At Least To Pattern Expert To Repeated Pattern Fennel Just Stand Language To And Got Killed In Length 153 Possible And Wherever You For This Is Constructed At Will Through Its Soul Will Give Water For Boys Will Live Within 100 Add Character Subscribe Channel Subscribe Multiple Sub Subscribe Increment And Links Pan India And Will Just Sacrifice Of Places Where Is Vikram And Basically Through All possible veg sandwich subscribe button and have so let's previous increment record for this approach 2.1 under land for this is like 2.1 under land for this is like 2.1 under land for this is like you from intel 200 ml - - festival you from intel 200 ml - - festival you from intel 200 ml - - festival m0vie plus for this b director is equal to two plus two is equal to two plus two is equal to two plus two and bell increment i And after doing chants of Viplav Sale is Twitter Share and subscribe the Channel ABC will start from subscribe to subscribe and subscribe And subscribe The Amazing Like this hairstyle in the first chief testing this pattern should strive for this from VCD I have been late Also serious and civil computer subscribe Video Below Lift Bittu And Will Give Welcome To 90 Will Return Gift Subscribe To All This Now It's Late I Folded The Switch I Gas Meanwhile Minister In Condition Arvind Check The Tiffin Perfectly Model Above The Current Length And Otherwise Will Not Be Correct subscribe this Video give a That And Accepted What Is The Time Complexity Of Dissolution Beautiful Time Complexity Of Dissolution Enlightened One Two Times Were Running With Truth And Dare End Director Subha Dhund Gay Men Will Go In Subscribe Solution Can Be Improved Subscribe Chief Suvivi Constructed With Time Pattern Multiple Time Subscribe Button Video 300 Spartan Mill Repeat The Saw A Positive Eid Ki Ends Flat Se Connected With Templar Same Here Right Nau Admits Devi Hai Android Playstore Time Subah Vikram Eid Between Slide Plusm Ki And You Will Remove The first character of Virudh First character and last character from Dos David Possible from this point of total 22 and Thursday morning District President Share and subscribe the Channel subscribe and subscribe the Video then subscribe to The Amazing Subscribe to Joe Here is the code for its very First Edit Two Times And Subscribe Remove The First Character In The Last Character Online Aa Ki And Which Again Is Its Content Dhi 10 Sudhir When You Visit And Like Subscribe Problem Solved 12000 Will Check All Characters Of A And B Plus Dhund Character Live One And Baseless One Check the Group Repeated Group Pattern Effigy of Repeated Group Chief 's Hebei JBC Sudesh Blackness One Will Find Even 's Hebei JBC Sudesh Blackness One Will Find Even 's Hebei JBC Sudesh Blackness One Will Find Even Group and This Group Will Check Rapid Times by Adding This Place Here and Between Foreign So Which Ladies A String for This Is Recent Write-ups A String for This Is Recent Write-ups A String for This Is Recent Write-ups sex in subscribe To My Solve Channel thanks for watching | Repeated Substring Pattern | repeated-substring-pattern | Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters. | null | String,String Matching | Easy | 28,686 |
64 | in this video we'll be going over the bottom up matrix approach of minimum path sum so let's go over the thought process so let's convert the top down memorization approach to a bottom model approach now where do we start in the memorization approach we have cached the current row and column with the minimum path sum visual common sum this means we can create a 2d matrix min sum to keep track of the minimum path sum for all combinations of rc keep track of for all combinations of rc now it asks us what are the default values inside the min sum matrix when rc is at the bottom right corner this means we have no more paths to we um we cannot go forward to any uh we can't go rightward and we cannot go downward anymore so the value that's left will be the value at the cell the default value will be grid rc now let's go over the pseudocode so we're going to create a 2d matrix create 2d matrix min sum to extract the minimum sum or combination of rc then we're going to iterates through the indices from grid.length through the indices from grid.length through the indices from grid.length minus one to zero denoted as r will iterate through the rows now we gotta iterate through the columns red r down length minus one to zero denote it at c now if r and c is at the bottom right corner we're going to set min sum rc to grid rc because we cannot go in any more direction so it's just going to be the default value at the cell and we're going to continue the next iteration then if r is not at the last row this means we can go downward so before that we're going to say set min sum rc to a very large value so to integer that max value we'll be updating this as we go rightward or downward if r is not the last row this means we can go downward so when it updates the current minimum sum if the sum of going downward is smaller if min sum of going down where r plus one plus grid rc the current cell is smaller that fc is not at the last column that means we can go rightward so we're going to update the minimum sum if going rightward is smaller then we can return the minimum sum starting from 0 which is the initial starting position because we initially start from top left and then we're trying to go to the bottom right corner now let's go over the time space complexity the time complexity is mn where m n are the on the number of rows and columns this is for the nested for loop space complexity is also mn this is because of the sum matrix now let's go over the code so we're going to create our the row and column first m n now we're going to create our main sum matrix to keep track of the minimum sum path for all combinations of rc i'm going to iterate through the rows and then iterate through the columns then if we're chronic if we're currently at the bottom right corner then we only have the value at the cell target m minus one and c is equal to n minus one by the bottom right corner so min sum of r c will be just the value at the current cell then we're going to continue the next iteration now we're going to set a very large value at the current minimum path sum and update it as we go leftward uh as we go rightward or downward and if r is not equal to n minus one this means we can go downward so we're going to update the minimum sum if we can find a smallest i'm going down then if n if c is not in the last column that means we can go rightward so we're gonna so i'm gonna update the minimum sum if the minimum sum of going rightward is smaller then we can return the minimum sum starting from the top left corner let me know if any questions in the comment section below you | Minimum Path Sum | minimum-path-sum | Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100` | null | Array,Dynamic Programming,Matrix | Medium | 62,174,741,2067,2192 |
261 | hey everybody this is Larry this is me going to do an extra premium prom one that I haven't done before uh let's just keep it medium for now maybe I'll get an SQL question maybe not hopefully not all right today's live is actually premium is 261 graph Valley tree so you give it a graph of endnotes um and then you have Edge you have edges okay it's a is it a tree oh well you have the valid data as a tree okay huh I wanted to yeah so there are really only a couple of things you need to know I was looking for it in the prompt because I just assumed that there may be but the first thing is that uh for tree you know if so d uh let's just I'm going to use V right so e is equal to length of edges and then basically there's a tree then V is equal to e minus is it plus one of mine oh yeah plus one right if this is not true then you return first because you just I didn't have too many edges so you don't have two enough edges right and then the other way um it's just making sure that no psychos right um but you can also probably do it in a smarter way um let me see if I can think uh they're probably some pigeonhole thing that um I mean that two ways right uh or well yeah I mean you could do some psycho thing and we actually did some psycho checking thing I had a was it yesterday or the day before or maybe two days ago something like this one of the daddy poems but the other thing that you can do with the with finding the reverse of having a cycle um or if the graph has the is it new plus one oh no G minus one edges or V minus one edges but then that means that if there's a psycho damage that the graph is not connected so that's kind of yeah um so they all go hand to hand so I think you can also just do um I mean we could do it either way right so I told you two ways of doing one is finding a cycle and then the other I didn't actually say it out explicitly but it is to kind of do like a breakfast or a definite search or just like a connected component and then you should have one connected component and that should be good um but yeah but the reverse of that is that you actually don't even need to do that because as soon as you see a second connected component you're already um it's already false right so yeah okay so I'm going to convert this to an uh adjacency list first um right so classic adjacency list construction and then I'm just gonna do a breakfast search um yeah okay we just do zero right and then maybe uh visit it times that we all right it doesn't even have to be popular left it could be pop right but then it'll be that first search but iterative version doesn't really matter right foreign that is interesting because even though I said no um because there are ways to do it but you have to look at your parent okay fine right let's not visit it then was it true cute out of penry that's fine and then now we just go if any visited or if um if I said or so you can return with all of them are true and I think that would be a tree right maybe that's good I'll try to so this is just saying that if we visited every node then it's a tree if it's not then it's not a tree I think that's sufficient yep it went pretty fast too um yeah um I mean this is just when we're first search so you can expect this to be linear time uh and by linear time I mean read plus e but we also made sure that we is well you uh yeah V is equal to D plus one so it's just going to be so V plus d is just over B right so yeah so this is all the time of read space and that's all I have with this one for this premium problem uh sometimes if you want me to click on this I don't know if it helps there you go I don't know if I'm giving up whatever but anyway um that's all I have for today that's what I have for this premium problem uh let me know what you think stay good stay healthy to good mental health have a great rest of the week I'll see you later take care bye | Graph Valid Tree | graph-valid-tree | You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph.
Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\]
**Output:** true
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\]
**Output:** false
**Constraints:**
* `1 <= n <= 2000`
* `0 <= edges.length <= 5000`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* There are no self-loops or repeated edges. | Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.” | Depth-First Search,Breadth-First Search,Union Find,Graph | Medium | 207,323,871 |
1,461 | Hello friends welcome to the new video question number 1461 check if string content all one week mode of size will our spring always be of a record of size very interesting question this is a medium level question the category may be springs and we beat You can also say Manipulation, let's start the question, given in the district Hamirpur district, you are seeing this external screen has been given and one person has gone, okay now we have to solve it, this is a very interesting question and we have to use a little brain to work. The code is very simple, Bani Spring, it can be a very big rain, so you cannot convert it in the interior, it can be very big, this Bani Spring, I want to tell you that it has all the binary codes of good size. How to take two of k was a good binary code, what would be the trick that one could be of the store could be one of this could be so in this courtyard said that is in the four corners okay good if equal to If it has to be done, then tell us that all the records will be of three sizes, all the galleries of this committee are open, give this size, all our songs are recorded, then if there are three threads, then tell us that all these binary codes should be in this trick, then basically Mac. If I don't want to calculate all the binary codes, then I will have to keep track. So if I just find out what all the 22 sizes are I getting in a small string, then it is okay and later I will see that all four are not coming to me. So how will we apply this kind of logic? Now people know how many hours are recorded on two sides. This will tell everyone that the power of two for a tube of two sizes is four. Okay, okay, you know how bad the tubes of three sizes are. Because the power of three is 8, so there is no point in generating this binary code. We know that there are three sizes of art codes, so if I just process this stuffing, I will process my small stuffing and I will make 3 sizes. Okay, let's cut it, take out size 2003, take out size 0, only after that take out three sizes from one position, move forward by 06 positions, then move forward to 104 questions, 101 is 21. You see, I am the arrow, that is 10 repeats. And if we don't take this then the question is 10 more, then this is repeated, this one too, I got three-four, but the question was a got three-four, but the question was a got three-four, but the question was a question, the meaning was to tell that all the three sizes which are there, whether the art code is string in it. Not only in this film, there are only four cords of three sizes, so in order to make us return, the question has become simple that how many should be of three sizes in order to find out from the math formula, how many should be from 2 years and If we do the cutting of three sizes and it cuts out 22 sizes, then this question has not come to the sliding window by twisting that what was the sliding window incident that the sliding window incident happened, take out three sizes from 32. At the end of the day, you should check how many have come out in Akshay. For example, if two have come out around the size and are equal to two, then I will say that all four are getting the returns. I will go through this. Further questions on the sliding window. I have to tell you. That I would like to write a template, the setting will be closed that I think everyone knows the sliding window, it is a very basic concept, so this is my whole, I did my string SS, okay, what is my style for the sliding window, I take the account and what do I keep increasing an account so everyone may have a different method, my method is this then I hope that if the size of my window is as much as I want, for example, I want to raise the sides of three windows, then what will I do? When my window 7 will be female then I will come in this effects condition, this I will apply my logic and finally I will reduce one account inside this window so that in the next time again I am angry in it like it will become three then I If I wash it, then in this way I have written this template of the sliding window, it is a very simple template thing, you all must be familiar with it, so if I take out all the windows of three sizes each and I will finally check 36. 84398439 If this is the number then how will we do one that will be stored that I saw, I showed you that these were the codes that you saw, 100 was coming again so I do n't want repeated, we have to do this unit more, how many unique codes? If we are getting three sizes, then by listening we are getting to know that we are talking about a set because our unit is set and if it does, then to start with, we will take the responsibility of providing this to the handset. If this side is okay, then there are three sizes. We will start cutting from zero to three, then from one to 30. How to do it? If you know that three sizes of windows come in this condition, you have come to the window and got the first window, then what will you do if you put it in your handset, how will you put it? The trick is to cut the string, either I substring that string, okay, and one gives me a point, meaning where I start from, so I take it from the name, I start at zero, I am returning zero to three, okay. Then I and the subordinate cartoon, then I will cut two to three and I am saving all the Winery Gods of three sizes that are unique to me on the left side, so from Start to Start Plus, three sizes have been cut, okay, next time. Didn't it? Start by cutting from Gali and 058, give a big one too, then this cutting has become very simple in our hair set. Horses, do not do anything too much, we have saved it by cutting. Now what will you do if you have a tattoo. You should check that all the four keys in the handset are through, if yours is through then you will think that this is our set, will that code come in it our set, this is our set, will that code come in it because there are 367, that is the logic, if it were more then it would be what we have. That is the binary code, its length of four and five and how many will they stand, so if you see, I think we will leave 16, so we will check that 1616 code has come to us, it has not come, how will we check, so do not generate all the quotes 16, we have If you had processed your string toe then note down the size of your penis because add naina any extra duplicate store is not spoiled its own property next time if a duplicate comes then it will not do the story this is the asset's own property this note is duplicate cold This unit does not take the implicit and does nothing. But the alarm is on the side of the set. How much should it be? I would like to use the function of a match. I want K to the power of two, so it means if my K is two then it is fine. If my size is set up then it should be three, then its flour should go to Advani records. If its size is for, then I should have 16 codes. So that's it, I have stored all my planets in the set, this is cut. If the size was free then I would just get four. Actually I should have 8 so I will do the return forms. So if I return some here and there that if this size is found to be equal then the return will be verified. If it is not found then I will return it. Here the form will come, hit this shot and after deleting all these, try it, just this little trick had to be applied, the question was very easy, not many people found it difficult, let's see once, it is accepted, let's see after submitting. This bit was due to manipulation. You can insult this train. Some mistake has been made. You will have to check once that this is a bit. You have made a mistake. You have used the wrong function of the power of two. Because if we have power to generate, then we will have a Let's run it again and this time we see that it is being accepted and after submitting, we check that it is being submitted. You can see that we have solved this question in a very simple way. See you later, Elite. Thank you very much for watching this video in question. You can subscribe this channel. Thank you very much. | Check If a String Contains All Binary Codes of Size K | count-all-valid-pickup-and-delivery-options | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
**Example 1:**
**Input:** s = "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
**Example 2:**
**Input:** s = "0110 ", k = 1
**Output:** true
**Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring.
**Example 3:**
**Input:** s = "0110 ", k = 2
**Output:** false
**Explanation:** The binary code "00 " is of length 2 and does not exist in the array.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s[i]` is either `'0'` or `'1'`.
* `1 <= k <= 20` | Use the permutation and combination theory to add one (P, D) pair each time until n pairs. | Math,Dynamic Programming,Combinatorics | Hard | null |
18 | Hello everyone welcome back to Shahnawaz Malik going to write July 4th inch the problem is 400 so this is too much problem the interviewer goes then the problem is that we will have an area in the input and we have a target value on us and union quarter. Four elements are needed to extract it. Okay, double Singh on this and 41 - 2 - 121. 41 - 2 - 121. 41 - 2 - 121. Okay, so tell us to print all that potter full which is this name in your name, President, time of day, target and answer. You can put any that this There is no problem in keeping it first and you will write one point here ABCD R District is ok so now Muslim is A B C D O L And please this is simple, at least what is coming in our mind is that what we need basically, we need whatever our norms are, it is okay plus norms of 6, which plus numbers of whatever we think, play it and plus norms. Of value, what should this be ours? Equal to equal to should be the target, that is, if I do it from here to here, it is okay, then after that, jail, this is from plus one to a and minus two because there should be queer elements, then maximum. From here to here, if this is ours, then this can be our moist, so if we do something to the elements in it, then here is a big one which has all our elements, so this pick will be very group controlled, it will work fine. Its complexity is some off n rate, four cloves are appearing till next A to Z, which we reduce, how do we wander, look at the I and as if we have clicked on the I and see, then we could have bought it from here. Basically what we will do is that now why is our target given the increase in the market time so what we have to do is the target given to us is zero okay what will we do first we give it to us because first of all it is - - 01 first of all it is - - 01 first of all it is - - 01 then after this we have to As decided, we will mix I and I. Okay, because to remove the wish element, the song target of all the elements lying on 449 is exactly Noida sector. So let's do it - and our I sector. So let's do it - and our I sector. So let's do it - and our I Plus. Minus minus so give this that we have taken what we have then come here in Marathi and whatever is here is okay now we have to take the medal we have to take two points that one will be ours one will be our right I complain and now what happened Look, why is our target, we have given this, if we have taken this element and from this, we need 100 - - 2 we need 100 - - 2 we need 100 - - 2 A very low and we need no, that is, whoever else has studied for us, their number should be less. A how to make mind karna i.e. if friend of karna i.e. if friend of karna i.e. if friend of lemon my tab page 24 pada they here we see if he is in front of us total targets - i hai hua hai targets - i hai hua hai targets - i hai hua hai na plus name possession which we have taken out that if that this give its quora If we do not take it at this time, then it means that if this scene happens, if this happens that this is the value of this saree, our slogan is that with this, we can increase the need to increase the value of this child. So what do we do if it's plus so that it's a and what if it's big means if it's all money increased then we decrease the high because it should be low so that it's down so if that will give us and if make great. Let's work tomorrow morning, this is fine after seeing the triangle, so why stop it once in a week after seeing the triangle properly? So, first of all, our I is fine here and this is fine for us here, what have you done? Kiya - Two minus one, you done? Kiya - Two minus one, you done? Kiya - Two minus one, how much has this become of communism - Meaning, how much has this become of communism - Meaning, how much has this become of communism - Meaning, how much has we got and how much do we need, now total target and you - If we have got, how much do we need, now total target and you - If we have got, how much do we need, now total target and you - If we have got, how much is this, that is, it should be not only and only, then what will we do now, we are here But now take this to-do list come here now look here on the chest of the album we have here so if the previous ones are that a vine is lively and successful number 1 to 13 is 8 - two minor is 8 - two minor is 8 - two minor is this lineage and two that this At your place, now ours will be finished and now what will happen to us, I pasted this, I am only two, so what will happen after that, we will take more here and then we will check, more here, we will take more here and then we will check, okay, now what is our zero minor here? Will be - 250 - - Here the opposition of plus and minus two Will be - 250 - - Here the opposition of plus and minus two is Vivo and in 2018 Journey to Okay so this one point to this matter - 2019 this matter - 2019 this matter - 2019 Okay now after that there is Kaya so here LG will be gonna be the one just on These pimples are their own judge here on the first sure issue, we have done it for that, so we can use this, okay, so here we go e-mail - broken, okay, now our here, now e-mail - broken, okay, now our here, now e-mail - broken, okay, now our here, now our This and here this is our today so come to our here this became our I and here today here is okay I love you and here is lo and here is okay so for this I used to check here that Joe who explains my total - I minus Joe who explains my total - I minus Joe who explains my total - I minus plus was decided - - and here plus two plus was decided - - and here plus two plus was decided - - and here plus two today we will do papayas will go behind 29 plums on the tables and here are two apk file su here on this camera watch so If this will adopt us more then it is ours or two then this expert pro has come or will go first, what are you doing that first of all make us soft one because we are inside so for two points we need one two then what have we done, we have one For Roop Laga Aayi, from lions to - till, for Aayi, from lions to - till, for Aayi, from lions to - till, for this project, from I Plus One to - Sutak and then we have taken a loan, we have taken a - Sutak and then we have taken a loan, we have taken a - Sutak and then we have taken a loan, we have taken a high loan of - 110 total size and high loan of - 110 total size and high loan of - 110 total size and we continued till the balance check is mobile and our Let's see what condition will sleep, there is a condition that our we will say saawariya here which will be our targets we - targets we - targets we - phone numbers of synonyms of i a plus name subject is ok that this is our target - number five plus one that this is our target - number five plus one that this is our target - number five plus one do if our The number of plus our name comes and if this does not mean that it is supported first of all okay, after that there is an answer and drains broken vector because we have to return the distance in our output in the question okay Is Victor Orbit and then after that we will take a big force N in which we will apply the norms of subscript again like we did - - 2 like we did - - 2 like we did - - 2 and if this is I many times and number five - 1234 so here we have this for this so let's go here. We see here we were here because we were here in the first one, so for this we are here and then we will find out the targets which is dead target minor number nine plus we find this of vegetables we find tuition. Jackson and management for and till add what do we file if we face college is 123 number of birth number affects teaser absolutely then make a person and do something in the answer so if this is this a 112 school Ne toe act - if we here 112 school Ne toe act - if we here 112 school Ne toe act - if we here we 243 if we here two that if for act from but number at - act from but number at - act from but number at - ventricular so again because we check that one in two then this product last Find the answer and submit if it was accepted then tell it clearly to the senior roots team, I have kept it in the description and if there is any doubt then do tell about some improvement and if you like and subscribe the video and in the next video In | 4Sum | 4sum | Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,0,-1,0,-2,2\], target = 0
**Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\]
**Example 2:**
**Input:** nums = \[2,2,2,2,2\], target = 8
**Output:** \[\[2,2,2,2\]\]
**Constraints:**
* `1 <= nums.length <= 200`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109` | null | Array,Two Pointers,Sorting | Medium | 1,15,454,2122 |
95 | Hello hello viewers welcome to my video famous and problem school boys subscribe sorry man manager this channel subscribe 125 gram saunf 125 volume subscribe and love you to quality sub bane Dish well broken left style witch fun unemployed right chal utar always dresses for all the best games for kids us this side - shashi left is always games for kids us this side - shashi left is always games for kids us this side - shashi left is always a small earthen root is always smile every day right only business in binary search tree na Forget One's Route OK Net's Network Problem Replace and Nazar Route to Play List Play 120 Channel Radhe-Radhe Video Want to Avoid 120 Channel Radhe-Radhe Video Want to Avoid 120 Channel Radhe-Radhe Video Want to Avoid You Too Two That They Will Give You Can One Be Pledged to Right Side Note Channel Beat It Will Electronic One Will Replace Share Holding A 119 Less Possible 3712 Possible Princess 1512 Must Votes For Any One To The Answer Is Gold Channel Subscribe To Bell Channel For Latest Updates Number 123 That NSA Quantum 3 A Mythical 12181 Case Record Broken Dance Class for Too Toot 9th in Cars Number One Two Three Two Children Who Will Not Attend Event Will Just Being Equal to the Number of Waste Two Best Possible Way That Penetrates to Use Two and Three and to Make a - and to Make a - and to Make a - Acid So let's you listen two subscribe number Sid 10 to 12 A two three one two three Shimel same pattern also same number of trees will be from Bigg Boss 182 and oil increase model 2ND YEAR ALSO INCREASING ORDER FOR EVEN TRIED FOR BINARY SEARCH TREE WITH 5 6 AND YOU WILL GET ASIMUM CASES WILL GET THE SAME CASES BUT YOU WILL ONLY HAVE TWO TREES HERE 56 LIKES OK IS ZULUTRED 10 INCHES SURYA IS I WANT TO FIND THE NUMBER OF The Best Place For Binary Search Tree With Two Three Do Subscribe To The Benefits Of Trees Kundli Mein 213 Parole Unbreakable Responsibility Sudhir Worst Case Advocacy Up To Take One Swaroop Note And Where To Find Answer Soen Amir They Ok Water Use To Cash Is YouTube One Should Not Limited To Lord Bless You Take Like This Okay What Is The Like This Thank You To Subscribe To First Letter D Soap Vancouver Starting With Vansh At That Time Starting With The Ones Who Not Only Desire To Tree Services Song Features And This Toot Receiver Answer Is Suggested Tourists And 123 20223 Se Them To Trees Have Shown In This Particular K Dancer School Love For Starting International To WhatsApp On Answer Drawing And Tried To Find The Answer Will Again Tried To Find The Answer Clear Starting Me Root To OK You Have You Can Place Children He Earth Water Possible Valley School Children At You All I Want To Three Avoid You To Face Rubaru Ka News Only One Minister Lover Can Replace Descendants The Ones Who Ordered Into Someone Will Give The left side this great and truth click on the right hand kudiya total gift directly without even looking at dance without even drawing history s how to fix redundant format note family values of less than note family values of less than note family values of less than 272 corresponding root note value added to validate or 125 values into 125 values into 125 values into Great Values To Take Into The Right Side That's Idly Much Clear That 24 Answer Is One Okay Knowledge Tattoo For The Tree With Root Notification Okay It's The First Tried To Find Out The Answer Without Driving Cars And Virvan Subscribe And Roots Rotting Hormone Research Number Three Use Number 123 Number To My Channel Must Subscribe A Minor Research Tree With Two Women In Various Avatars Taken For Looking For Answer For Any One To The Answer Restaurant Serves 2.5 2.5 2.5 Idea Of Small 1382 Venice Model Residential Building In The Way Consider Vidra Number One with September 2012 and 2013 Luta Do Subscribe Must Have Good Luck Verify Tower Answer Is Correct Answers Do Barauli Two Possible Children For This Particular Kids So If What Is The Total Answers Were Look At All The Cancer Skin All The K Swift Total Answer Will Be the sum of birth freelancers foreign equity dancer two plus oneplus 5 wickets one saree with one young two minor sisters starting 2019 research t-20 opposite when loot 2019 research t-20 opposite when loot 2019 research t-20 opposite when loot playlist downloads just society took root 1512 vibrations it two three lines and here this free leg him Starting With Roots 2513 Possible One Liquid Liner With Sri Lanka 324 325 323 354 A Foreign Country Answer This Point Is Requested To Answer Object For Any School Dance For Any Total 2012 Then Answer Ladies Considers Want Bigg Boss Any Time You Can Not For May Fuel Free Rate for Example Will Suggest Non-interference Video Non-interference Video Non-interference Video Trying to Form with Great Care During One Too Bust Economy No Possibility to Find Answers Where Multiplying So Finally First Readers Can Be Formed with Absolute Value Crystal Stone War Right Hand Side Crossroads Zill Get Answers You But You May Live Without You Will Get The Answers To All You Want To Give The Answers In This Place Has To Write Secure Puranic 120 Limited Service 130 Subscribe To Find Answers For Any One To 4 Inch Right To Find Answer Co Request Phool Lakshmi Don't Thing Video Modern Mythical 124 A I Just Change Of Cases Will Know I Tried To Build Up Without Drawing For Any Good For Water Possibilities Rate Admin Quite Different From You Can Take One Arjun And 2013 Near Sure Up For Facebook Today Was Sure What Will Happen If It A virus is needed all you can see the remaining element ok must subscribe and but from left side grade one to three four will be right side are using two three and four ok and using any three elements in ascending order how many - elements in ascending order how many - elements in ascending order how many - 2G scam solid waste In the case for any questions and answers paint and left side active tips hair zero two answer is vansh villain smile reply this to validate your way 200 for any 120 the answer is not for any questions and answers 50 fiber and research scholar definitely super this Is The Answer Is Pipe Let Me Resist And Latest Not The Answer For This Specific 500 Index Case Your Answer Is File Latest On Next K Latest And Industries Answer Latest And Finally Bigg Boss Two Three Four One Two Three Four you can place two numbers in ascending order in Andar is set for any country to the answer is 2012 transfer into its significance and answer is to jai hind is particular kisan sirf the latest no clear right answer and let's move to the next session on ka nishan service to latest and discuss the issues with starting note water possibilities for electronic burden small Hey 322 Notes For This Bigger Than Three Inch Plus Courier So That Twitter Only Possible Cases For Anybody To Answer School For Any One To One Answers Work Towards The Problems Of Clan Service To Pimple 121 Select Residential Projects' School Was The Last Tubeless Force Group Lord Witch Can't Have Any Right To Life Can't Have Any Right Brothers Who Will Get And Food Water Every Citizen For One To Three For Any Questions and Answers Pair Equal to Zero Answer is One OK Safed 2150 Answers English Particular Question What is Airport Alarm Sir Total Answers for any query then portal number 42 year old can form issukti wali file fiber 510 subscribe francisco ki electronic ko turn on hai hello friends particular case me to declare and distribute to the distributor on 2015 specific builder solution from any one to one rank one to in Cars And John David Axelrod Electronics And What Is The What Will Be The Best Possible Way Is So Someone Want You Can Also Get More Difficult To Give To Answer Base Teenager Asian Shot Building Time A Latest So English Particular Case Play List Start From Iodine Eye Lens Icon 285 Plus Person Absolutely Three To The Giver Number Piss Example For More Latest Changing Toward The Co Fold Pet Mitthu Malik Let Me Service To The Old Is Gold With Little Bit More Comfortable And 1000 E 17 Points IF One Dose Free Oil Daily Stay i plus latest 1950 vitamin 120 and for its political activist and tenth and finally I will make the lava the current person doctor appointment subscribe j210f example2 definitely 2018 - definitely 2018 - definitely 2018 - definitely family to family possible how to find the number of This is possible you can just look at how 19 number is smaller than what do you mean in numbers for smaller Radhe-Radhe-Radhe-Radhe Gyan Find out the opposite word three rate instead of one form number smaller than two numbers enjoy certificate this face number se smaller and smaller These size phone numbers are four this week they found number se small argument and no small argument and 1298 why number smaller in size minus one should find number of smaller than just look at minus one so you can get it click subscribe button on left side Pacific World You okay let's you or e should attend and currently you rot this poem to find out how you can please write for laptop for demo reel person place for the laptop the liquid values will be the laptop values will be the laptop values will be the laptop total revenue and values in children values in children values in children a Three four one two three four one two root 66 values from two 66 values from two 66 values from two 9 plus fri right side officer rude all is well as every place under right side of and posting this will right and left the words in conflict where gods in the day for recruitment of One to Three Solid State and Switch to Left Baroda Balance What Were Right BST Right The number of units of trees that you can form from the right side of Minimal Devi Services and that is the number of seats will look at this table is minor on The issue of - manner what is the issue of - manner what is the issue of - manner what is the english as well as for rent i10 - the security answer is i10 - the security answer is i10 - the security answer is 1000 vs 110 - 460 switch on the tree again play 110 - 460 switch on the tree again play 110 - 460 switch on the tree again play list 60 tubelight for winters 6 are listed on and because normal start i ignore find the Number of Units There Left OK Calculate the Number of District Road Teller Very Much and UI - Select - But Road Teller Very Much and UI - Select - But Road Teller Very Much and UI - Select - But When You Want in Simple Way Also IT Manager Will Give Answer to 20 Semi Left BST Third Indication Will Be Reduced to Avoid Any Content Code Simple REDUCED RATE LOGIC TO EDIT IS IMPORTANT TO BE UPDATED FRIDAY TO WHAT WILL BE AND ANSWER THIS ANSWER WILL BE TIME TUBEWELL ALSO NUMBERS AND BENEFITS YEARS INFORM THEM ON THE LEFT SIDE AND IF YOU LOVE TO Multiply Principle TOTAL PERMISSION FINALLY IN YOUR DUTY TO OFFER YOU Can start michelle janson thursday ok pure problem stress problems your give - but your give - but your give - but request change the rude so dravya smaller than ji victory minus one and tested os white and latest friends that church and ki net speed ki formation | Unique Binary Search Trees II | unique-binary-search-trees-ii | Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 8` | null | Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree | Medium | 96,241 |
520 | Hello everyone and welcome back again recording, this time our today's question is detect capital, so what we have to do is we will find a string in it and we have to detect that it is capital. If we understand these three conditions, then first of all we have to find out if all the letters are there. We will get the word, all its characters, whatever the string is, we will get all its characters, capital also, two have to be returned as true, if all of them become small then we have to return true or else or what should happen, the first letter should be capital all in over case. Either the first character is left, the first character can be either capital or both and the last character and all subsequent ones are small. Right has to be returned in all three conditions. True has to be returned in all the rest. So look like this. Now make me all the captains in it. Now about this, F is fine, it is capital LA, it is small but this G has become capital G, it should not be capital, so only the first one is sorry that you can be anything, both of them are small capital. You can, but all the next ones should be small. The app has become capital. Either way, all should be capital. In this condition, what can I do here, so I can simply check it and I will give all of them. Brother, you check the second condition. What is the second condition? This is the second condition that has to be checked, whether the lip is all small or not, otherwise all the small ones can be handled in such a way that we will not check the first character. First of all, there is an option either it will be small or So the capital will be direct, we will not check the first one, we will not check the next one left from here onwards, we will not check the zero one, we will check all the characters from van till its length, as per the length and in all of them, if all the characters are If all are small, then this case should also become true. This one should also become true. Right, we will not have to put these two in separate cases, so we will become them with one dream, so follow it up completely. If you hold on to the strong, what about all of them? There is a capital end, you give me respect, you get to check the second condition, what will we put in the second condition, we will not check the first character, we will start checking from the next character and all the days till the end, you will give me the center of the lover, there is immense gas. So we will give useless correct Then we will have to come out with the next one Will go till where one will keep growing Only then keep checking Whenever I will get a lover case But the case is done But there is a case to come. Whatever cases will be found in the future, I will say no. If I don't have the answer then I will put the character here and give a group here. I can put note or directly give the lower case group. Whenever I get the lower case, I will directly break it. I will break it in the condition if this condition ever occurs. If there is no break, where will we reach? We will reach the end of the length. While checking till here, we checked one too. We were going to check ahead of that, so we stopped in the for loop, so what will we do? We will check if my This means that the value of has been reached, this is what we will return in all the Apar cases. Now let us understand this condition that what have I done, do something here, is it capital and have we also checked the end one, then there is no There is no problem that the value of Eye must have been what time would it have been. Somewhere in the middle, it must have become small. Look, the character has placed it on the note of inferior, the stomach means it will be small. Somewhere in the middle, we will break it, meaning Eye is ours till here. Will not be able to reach. If you reach the end then it is correct. Return all the truths. There is a condition in between. I will repeat. You can come out and repeat the whole thing. I came here late and wrote here again. From I had made A, somewhere in the middle, I got immense case, I will get immense case anywhere, I will break, I have broken, I have come, I will not reach my length, if I have not reached the length, then what will we have to do, we have to return false, I have reached So I can do this directly: Greater Return Reduce this Han Submit for Artist Cases It is capital In this, when I will be all capital, it is not all capital, all of them will be small, except the first one, all the others will be small Correct For that, I have not even checked the first one, I have only two options, either it is capital, it will be small, then what should I do, all the rest should be small, leave the first one, let's leave the first one, left zero, started from van till N. I went wherever I would find you, when I found someone in the beginning itself, I will find all the capital letters, then I will break, after breaking, I will come here, then I will check if I is equal to my word, means it has reached the end, now that All the capitals must have been there only then you have reached or not, what does it mean that somewhere a capital A has broken you, if it has broken then this fast data will be in the condition correct then thank you for watching this video and c. Will Make It Into It | 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 |
1,047 | Hello friends, welcome to the new video, question number 1047, remove all duplicates in all exams in spring, this is an easy level question, this is a tech question, this is a classic example of how to use the steps, part to be adjusted in part 2 of this question, we do There was a little question before but it is very easy and if you want to learn the steps then you will not get a better question than this. Let's start with the question which says that if any of the adjustment characters come together, any two characters come together. If it is found then it has to be deleted but after deleting if it gets added then it has to be deleted again. Once you understand how to tap then it will be done well. I would like to take two test cases and clearly know that the stock If you have to use it without any step, it will be very complicated, so what have we taken, first, we have taken the string, we will learn how to feel in the attack, how to delete, and this induction is nothing, this is basically the rear index of ours and this is what the stringers did in the first test case. If an f5 is going intact then you will process this trick as a text like there will be a step or behind the stand you will see that there is no element which looks the same so you will add in the check then you will also process. You will see behind that no element is like the middle, it is not visible in the state, it is okay or even if the stock is empty then put it or you can see the element which is not like grease, then also put it till you come. On the index, yes, in our rager stock also, there is an element of exact copy which is just behind, okay, so what will we do now, we will not insert it, this time we will pour it, we will delete it from this tax, we will delete it, you see, now I am induction. But I am thinking about how far behind should I do the stock Omex, then this is the advantage of this type, I am maintaining it in the strike, but did you check before putting it on the record index Sharif, is it not behind in the stock, because if If it is behind then we will delete it, okay then we have deleted it, now okay, now you came to the seat, you looked at the back, put ghee, then before putting it, you looked to see if this is not in stock somewhere at the back, if it is not there, then okay. I have put one, if this was the case then we would have kept deleting it, otherwise how is the addition happening, see once in which way it is getting deleted, delete has to be done in the same manner, keep going with the trick, even if two are visible, do the talent, then this If you delete the two that are joined together, then CA is left, so we have to delete it in this manner. We have to keep looking behind the skin as well. We have to look at this loop that we will run. In this, we keep moving forward. We will leave 10 to see that there was someone behind. But what will the tech do, this one of ours is working, it will text that two have been deleted, now the people behind are also accessing, together they are connected, delete them, so this one has to do the relation, friends, will he be able to do that a string toe aa It is said that you are increasing, no one is behind us, we do not know what is the record, what is not, to delete it and what is being created, then the work will be done only with this tax, it makes it very easy, you will not use the text, it will be printed at the bottom, it will be easy question. This is a very classic example. This track is asked at many places. Let's start with the second example. Let's write down how many indexes are there in it. Ok, we are going till the index. Now let's start the measurement. Is it a step or is there some other element behind it? If it is not the same then add it because the element behind it is not hashtag MP but the element behind it is also not the same then add it. Now before adding it, if you saw that the good was in stock also then add it in your pot. You came to induction, you checked before inserting it, asked if it was not there, then inserted it, you applied it, then you came to the index for, you saw that there is no element behind before inserting this thing. There is an exception to both of them, we put it in it, either it is okay, then after that we got it done and saw the same Wind Pipe. Before inserting it, we saw what is behind it is the same, we did not see it in the same way, if you do not see it, then it is not behind or Then its Shimla element is not visible, what will we do, we will just put C, we have put it ok because it was behind, then we have put K which was behind, so do this child code to delete it in the last, very simple code. Make a track, give a name to the fat, handle it with a character, where is my tab, the name is ok, we have created a new stock, what did you say, this trick has to be processed completely, let's do it, put a loop, extend it is simple, ok This trick is Capital, this is Selenth, this is our trick, we have to process it, we told 2 A gas, look at the back, if you see the element, then what will you do, track it, what do you do behind the test, look at the element, take out something, just take a pick and see, drink it. What will we do after seeing the las element? Okay, this is the last element, that is, if we pick it before inserting it, then it is told that if the last element is equal to the one that our John processes the current element, then it means that we have got the last element, okay. If it is equal to whether we will put it in it or not, then it is simple, I told you that in this case, top this track and whatever is in place of the other one, it is fine, that means it is not equal to the previous limit, so we have to add it in the tag, that's all we have to do. There is nothing else, just add whatever element will be there at that time. There is one more thing left in this that before getting it checked in the tech, it will go somewhere like Campty etc., then you should check once that this etc., then you should check once that this etc., then you should check once that this rate should not be MT. Anti will check if this note is not done, impose a fine on this chapter note, take note is MT only then you will chat with it about the next condition, it is ok, return type spring said, what did we do, this is what we did If it is inside this track, then this is C. This is a small step, we will have to convert it into some trick, the main work is done, we have written the mail, create a string builder, okay, just create a new range builder because it is a statement element. Okay, you know, now if I remove CA from the stock, the lot element comes out first, then it will come out as effective property or mine will come out, then instead of CA, my answer will be AC. Tag, this does a lot of track. It is a good application that the spring should be reversed, put it in, take it out, it will go reverse, okay, we will reverse it later because we have come out like this, but the answer is that we should reverse it, okay, so let's do it quickly, empty this type, how? Will you come down and do one thing that is viral of ours, which is this stake, till it is not empty, keep extracting limits from it, empty it, okay, and till it is not empty, it was created by your Singh Bhinder, Stringbuilder Singh. There is no difference in that reminder, I created it for performance and it is a very good feature, for this purpose I will tell you what I did, we took it out of the step and put it in the stringbuilder. When it ends, the track will become empty, so instead of this, our AC is stored. Let's go in it, okay, it has been restored, what will you do, Tinder was created because there is a property, Singh Mr. Gaya, now we will also return but we do n't want to return like this, we are returning it in reverse, so Stringbuilder does it very well. It will automatically reverse and do the research. That's it, the work is done. Finally, convert it into year and it will go deep, otherwise the resident of the string is not a string builder. The builder was created because we wanted to use this function so that we could delete all this by hitting a shot. Let's do this and once we run it, some compiler will come and we will see that it is a very simple question, the spelling of some random characters is wrong, how to put it, then compile it once, write any good code, let a computer accept it. Okay, let's submit and see, there is a problem, we have fixed it, we have submitted the compiler and eclipse, it is a simple question, it is a very simple question, no, there is no difficulty, you can also ask more questions, you can see all the videos I have made. Here is the list that you can do part-2 of it, its list that you can do part-2 of it, its list that you can do part-2 of it, its link is in the description. Thank you very much for watching this video. Thank you very much. | Remove All Adjacent Duplicates In String | maximize-sum-of-array-after-k-negations | You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.
**Example 1:**
**Input:** s = "abbaca "
**Output:** "ca "
**Explanation:**
For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ".
**Example 2:**
**Input:** s = "azxxzy "
**Output:** "ay "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters. | null | Array,Greedy,Sorting | Easy | 2204 |
413 | um hello friends today less of their arithmetic slices problem this problem is further comparison with their there is much thicker slices to problem so let's first solve this one lesson statement a sequence of numbers called arithmetic if it consists of at least three elements and if the distance between any two could see conservative elements is the same so in this problem all the numbers for the because you ative conceive like this one two three is one arithmetical slices and the two three four is one i want to surface one arithmetic so internal industry is problem if one if two four six eight ten in this example 2 6 10 is not arithmetical slightly because they must be considered conservative a continuous so this is my simple we just use the dynamic programming idea to solve this question we want to capture previous the total number of the arithmetic slices if there are at least three numbers there arithmetica slices if not we just clear the temporary culture to 0 if there they are the arithmetic slices we will increment to this a temporary couch at the same time we will add the color to the result so let's the saw it first so we needed the total result which even a total cut of the arithmetica slices it was only a temporary cut 0 so for we start from 2 because we elisany the three numbers are less than $1 three numbers are less than $1 three numbers are less than $1 I plus so if I say I - a I minus I plus so if I say I - a I minus I plus so if I say I - a I minus one equal to a I minus one minus a I - one equal to a I minus one minus a I - one equal to a I minus one minus a I - to their culture increment by one and their cemetery result will add the zerk out and the in other case we just a clear the current account to zero because the they are zero right so final general returns is the result okay thank you for watching see you next question | Arithmetic Slices | arithmetic-slices | An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences.
Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 3
**Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 5000`
* `-1000 <= nums[i] <= 1000` | null | Array,Dynamic Programming | Medium | 446,1752 |
489 | in this video we're going to take a look at a lego problem called robot room cleaner so you're given so you're controlling a robot that is located somewhere in the room is modeled as an m times n binary grid where uh zero represents a wall and then one represents an empty slot so a robot starts a unknown location in the route that is guaranteed to be empty and you do not have access to the grid but you can move the robot using the given api robots so you can see on the right there is this interface right here right so you can see that we can move we can turn left we can turn right and each turn is 90 degree and we can also clean a particular cell right which is the current cell right if we call this clean function it will only clean the current cell so you can see here we are we can be able to use the robot using the given api so your task is to use the robot to clean the entire room clean every empty cell in the room the robot will with the four given apis can move forward turn left turn right each turn is 90 degrees so when the robot tries to move into a wall right a wall cell its bumper sensor detects the obstacle so it will stays on the current cell so basically what it means is that like this is our robot right so what happened is that let's say there is an obstacle here and this robot is trying to enter this cell right if it goes straight forward basically what happens that it will stay at the current cell not move because it has a sensor if we try to force the robot to go forward because there is a obstacle the robot stays okay so this is basically the core logic there and then you can see here uh design it algorithm to clean the entire room using the following api right we'll talk about this and then you can see here um this is our input right so basically you can see this is our little robot and then we're trying to clean a room you can see this is our grid but this grid is unknown to us right so you can see in our clean room function the robot right is only given we don't give the grid we do not know the grid so what we do is that you can see here we can take this robot right and we can try to do some maybe dfs back tracking right try to explore or basically try to explore each and every single corner of our grid right so you can see this is our little robot so we go up so maybe we can try to clean the current position right and then we go up we clean it and then we try to explore do a dfs try to clean this maybe once the robot hits a wall right and that will be we can try to do a dfs in other corners right but in this case let's say if there's a situation where you know if we keep traversing right if we keep traversing eventually we will end up in a dead corner right like this so what we do is that we have to do some backtracking right just like any other backtracking questions we did uh in this case you can see the robot cannot go left cannot go straight cannot go right or sorry it cannot go right yes in this case this is the right and this is the left and this is down right so in this case robot cannot go so what we do is we have to backtrack to the previous right to the previous position we try to explore all the options in this case we come from here right and then what we can do is that maybe we can go right okay so after we visit this we know that all four directions are visited so in this case what we do is we go backtracking right we backtrack to the original this position we know that we explore all the options right here we all explored it so what we do is we come back to this location right so in this case what we do is at this position we know that we visit here we this is out of bound this is already visited so we explore all the options and then we can just you know go to here right so this is basically how we solve the problem it's basically we're going to use backtracking and we're also going to cache the um the visited places right so in this case you can see the grid is now given to us how do we cache this well we can say is that at the robot position we can just set the current position as zero right so just like a grid right we're at the center right where the center um a couple videos ago i did a video called robot circle bounded or something basically what we can do is that we can basically set the current robot position as zero right so zero uh in the x axis and then zero in the y axis or in this case doesn't really matter how you say it basically we can say that the current robot is at the dead center right this side is you know we have four uh sides right we have the top left top right the bottom right bottom left right and then as well as all a directions right so you can see here what we can do is that we can say this is the robot right we can cache the result like let's say this is the grid right we don't know where we are but we can say that the current robot position is zero right we can say that and then what we can do is we can cache that maybe you can kind of like use a set right and how do we cache this what we can do is we can use a pair right or we can use string we can basically add a zero here right zero is an integer number and then plus the empty string plus a zero this will convert it into a entire string right or you can use a string builder there's many ways you can format uh converting this um coordinate to a string and then we what we can do is that we can basically start here and what we can do so we can do a dfs we traverse all four directions right we traversing this we go we do a dfs down this path right and then once we traverse all the options right maybe we can traverse all the options and then come back and then something like this and then come back after we come back what we can do is that because since we already visit a lot of places what we can do is that maybe we can uh try to go for another direction maybe we can go to right and then we when we go to right you can see this place is already visited so in this case we exhaust this option already so we backtrack right so we backtrack to this position and then what we do is that we can go try to go down we know that if we go down we already visit this position right and then maybe we can try to go left or something like that right so the goal is we wanted to dfs all four directions right and then for each path we go down to right we want to make sure we backtrack and then try to explore other options right so it's pretty simple dfs questions um and then i'm going to show you look at the code so inside the code basically this is what i did so i put a set a hash set that keeps track of all the visited coordinates right all the visited coordinates that we have visited we want to make sure to add it onto our hash set and we also have a 2d array that represents the directions right you can see we all have all four directions we have up right this is up we have right we also have down we also have left right so basically you can see here we have all four directions um and then you can see here so the reason why we do it this way right because you can see what we're gonna do is that what we dfs let's say we're let's say we have like all four directions right so you can see we have all four directions this is the robot it stays here first we go to the up right and then once we traverse all the path that we can explore if we go up then when we backtrack to the original position which is here we also have to rotate ourselves 90 degrees to the right and explore all the options on the right side and then we come back to the original position and then we go rotate one to the right in this case you can see we're going down reporting down and then we explore all the options in the downside and then we rotate 90 degrees we explore all the options for the left right so you can see that's the why that's why we position it this way which i'm going to show you why or in detail so you can see here i'm good i have this clean room function it takes a robot but call this dfs function takes four variables uh and then you can see this is the robot this is the column right sorry this is the row this is the column this is the robot and this is the arrow basically means that where is the robot currently pointing at right is it pointing up is it pointing right is it pointing down is it pointing left right so in this case first what we do is we take the coordinate that we have we convert into a string we check to see if that can if that coordinate contains in our hash set if it does right if it does already contain that we can just backtrack right because we don't want to explore or visit uh already visited coordinate right but if it's not visited then what we have to do is we add the key onto the visited hash set we clean the current position and then what we do is we iterate four times the reason why we iterate four times because currently our robot is pointing at the current direction right which is the arrow right so what we do is that we say uh we're trying to go straight like let's try to go straight robot.move like let's try to go straight robot.move like let's try to go straight robot.move right this robot.move returns a boolean right this robot.move returns a boolean right this robot.move returns a boolean function if it's true that means that we can still go that we can that means that we can go straight if it returns false that means that we're staying at the same cell because there could there is a obstacle that prevents us to go straight so what we do is if we can be able to go straight we get the current direction right and you can see the directions is basically arrow so in this case the initially the arrow zero right so in this case basically means that it the zero reference to the index of the directions array so you can see the direction array index zero is up right in this case we're going up the arrow starting right is pointing up right so you can see the arrow starting is pointing up so that's why you can see here we go up first and then we do a dfs right down the up path and then what we do is we change the direction we turn the robot to the right 90 degrees clockwise and then the key part for the modulo here is this right so let me show you something so in this case i have my on my uh console right so let's say we have zero modulo of four we have zero right so let's say we have index or the direction is zero modulo four is zero what about one modulo four it's one right what about two modulus four is two right three in this case is you know three but if i have four um you can see that it's zero it's starting back it's basically kind of like looking back to zero right so that's the key part here so if arrow plus one right which we know that we're turning clockwise because you can see the next in the next element after index zero is index one and index one is right so in this case we're turning clockwise we're going right but eventually if we're at the left if i want to turn one more to the right i want to have modulo 4 this will loop back to the first direction right which is up so that's why we have this basically this equation here right so once we have our arrow uh pointing at the desired loca uh the right desired uh direction uh we go basically next iteration we will basically do a dfs down to that path right so that's basically the goal and at the end what we have to do is we have to move back um we have to backtrack to the original position right so let me just give you one last example right so now you know how it works right let's say uh in this case if i want to go straight i explore all the options maybe all the options here like let's say whatever right and then what we do is we would come back to the original position um in this case i have to backtrack right after we done all the options for this cell right we visit here already right so we do is we have to move back and this move back function basically turns the robot 180 degrees back right so let's say we have this robot right here in this case if i wanted so this arrow this robot currently pointing it straight if i want to turn it back i will have to turn 180 degrees back and then i will have to go back once uh go forward one steps and then what i have to do is that i have to turn back to the original direction which is turn right 180 degree which i will get this robot pointing to straight it doesn't really matter if i turn uh turn right or turn left to left because we're like all we have to do is that for the current uh arrow that's pointing to we're basically turning 180 degrees back right so this is basically how we solve the problem so there you have it thank you for watching | Robot Room Cleaner | kth-smallest-instructions | You are controlling a robot that is located somewhere in a room. The room is modeled as an `m x n` binary grid where `0` represents a wall and `1` represents an empty slot.
The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API `Robot`.
You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is `90` degrees.
When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.
Design an algorithm to clean the entire room using the following APIs:
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
**Note** that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.
**Custom testing:**
The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded ". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.
**Example 1:**
**Input:** room = \[\[1,1,1,1,1,0,1,1\],\[1,1,1,1,1,0,1,1\],\[1,0,1,1,1,1,1,1\],\[0,0,0,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\]\], row = 1, col = 3
**Output:** Robot cleaned all rooms.
**Explanation:** All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
**Example 2:**
**Input:** room = \[\[1\]\], row = 0, col = 0
**Output:** Robot cleaned all rooms.
**Constraints:**
* `m == room.length`
* `n == room[i].length`
* `1 <= m <= 100`
* `1 <= n <= 200`
* `room[i][j]` is either `0` or `1`.
* `0 <= row < m`
* `0 <= col < n`
* `room[row][col] == 1`
* All the empty cells can be visited from the starting position. | There are nCr(row + column, row) possible instructions to reach (row, column). Try building the instructions one step at a time. How many instructions start with "H", and how does this compare with k? | Array,Math,Dynamic Programming,Combinatorics | Hard | null |
1,970 | hi friends welcome back uh today we are going to solve lead code problem 1970 last day where you can still cross recently i come across this very interesting problem on lead code this is one of the hard problems and as you can see this is a very likable problem from like and dislike ratio and uh this also test one of the very important like two of the very important concepts actually so uh i found this problem very interesting and i just thought that it's worthwhile to create a video so that you guys can understand how to solve this problem uh so i can you know discuss the logic and approach uh we can use to solve these kind of problems so today we will uh do that but before we start looking into the problem details i want to mention that my channel is dedicated to help people in their java journey and coding interviews you will find more than 400 different varieties of coding questions on my channel which are solved and explained using whiteboarding session examples and java code those questions are taken from previously asked coding uh interviews by google facebook microsoft yahoo amazon apple and many other big financial companies so if you are preparing for any java j2e interviews or coding interviews then this channel can definitely help you in your interview preparation because there are lots of vast varieties of problems as well as java g2e related videos that you can use for your preparation so please subscribe to this channel now so let's start with the first we will just go quickly through the problem statement then we will go through some examples and i'll explain you uh the logic we are going to use to solve this problem and then we will just go through the java solution right the java code so let's start so there is a one based binary matrix where zero represents lan and one represents water you are given integers row and column representing number of rows and columns in the matrix right so they will give us how much rows and columns are there in the matrix initially on day 0 the entire matrix is land right means everything will be zero in the day zero however each day a new cell becomes flooded with water you are given one based 2d sales array where cells of i is row and column location right which represents the i today the sale will become like filled with water right for that row and column correct so that's given to us as input you want to find last day that is possible to walk from top to the bottom by only walking on land cells you can start from any cell on the top row and you can end in any cell in the bottom row you can only travel in four cardinal directions right like a left right up and down right so written last day when you can possibly walk from top to bottom so that's what the problem says so uh they have given us couple of examples here so for example if you take a look at this first example right so they are they have given us input this thing like row and columns so this is a two by two matrix they have given us and in the beginning everything is filled with zero right you can see zero means land right now they have said that in the first day cell one will become flooded right so they have shown us here so this is one best index you can say right this is one best index so one means this cell will get flooded but we can cross it right like from they have shown us how we can cross it one way to cross it right from top to bottom right so on the second day if you go then the second cell will become uh populated with water so this is the sale right one so it became populated with water but still we can cross from top to bottom they have shown us in the red color right here after that on third day one two cell will become populated so now this cell right one two is populated so now there is no way we can cross from top to bottom because the whole row which is top row is flooded with water so we just cannot start walking basically right because everything is water so we have to answer what is the lot last day we can cross so this is the first day this is the second day so second day we can cross right third day we cannot cross so we have to answer two correct so this is what the problem is so they have given us big example so we'll just discuss using this big example here so i just took the same example so this is a three by three matrix that they have given us right uh let me take the color so three by three matrix they have given us and these are the sales right so these are total nine cells they have given us right so basically the uh positions for nine days is given right each day one cell will become populated with water or filled with water right so these are total nine cells one two three four five six seven eight nine right so total nine days positions is given to us basically right so this one is total nine correct so this is nine days and uh if you uh just start looking into their pictorial representation they are giving us uh the day by day positions right what will happen right so let's just first visually look at it and then i'll explain you how we can solve this so first day everything is land right it's all zero so we can cross from anywhere we can just crossing means we have to start from the first row and we have to reach end of the row basically any cell we can choose right any cell so um this is now the first day right so first day so i'll just remove these colors so first day we are here correct one two so they have shown us this is the cell which got popped like uh filled with water so still we can cross this right either you can cross from here or here you can cross from here right so on the first day we are here on the first day we can cross we know that now right now we are on the second day correct two comma one so now this cell will also get filled with water so still we can cross as they have shown us in the red arrow right so second also fine we can cross it now let's take a look at third day so third day means three comma three will get populated right so polluted uh with water so this one got filled with water now so total three cells are filled now as you can see they have shown us in the red color how we can walk right we can walk using four cardinal directions so we can go left up down and right so here they have shown us one way to walk this right this is the only way by the way we cannot use any other way so third day also we can cross it basically right now they have now let's go to the fourth day second two comma two cell will get uh so this cell basically right two comma two means this because they are using one best indexes correct so this will also cut filled now there is no way we can cross correct if i start from here i will get blocked here right if i start from here i will get blocked here we cannot start from this cell because this is already water here right so on fourth day we cannot walk basically or we cannot cross from top to bottom right so the latest day is three so this is what we have to output as our answer right so this is what the problem statement is and this is what the problem we are trying to solve right so we want to find out the last day the latest day when we can cross right there might be couple of days where the crossing is possible right like for example day 1 day 2 is also possible but that's not the last day is 3 so that's what we wanted to return as our answer so let's let me remove this color so now let's discuss how we can solve this problem right so this problem basically can be solved with two important very important concepts one is binary search and other is bfs right or breadth first search and binary search right uh so both concepts we are going to use to solve this problem so why do we need binary search to solve this problem i will tell you that so uh there are these are the nine days that is given to us right these are all if you count we already know that these are total nine days they have given right uh the position of the cells which are going to be filled with water each day so total nine days so now how we will how uh we will start right means we cannot go from day one to day nine right because that will be too much basically right if we want to check for each day one by one right then that will be too much and it will time out basically right it will get a tle if we start going linear right so that's why we should choose binary search to solve this problem so how we can use binary search uh what we will do is if there are nine days basically write nine days so we will first find out the middle basically of this right so we'll start with the middle so as you can see i just put one track stack trace here so that you will understand this is the binary search stack trace right so 1 comma 9 right so left is at 1 and write it as 9 right so left is here and right is here basically so we'll find out midi middle element right so middle element is 5 which means that we will check with day five basically right this is a day right so we will check if the crossing is possible on the number five day right fifth day so we will check that right i'll explain you how we will check that but you just understand first this binary search logic right so first we'll check it's possible on the middle right so we took the middle element and we are checking if crossing is possible so now crossing is not possible on fifth day we know that let's say right so crossing is not possible on fifth day then we have we will move the left hard left half right so basically let me just write down so this is basically we are here right one two nine so we went here so we checked this middle element crossing is not possible so which means that we have to now move our right boundary here right so we will only now check from one to four because anyway we cannot cross at five right so we will check between one to four now so again we will calculate the middle element of one to four is two right and you can see one two four the middle element is two correct again we will check on second day right we will check on second day if crossing is possible so crossing is possible yes the crossing is possible on second day correct so this is one this is two right so second day crossing is positive and this is three and this is four right so crossing is possible on second day so now our uh we know that we can cross definitely at second leg which means that now we wanted to check from three to four now right three to four now we wanted to check correct because two we already know that we can cross now we wanted to our interval will become three to four days three and day four right three and four so now again we are at three four we will again calculate the middle of three four which will become the day three and we will check if day three crossing is possible yes day three crossing is possible we just saw that right so day three crossing is possible so whenever we find any crossing is possible we will just update one variable uh let's say the last crossing possible day right so whenever crossing is possible we'll update it so now at 3 crossing is possible we'll update that to last possible day right and again we will uh now our boundary of the interval will again just go 4 comma 4 now so left is also 4 right is also 4 so middle is 4 correct we check middle 4 once middle 4 we will find out if crossing is possible no it's not possible so we will not update our last so our last will be 3 correct so this is the last day when the crossing from top to bottom is possible so we just return that as our answer correct so this is the approach we are going to use to solve this problem this is one of the hard problems on lead code and very interesting problems so um so now we have seen how the binary search will work to solve this problem other thing now we wanted to check here is how we can use the breadth first search right or breadth first traversal correct so let me just quickly do here real points um i'll just quickly open this so this is the image right so uh let's see now how we can use the now uh the binary search logic we have already seen now we will see the logic how we can use the breadth first search correct so here we are here right let me just make this big so breadth first search means we will start at whenever we see any zero here right uh sorry so we are at day one so first thing we have to do is whatever day we are checking using binary search let's say for example here we are checking the fifth day right so we have to first find out the uh we have to create a grid uh how the uh sales will look on the fifth day right because the sales will be populated right for example here you can see if someone asks us how the cell cells will look on the fourth day you can see here right so this one two three four cells are populated correct so similarly we have to find out a matrix and create a grid basically uh that will tell us how the sales will look like on that day correct so we can use this input cells to find to create one grid and we will create a grid right so that will uh tell us how cell sales will look like on that fifth day and then for example so um let's just consider this example right so let's just assume that this is how the sales will look on the fifth day correct fifth day let's just assume that right so uh what we will do once we create this matrix correct then we will go through the row right whenever we see any zero right then we will start to do bfs correct we will use bfs or breadth first search or breadth first traversal correct now here we cannot go to right we cannot go down so we cannot go anywhere right so for example right then we will check this basically right here we can go to down so we will try to go here again we will go in four directions you know if we cannot go uh to the we cannot reach the end of the row like the last row then we will just return false basically means crossing is not possible correct if we are doing a dfs sorry a bfs on this uh on this matrix for example then we will check here we cannot go anywhere now here we will do bfs from this cell correct we have to start from the first row only correct so from here we will go here right bfs in four directions from here we will go here correct as soon as we hit the last row right we will just return true here correct true so this is how the bfs will uh help us in understanding if we can try like we can uh cross from top to bottom right so bfs will help us in determining the possibility of crossing correct so we'll use the four directions correct four directions up down left and right so this is how our bfs part will work so let me show you now the so you must have understood the approach the java uh solution now we will discuss uh that will uh you will understand the uh java solution with this approach right so first i just created one this for the directions right four directions so this is our row and column which is given to us else is given to us right row is three column is three and sales are this which is given to us right these are the cells so that is given to us as a input first i created one left it says one and right left and right variables i created correct left and right variables right is at the sales dot length correct because we want to do binary search right and days will be zero in the beginning now using binary search here now we started using binary search right left is less than or equal to right we will do this basically right we will calculate the middle day from this correct left plus right minus left divided by 2 this will give us the middle day and we will we have this one function we implemented uh top to bottom walk possible right here we will pass the sales row column and middle day basically mid means middle day basically right and we will check if crossing is possible for that middle day then in that case it means that we wanted to go to the right side right so there are two cases when we know that we can cross for some day the last crossing day would be in the right half correct so we wanted to check right half so that's what we will do if the crossing is not possible for that day then which means that we have to go into the left half so this is what we are doing here right this is the second case right where we are going left half and then uh at the end we will know uh the days will uh capture the last day when we can do the top to bottom crossing right so now let's take a look at the top to bottom what possible so this is now bfs right so this approach is binary search we saw this is the binary search and this top to bottom work possible is a bfs approach now so how we will do the bfs let me just modify um make it big so um we first created one same size array as the cells right so this also has a row column this is the same size grid as the cells and what we are trying to do in this for loop is we are trying to simulate it how the grid will look like on that day right on the fifth day or on the third day right or on the fourth day how the grid will look like right because already let's say once we pass like one two three four and when we are in the fifth day already five sales are populated correct with water so we have to uh simulate that basically right how the grid will look like on the fifth day or on that specific day so that's what we are doing right so this is how we will populate that grid using the cells correct so we will know now the grid will show like this right like this so it will show us how the grid will look like on that specific day and now we have to do the bfs after that right then we created a cube of integer array it's a just a linked list now what we will do is we first will go from zero to number of columns right so we wanted to check if the first row has anything zero correct if anything zero is there that is our starting point for the bfs correct as i shown you here right so again i'll show you so first row zero right first row zero so these are our starting points where we can do the bfs correct so that's what we are capturing here and we will just add it to the queue right the 0 is a row and the column is c basically correct so these are the row and column for that specific sale right and we will change that grid to one so that we don't want to reprocess it right once we add it we don't want to reprocess it again right so we'll just change it to mark it as a one right so now here our bfs actually starts right this is our bfs starts so while q is not empty we are just going to pull the current like uh we'll remove the from the cube the coordinate of the cell and we get the new row and new column let's say we just called it as new row and new column and we will check if we did we reach the end of the row if we reach the end of the row then we will just return true because it means that we can do the crossing from top to bottom correct if we did not reach the end of the row then it means that we have to do the bfs correct for example here we will do the bfs because we did not reach the end of the row and we have to do it in four possible directions right so we will just capture the new x and y using the direct this dir array that i created right it will give us the x and y means i row and column uh new row and new column for the bfs right because we wanted to go in four directions correct four directions for example uh if we are here let's say right if we are let's say here then we wanted to go up down left and right so we wanted to check if these are all within the uh boundary of the matrix and then if that should also be zero right then only we wanted to consider it so that's what sorry that should be uh sorry yes if it is one then we will just continue right means we will not process it has to be zero because it has to be a land cell right then only we can walk basically so here we are checking that we are within the bound if we are outside of the boundary or it is filled with water then we don't want to process basically right otherwise we will just mark it as one and we will offer that cell to the cube correct because this is how the bfs works so we'll keep continuing like keep doing it until the queue becomes empty and um you know at the end if we reach here it means that we cannot process uh we cannot reach the uh last row which means we cannot cross so we will return false here correct so this is how the solution looks like and here we already always capture the last day when the crossing is possible right days is equal to mid it is it means that we are capturing the last day when the crossing is possible correct and at the end we will just return the days so this is the binary search plus bfs approach to solve the problem right so if you are new to my channel then on my channel there are you will find there are more than 200 different varieties of problems uh from lead code as well as code forces code chef at coder which are solved and explained using whiteboarding session examples and java code and those problems are taken from previously asked coding interview questions by big tech companies such as google facebook apple amazon microsoft yahoo and many others financial companies so if you are preparing for any java j2e or coding interviews then this channel can definitely help you uh all the videos come with a whiteboarding session uh just as we have seen here so that you can understand the problems uh in an easier way uh and those are explained with examples for your easier understanding and always they come with the java code all this java code you will find on my github account i'll give you the link in the description you can check it out the link the code on the github account if you like my java solutions then please consider giving it a star on my github project that will be helpful if you have any friends or colleagues who are preparing for interviews or simply want to learn java concepts share the videos with them they can also learn from these videos and get help during their interview process if you have any questions related to this problem or related to this video please put your questions below the description section um and we will let's just run our code now and let's just make sure our code works with the examples that they have given us so these are the examples that they have given us so we are running all the examples to make sure our code works so our code is getting accepted as you can see two one and three so all answers are correct so we'll just go ahead and submit this solution now so our solution got accepted by lead code it is 41 percent fast on performance side and 39 on the memory side which is pretty decent uh so this is the way we can solve the last day where you can still cross one of the hard problems on lead code 1970 so make sure you practice these problems you understand the logic and how we solve the problem uh whenever you are implementing the java code uh like make sure not to use the id because many times in the interviews you have to just handwrite the code so try to remember you know as much as you can that will be helpful to you and thanks for watching this video | Last Day Where You Can Still Cross | sorting-the-sentence | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it | String,Sorting | Easy | 2168 |
914 | hey what's up guys chung here again and so this time i want to talk about another a different lead called problem here so which is number 914 x of a card in a deck of cards it's an easy problem but i think for me it's more like a medium problem because there's something that i didn't know before doing before solving this problem okay let's take a look so you have a deck of cards and each card has an integer written on it and return true if and only if you can choose x is greater than 2 such that it is possible to split the dac into one or more groups that cards where each group has exactly k cards and all the cards in each group have the same integer okay so what does this tell us right basically you have a you have different numbers here right and it asks you if you can split all those numbers into like any group right basically starting from one or more into any group but among all those groups the size of those groups has to be the same and each group need to have the same value right so for example this is the first one it can be uh split into four groups right oh and sorry and the uh and each group the value has to be greater uh like at least two elements in each group so for example this one there are like it can be split into four groups here so one two three and four so and the lengths are the same and uh and each element in the this group are also the same so for this one no we can't right because one is a group 2 to 2 is a group but 3 is not right so that's why it cannot be split and this one even though we can other elements in the groups are ones but we need this element in each group at least two this one is fine because the uh the group can be one or more so in this case there's only one group and in that group there's one here and a different example is this one here so we have one two right basically this two and can be split into three groups even though there are like four tools here but we can split those four tools into two groups of two so that it can consist can make this three groups right okay so you guys can see right even though it's a simple it's easy problem but the accepted rates is like only around 30 okay right so how do we solve this problem right so i think the first thing come to my mind is that we have to do a county right we have to count each of the unique number the numbers each numbers count appearances right and then we have to somehow use those countings to come up with our result right for example here let's say so in this case it's that's the easiest case right so the count for the uh for 1 is 2 for 2 two three is two right that's the easiest case right and then this is fine and uh another case is like uh one is three two is three right so this is also a valid point a valid uh split and then it comes to a more interesting part here so let's say there are like two uh one is two right two is four and then what three is eight right so this is also can be splitted evenly right because even though two we can split basically these two into two group of two here and three we can split the three here into four groups of three right so that this will be also be a valid split but let's take out at this one is two is six three is sorry two is four three six uh well actually right so this is all this is also a valid one because we can split um we can split this threes into three groups of twos right so this is also a valid one right this is also good and now one is two is four three is seven right then obviously this is not a valid one right so is this kind of combination so what kind of like techniques we can use here right so this problem is more like a math problem you guys must have already have learned this like this concept called greatest common divisor when you were in school right so i think the technique here we'll be using is once we have out countings here right basically we'll be getting the basically the common the greatest common divisor for each of the uh for each of the those two values for example here right so two and four the common divisor the greatest common divider is two right and every time when we have updated one we use this updated one try to do another com uh greatest common divisor with the next count here until we have uh until we loop through all the outcomes here and in the end we simply check the current divisor right that's a and this is the greatest common divisor if this one is if it's greater than one or not right because for let's say for example this one here right so let's say for two and four we have a common uh greatest common divisor equals to two here right and then two and seven right how one two and seven is one right because we cannot split evenly right for set between seven and two here that's why as long as the at so in basically in the end we just check if the update if the last uh basically if the common divisor for all the um sorry actually it should be the common divisor the greatest common divisor among all those values right if those if the value is greater than one then we know we should return true otherwise if it's a one then if it's one then we know we can't it don't it's false right yeah for example this one right so the common the greatest common divisor for this one is three right so this is four this two so a few more cases let's say they're six and nine uh right how about this one so the greatest common divisor is three right and then more here like six and twelve right that's same thing here this six right so basically all we need to know to check is among all those counting counts here the common divisor the greatest common divisor for all the counts if it is greater than one if it's greater than one true otherwise false cool all right so okay so with that being said let's do uh the coding part here so i'm gonna have a counter right so i'm gonna use the uh the pythons uh collections libraries here so it's gonna which will have as a color beauty method here it's basically it's checking uh passing the deck here it with what this one does is basically will count everything and they will it will generate a dictionary here and then uh and then the uh the current divisor gcd okay current greatest common divisor equals to zero right and then basically we're gonna have like four count in counters dot the values right so current gcd equals to the get gcd okay a and b uh sorry the count and right current gc d and the count right so in the end we simply return the car attract if the current gcd is greater than one or not right and now all we need to do is to uh define uh helper functions to help us calculate the greatest common divisor for those two values right so there are a few ways that you can do it and one of the way one of the algorithm i'm using here is i'm basically i'm doing the mod right so basically while um while a basically while any of them is not zero because one of the special case for this like gcd is that let's say we have a zero and three so what's the greatest common divisor between zero and three the greatest three right and basically any uh basically as long as there's like one zeros there's a one zeroes uh we have to uh basically we'll be returning the other one right this could be 100 right so because zero and zero there's no um because it's uh i think that's the definition of the greatest common divisor right between 0 and 100 it should be 100 right because 0 divided by 100 it's also zero right and same thing for this 100 to a mod 100 is also zero that's why we are for anything with a common divisor with zeros it's this number itself okay and since we're using like a the mod here right so that's why basically if the a that's why i'm doing this like i uh i check if any a or b is zero or not basically i'm doing an a times b to help me to check as long as uh either one is zero i just stop the while loop right because i'm going to use uh like a division operator here basically if the a is greater than b i do a uh i do a mod right i do a mod base b sorry and b right else i'll say if right aussie if a smaller than b right into a b is a right so over here and also and a is not equal to b because when a equals to b then we need to stop right basically if when if a is the same as b then we simply return either a or b okay so and then here we simply return we return a if a is greater than b else b right so basically here i'm covering two scenarios so um so first is this one okay so i think for this one it doesn't really matter i think i'm only checking if a or either a or b is zero i just need to return the other one okay basically if a is zero and i'm basically i'm returning b here okay yeah cool okay let's try to run this code here all right and submit yeah so past basically it's a math problem i think why i decided to uh to make a video for this one is because of this gets greatest common divisor i didn't know this like i didn't know how to get this one before solving the problem that's why i wanna maybe make up videos for you guys and for any of you who didn't know this kind of how to calculate the common divisors and yeah you can use this uh this mod algorithm to calculate that right so okay cool guys i think that's it i wanna that's it about this problem thank you so much for watching the videos and stay tuned see you guys soon bye | X of a Kind in a Deck of Cards | random-point-in-non-overlapping-rectangles | You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card.
Partition the cards into **one or more groups** such that:
* Each group has **exactly** `x` cards where `x > 1`, and
* All the cards in one group have the same integer written on them.
Return `true` _if such partition is possible, or_ `false` _otherwise_.
**Example 1:**
**Input:** deck = \[1,2,3,4,4,3,2,1\]
**Output:** true
**Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\].
**Example 2:**
**Input:** deck = \[1,1,1,2,2,2,3,3\]
**Output:** false
**Explanation**: No possible partition.
**Constraints:**
* `1 <= deck.length <= 104`
* `0 <= deck[i] < 104` | null | Math,Binary Search,Reservoir Sampling,Prefix Sum,Ordered Set,Randomized | Medium | 912,915 |
120 | hello everyone welcome to my channel let's solve the problem 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 more formally if you are on index i on the current row you may move to either index i or index i plus 1 on the next row so let's understand the example in more detail over here so we have trying this like input given forming like a triangle kind of structure so here like this is zeroth row first row second row this is index i am basically mentioning uh index of the each zero and this is like an index of the column like this is zero column of each row then we have first column of each row second column of each row like index of and the third column of the each row so this is how so now we have to start from this like here we have only one possible start index start option so we have to start from here 0 comma 0 then from here we can go either the 0th column 3 or the first column like 0 plus 1 which is the first column into the next row so we have to go downward row by row one by one row and the column we can choose whichever give us the path sum is minimum so how we will solve this problem first we will try to form the recursive solution of this problem so if you have already solved some of the famous dp problem it is very straight forward you can come up the recursion solution of this problem so how we will do it so let us say if i call my recursive function helper so that helper function will get the input like roth number and the column number so from row number so first of all what will be the base case so base case is if we cross this row last row so which means if r is greater than or equals to number of row let us say capital r total rows in our triangle then we just written 0 over here because we are done we found the path from top to bottom otherwise we need to select we need to like we need to go in the minimum whichever the path give us the minimum so we will take min of ah either the from helper sorry for the handwriting help helper of next row which is r plus one and the same either the same column or from helper of the next row r plus one or the c plus one column so this is from these two plus the value on the current cell like if we are on r comma c we need to add the value so let us say input k1 as a sum array or something t so t of r comma c is the value of the current are at the r comma c so this is what we will add and we will keep calling recursively until we hit the base case once the base case hit this recursive all the recursion call stack will be fold up and we will get the answer so for this triangle is this is underscore like highlighted from the example i took the image so this is the path which is giving us like two three two five then five to one this is the our path which is giving us a minimum sum which is total is 11 so this is if i choose let's say instead of fair 3 i go like 3 2 4 then 5 then 1 so which is 12 if i go 4 7 3 which is more than 12 so the overall we have only one path here which is giving us a minimum possum which is 11 so this you can pause the video try to write the recursive code so here is the recursive code i have a snippet i have already written and tested this will work definitely for the small test cases but this will give you time out for the bigger input bigger triangles why so let us see what will be the time complexity of the solution let us say we have r rho in our triangle so we have to go ah call the r time so this is r into at in each row we have two choices so in each row worst case we will have c column so there will be two raised power c options so this is the time complexity of this which is exponential so this will definitely time out for bigger input how we can optimize it so before optimizing it we need to see if there is any pattern so let us see if i am on this place which is on the first row 0th column so from here i can go on this five as well as from if i go in this call stack i can also go here like from the one to one so if you clearly see this problem for the same row i we are solving trying to solve for the same row number two and the same column we are getting two times call so what we will do in this case we will catch the solution of this small sub problems and reuse them later if they again occur so how we will catch the solution we can use either the map data structure or we can use the 2d array of integer type as we are finding the integer sum so here is the code like i did for using the map i always try in python you can use at the end at the rate lru cache which is very handy you just write to uh need to write the recursive solution and just put the rate lru cache on top of your recursive function that will take care everything you do not have to do any but in java we do not have direct those things so we can use map here or also nc plus so here the key we can form the combination of these two rows number and the column number by appending like by delimiting with some keyword like some different delimiter like because these both are integer two different combination of row and column make combine and give if you do not add any delimiter so that is the reason once you do you check if we already not solve we will solve this problem recursively and store the result corresponding to this key and later we will return the answer so this will be success and the time complexity of this solution will be r into c which is nothing but if r our c is same as r so r square so one is what and what will be the space complexity as you can see worst case we may store all the solution so space complexity is also r square so this is the one solution now if you don't want to store like use the hash map we can also do save like the same code i have here so we can also store into a two d integer array like lets me define integer two d array d p and you can make instead of global in locally and pass over the helper map function call as well thats nothing wrong you can do that as well so here we define integer array so the what will be the size of this interior whatever the size of our triangle so the triangle has same number of rows and columns so we just use this triangle dot size again here so once this then here instead of generating this string key we just need to check if dp is null then only calculate if dp of r comma c is null then evaluate it and once you done we will put this dp of r comma c is the value and in the end we return the dp of rc the value at this so this is how we are now using the different cache like integer 2d let us try to compile this code this should work it is going and it is working lets we can submit so it got accepted so this is the top down approach from recursive to top down how we can solve its in bottom up approach so let's understand if we start from this row so in this row if i see this 3 which is on the fourth column so this is coming from the previous row third column which is i mine i minus 1. so if i say this is my i or j ah let us say if this is my column so c column i am on current column so this is coming from c minus 1 similarly if i am on 8 this 8 is coming from here and here so if i start like instead of this arrow downward i will take c on seven i can come from this eight or three and from out of these two what i need to do i need to choose the whichever the minimum and then add it so first we will take a 1d dp array of size is same as the last row and fill the last row element which is like 4 1 8 and 3. now what we need to do at 6 we can come from 4 and the 1. so if this is the seat column then we can come from c or c plus 1 of the next row if we are on earth row then we can come from r plus one row this two places only so at six we will check minimum of both of them we will take it and store it back to over here so this will become seven now again at five we will check minimum of this eight and one which is one so one plus ah five which is six now at seven we can come from minimum of three so this is three plus seven which is tan over here so this is 10 over here so this last column will be not again evaluate then we keep further go upward at 3 we can come from this index or this index so whatever value over here we calculated first 7 or this six we will take the minimum from these two which is six plus three this will be updated to now nine and again at four we can either come from this or this so six or this is eight so six will be minimum so this will be ten now again at two we can come from either from here or here so nine is minimum so we will take nine so the minimum nine plus two which is minimum so this is the final answer eleven at the end at zeroth index we will get the answer so this is another approach thinking to build the solution from bottom up so now once you got the idea you can pause the video and try to implement yourself so let us quickly implement this code let us reset this first so for code we just need ah 1d array of dp so let me first define the size of our triangle which is let us say n triangle size so this is triangle dot size and now this will be same size as of n plus 1 and so first we will initialize the last row from i 0 i less than n i plus dp of last row i is triangle dot gat ah n minus 1 the last row and get the ith column value so that's it once this done and so here we are have to start from the second last row and i until go is zero through and i minus then on the column like let us say column is start from in j is equals to zero j less than i and j plus now dp of j is math dot min dp of j comma d p of j plus 1 plus the value at that row which is i dot gat at that column j so once we done we just return dp of 0 that will have the minimum pass sum so let us compile this code bottom up approach code so it got compiled there is a answer is not correct let's just go again oh this is what is the mistake as every row will have i column so we have to run this loop i plus 1 until i plus 1. so let us compile it again and it got compiled let submit this code so it got accepted so now the time complexity of this solution is again o of n square n is the number of rows and this space complexity is o of n and this is bottom of approach solution so if you like this solution hit the like button and subscribe to my channel thanks for watching | 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 |
93 | Hello, today's pull-up problem Hello, today's pull-up problem is the problem of Litcode 93, Restore Lipier Address. If you interpret this problem a little, it means composing a valid IP. One string is given, and the string is divided into 4 spaces. For this to be a valid IP, one space is required. This now depends on the numbers between 0 and 255. If it is configured in this way, it is a valid IP. And when the string is given under very restrictive conditions, only numbers are given. There is a condition like this, and if you look at the example, it is given as a number like this. Now, this is a problem that needs to be properly divided to form a valid IPA address. However, since this is just three spaces, I think the problem can be solved by using statements in succession. However, the more statements overlap, the more complicated it becomes. Since we thought it would be difficult to calculate the number of all possible cases, we will try to approach this problem using a method called tracking. First of all, the concept of backtracking refers to looking only at cases that satisfy certain conditions among all possible cases. While searching for the solution like this, if the current path does not seem to be the solution, it means not going on that path anymore and just cutting it off. Usually, I call a function to replace the statement, but let's try to approach the problem a little bit. Yes, first vs. I have moved the problem to the code, and now I will receive the string and solve it right away. First, let me check whether the string is coming in properly. It is coming in well. Now, the IP address string cannot be less than 4 or longer than 3x4 12, so for example, 0.0 .0 Well, I did it like this, but 0.0 .0 Well, I did it like this, but 0.0 .0 Well, I did it like this, but this is the smallest string, and now the IP address filled with 3 spaces is the longest string. So, in order to process this condition first, if it is less than 4 or greater than 12, it does not apply, so it returns immediately. Now, since we are going to declare an array for what we want to find and solve it through backtracking, we will now minimize the use of prologues and try to re-call a function to find a satisfying condition. try to re-call a function to find a satisfying condition. try to re-call a function to find a satisfying condition. Obviously, we can do it with prologues, but parents. 4 I think there may be complications such as overlapping, so I prefer backtracking when finding the number of cases like this. So, if you try it once, you first declare this function and call backtracking. Then, at the end, anyway. Since we are going to return an answer, we do it this way, and now we fill in the answer in a function called backtracking and receive the dancer right away. What we are going to do in backtracking is to properly array it into 4 spaces, that is, fill in the 4 spaces separated by dots. I'm going to put a current index that tells me the current index, and I'm going to put an index that tells me how far I've come and things like that. So, inside this, you can cut it by one space or you can cut it by three spaces, so at least you can cut the age by 1 to 3 spaces. The child returns to the number 3 in this way. Basically, in the problem, everything is given as letters and numbers, so you can cast it as a number. Since it is a string, cut it and insert it from the snice index to the index plus eye. For example, if the index is 0, go beyond 0 and cut it by one space, and then pass the inserted array to a function called back threading. If you pass it and put it back into a function called back threading as the index has increased, for example, if you put it up to 192, you are interested in the index from then on. So, it is a process of inserting index 0, index 1, index 2, and index 3. So here, when backtracking is finished, you need to pop it from the current. This is because for all cases, it keeps going down while calling backtracking to itself. Now, if you don't pop it just keeps going every time you call effect tracking. Since it is piled up, it is not possible to find the number of legitimate cases. And the function called two-back tracking the function called two-back tracking the function called two-back tracking has a base case, and the base case means an escape condition. So when the link is 4, it pushes when the array is full of 4 spaces. When displaying, you need to push it together like this and return. If you do this, now all 4 spaces are filled and it goes into the Elser. If you go this far, this also starts from 0, which is the initial stage, so if you pass 0, you can see the output like this. But here. The problem is that if you do not use all of this 25251135 and backtrack only the front part like this, 2552, it is treated as a suitable IP, but in this case, it is not a suitable IP because the entire string was not used. So when this current array is 3, it is 3 and S Length So, the remaining length is the length from the index to the s-length. For example, the index is length from the index to the s-length. For example, the index is length from the index to the s-length. For example, the index is 9, and the 12 sides that use the s-rank are 12 - 9. and the 12 sides that use the s-rank are 12 - 9. Then, there are 3 left, and in this case, there are three spaces left, and the index starts from 9. If there are three spaces left like 9 to 10 11, you can add something to the current, but if there are more than the color, in this case, as I wrote, there will be more than the color. In this case, it is not an appropriate IP address anymore, so you have to subtract it. Continue In this case, we just do a return process and this also falls under the escape condition. Then, if you look at the answer again, there are still some duplicates, and since there are duplicates, when you do this backtracking, the duplicates are removed. You can do that. So, how do you remove China? This is an array, so use three. Three now receives Eater Love, and Answer is now an array, so if you put it like this and just put it in three, you can see that the duplicates have been removed. But it's still not an appropriate string. For example, if you go like this and get to 1, you haven't used all the strings yet, so you have to make all the strings available. So how do you handle this case? You can filter out cases where you have not used all the strings in this answer. So the length of each element is this plus 3. What this means is that there are 3 dots in the middle, so if you use up all of these elements, this element is the existing one, so the problem is It says that it will be treated as an encoder only if the length is the same as the three + 3 dots added to the string given in , and only if the length is the same as the three + 3 dots added to the string given in , and now when I look at the console log, it shows something like this, but now there is something like 525 is no longer a string between 0 and 255. Therefore, this also needs to be removed. In order to remove this, if you cut it by three spaces, starting from the snice index, if it is greater than 255, break it. Now, it will not even push the current array here, so it will handle cases greater than 255 like this. I think it can be done. But now, the last thing that starts with 0 in that IP cannot come later like this. You just have to process that part. So, if this part is 0, when backtracking, put the parent and then put in 0. Since you cut one space, you just need to increase the index by one space and put a break right here. Because if it is 0, you can't add anything after it. So if you cut it here, you can see that it is output normally. So you can return this part and do this. I'll try submitting it as an answer. You can run it and see it pass, and even submit it so you can see it pass like this. Yes, this was the tool for question 93. Thank you. | Restore IP Addresses | restore-ip-addresses | A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros.
* For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses.
Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order.
**Example 1:**
**Input:** s = "25525511135 "
**Output:** \[ "255.255.11.135 ", "255.255.111.35 "\]
**Example 2:**
**Input:** s = "0000 "
**Output:** \[ "0.0.0.0 "\]
**Example 3:**
**Input:** s = "101023 "
**Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\]
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of digits only. | null | String,Backtracking | Medium | 752 |
956 | Hello gas welcome you me YouTube channel so today we are going to solve problem 956 toilet and what is this question what is the billboard and want you one you have the largest height d billboard bill have you steel support mast be of equal height You are life and collection of road date can they bill date together, so the one on his side, the one on the left side, which will be steel left and the one on the right side, it should be of the length of both, so how will we take it, like Here 123 is taken on one side and the last coin is taken on the right side. What is its sum? 6 Its sum is six, so how can we make the maximum so that its sum is equal to the sum of both, the maximum is to be found out which includes left and right. If I can put it, then the length of the two should be 23546, so 123456, so now how can we take it, then both the sides should be equal, then the sum of both should be equal, that is, only then we have to make it equal by making everything equal, so like you will take this, you will be 35 left. What will you take right now 56 235 46 How much is done, what will you do if you have to install it, don't take it right, let's take it in sum and this WhatsApp has just happened, what will you do now you have taken this one, so I Plus one will do nothing in the album plus Plus one Ashram plus Now what was the third option What was the return What will we do Which of the three will give the maximum value Which of the three will give the maximum game On's map What will happen after doing this What to return and if it is not then it means that it was not valid because we had to take the same, then we will give an invalid answer, this is what Max is saying, so we will give such a minimum value that we will give -19, give such a minimum value that we will give -19, give such a minimum value that we will give -19, which can never be an answer. Yes, then this is your solution, now let's submit it and see, Tilia has gone because alpha sir, very sir, this is happening and we can't even do it in DP because what is said here is the length of 25 and this is of road. The total of both here, which is the total sum, can go up to 5000, so if we make a DP, then the DP will become 3D, first, its DP will be made of M size, then for ₹ 5000 and will be made of M size, then for ₹ 5000 and will be made of M size, then for ₹ 5000 and 5000 for 5000 rights. It is not possible to make so much and this will not be such a big solution for N. One, what is the other way to do it? So this is 00, this is correct, this is the difference and one, what will happen now is the DP here, now there will be change here also. One here we are storing here this difference is what is yours and also this rod is three options so now difference now here what would be an option difference which is bigger so difference is one difference one what would be one Nothing will be changed in the difference and now the max that it will give of all three is the answer. Now what will be changed in it, what will happen here, went till the last, then how did it become the base, so and when here, what here It will happen here, so now if we store it in front of both of us, then the difference will be equal for both of them, only when the difference of people is zero, we will write here what we are making and make it for 5000 because it was in the evening, so we have divided it into two. After submitting, let's first see what is happening and if life i and this sum are calculated again and again, once we have stored the difference for i and this i and all these then Then why calculate it again and again, that's why we will make one DP, here it is Rajasthan, which is the difference, if we made it of this size, then it has become DP, what will we do after doing so much, now what we are doing here tomorrow. Before that, we will check here, what will we do if we return, OK, it is done here The difference will be stored sometime - I have got a total here of 63, it can be done before this, there is a difference in Cap's mines, one two, three, six, one. If you are three or six then what will you do, the first one will become zero and take it all as one, you are doing one, three plus three, if you cannot do the difference then what will you do in this +5000, this is how much positive you have got. If I go to A, then what to do, if the plus goes to 5000 - then to make it positive, goes to 5000 - then to make it positive, goes to 5000 - then to make it positive, what size will you make? 21 and the minus will be made positive, like - if A goes to 5000, then to turn minus will be made positive, like - if A goes to 5000, then to turn minus will be made positive, like - if A goes to 5000, then to turn it into positive, you need to do the same. Take relief in positive, if there is relief in positive, it would have been 5000 plus, so it is worth 10000, this one is worth 5000, let's run it so okay, see you in the next video, thank you and please like and subscribe you me Channel | Tallest Billboard | number-of-music-playlists | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null | Math,Dynamic Programming,Combinatorics | Hard | null |
4 | Hello Gas I am Lalit Aggarwal Welcome, this question is literally a very easy question, there is nothing to take much tension here, literally this question can be answered very easily, what simple logic you have to apply here, that is a small brick. It is possible that you have one, can you reduce the vein which is one and the vein which you have, you can find out the total number of elements in it. For now, brother, I have found out the size of this too and find out the size of this too, from that you will get the total number of elements. Very good, after that then what do you have to find the median? Then you reduce one, add the size of both, then you have total number of elements / 2, then you have total number of elements / 2, then you have total number of elements / 2, then you have reached its medium, it is absolutely correct, now at the medium. After reaching the problem was that we had to find the median, then what is there in the median that it will be in the sorted way, first of all it means number, its shortcut is if we have individual life, then we have to bring both of them together in the socket and then after that. If you want to give its medium then what will you do? We have gone to half the size of both, now we will join only the elements up to the same number of elements. If we will join the number of elements, then like we will join the half elements up to the same number of elements. And we will return it to whatever number A was on the half-n element. And we will return it to whatever number A was on the half-n element. Such a medium is fine. Think a little about its bigger size. Literally, it will be done easily. Well, for those who did not understand the question, there is no need to take tension. First of all, you are going to understand very easily what is the meaning of the question, we will approach it and give the final bill, move towards its implementation. Look, it was explained that the question was going to be eaten. In the question, you were saying that here the name is understood by the name. Hey ka rahi ki maine aur Dums tu naam ka hi kari ki hai ok very nice name kya hai hey ka rahi ki maine aur dums tu naam ka hi kari ki hai ok very nice name me hey ka rahi ki maine aur dums tu name ka hi karni ki hai ok what a wonderful name hey I am two elements and namas tu naam ka elements are double ok what to do apne ko karna hai that we have to combine this whole. Combine political and write in sorted way. A is in political, now reduce one, now return whichever is the median, so is this the medium? Tablanji Bhaiya, this is the medium. Android Discussion Solve OK, now look, now there are two or three more things here which Do you take care of yourself? First of all, whatever life will be here, it will be sorted in itself, meaning it will never come three comma 1, it will come only one com three, meaning it will come to you always in a sorted way. Okay, this thing should be very clear and similarly, Namas, you are also there, that is mine, it will come to you only in sorted way, okay, now propose here, it would be like this, one comma three and here two comma four, it is ok, very Okay, now here if there is any asset, then here we will write it in shortcut, what will come three comma four, so now tell us here, what will be its median at this point of time pink, because what is there in the middle here, there are two values, so tell us. What will be its medium? What will be the median in this? Plus these two and divide by you i.e. 2.5. Got it. Yes brother, I understood. There you i.e. 2.5. Got it. Yes brother, I understood. There you i.e. 2.5. Got it. Yes brother, I understood. There should be no doubt in this. Said, OK, even on the story, if the total of Apne and number of values has even on the story, if the total of Apne and number of values has even on the story, if the total of Apne and number of values has come out then what will Apne both do? Meet, we will do the plus of both the middle values and divide by 2, plus of both the middle values and divide by 2, plus of both the middle values and divide by 2, that is, we will find their average and even if there is an odd number of values in the story, then and even if there is an odd number of values in the story, then and even if there is an odd number of values in the story, then its medium will be found very easily, there should not be any doubt in this, ok, question is here properly. Understand, since you should go, you have to sit towards its approach. Look, the approach you are going to do will literally be a very easy approach. According to this question, see what you will do, you will not do anything, your total number will be off. If we take out the elements, then its total number of elements is how many numbers, how many are its total number of elements, meaning one, then the total, now whatever is our second element, what is our radium, what is the second element, what is the median, why did it become like this, did not do anything, total number You understood the concept of finding the total number of elements and dividing it by you. You understood that you had to reach the median. You said yes brother, you understood, there was no doubt in it, now where is the problem in it that you have to reach plus one. Was also maintained because Apna has to be taken up to the second element. If Apna needs this second element, then like one or three, it is okay. If Apna does not take the second element, then only this first element will be taken and Apna also needs the second element, therefore. What did you do, you did plus one, there should be no doubt in this also, he said yes, back and if you do 3d/2, should be no doubt in this also, he said yes, back and if you do 3d/2, should be no doubt in this also, he said yes, back and if you do 3d/2, then what will come directly here is 1.5 and then what will come directly here is 1.5 and then what will come directly here is 1.5 and then what is that, I understood, so what did you do? First of all, okay, let's do plus one inside it, 2.5, which is rounded off, 2.5, which is rounded off, 2.5, which is rounded off, you are there and you are there, then it is okay, yes, there should be no doubt in this, first of all, find out the number of elements. The total number of elements was divided by 'Tu', total number of elements was divided by 'Tu', total number of elements was divided by 'Tu', within that 'Apna Kya Hai within that 'Apna Kya Hai within that 'Apna Kya Hai Tu A Gaya' and this one, 'Hey, you mixed both ' and this one, 'Hey, you mixed both ' and this one, 'Hey, you mixed both ' Apna' and 'Thu A', after mixing both, this Apna' and 'Thu A', after mixing both, this Apna' and 'Thu A', after mixing both, this element of whatever will come sorted, this element was simple. It's a simple thing, call me, it's a simple thing, you will do less than yourself to get it, what will you do less for yourself, we will try to solve these two till now, you know that you are sorted in yourself and this is also sorted in itself. He said, yes brother, I knew this, there is no problem in this, so first I have started looking like a bell, okay, what did I say in the looking of bell, first of all, if you are standing here in your starting, then make a poetry here. Took and made a painter here, okay reduce one, make this one a little bigger, make this one and this one bigger too, okay, there is no problem, so first of all I checked which of these two He said, this one was small, brother, this one was small, this one's value is not a problem, after that he again said that you three are small, you have taken it here and pointed this one, then now this Tell me, is there any problem in the screenshot, that is any of it fine? Suppose India said this. Yes, brother, they are going to do their calculations like this. They will be checking all of them at both the points of time, so that the time will not be wasted much. Whatever M. Or whichever of the others we have the highest time, it will be ours, okay yes, now here too, what is the problem, we will see it in ourselves, it is good for you, what will we see about the half time of these two? Complexity means by adding these two, the complexity which will come every time, you must be moving inside this because you had to calculate your Apache itself, you did not want to go so far, so as soon as you have the second element, you broke there. And after breaking, whatever last element you have, what did you do? Okay, now what happened here you had an odd value, so what did you do, straight up to the second, this, till the second, this, you counted and the seconds. What have you done in direct retail, there was no problem in this, but for supposing, you have these and number of values, meaning one, three, four, you have this, after solve also means this happens here. 13 happens here, add one more four to the number of 2, that's it, now the calculation will change here, how will the calculation change here, first of all, we will do if it is of all quality, then the total number of elements will come out, how many are there, meaning 1 2 3 4 is 4 + 1 5 / 2 i.e. 2 3 4 is 4 + 1 5 / 2 i.e. 2 3 4 is 4 + 1 5 / 2 i.e. how much bullet will come to you, only you will come, is there any problem in this, you have come to yourself, now what will you do, if you run it total, then zero one means that you have come to yourself. One comma, you are fine, you have this value, now what will you do, whatever your N - 1 and N - 1 are both, whatever your N - 1 and N - 1 are both, whatever your N - 1 and N - 1 are both, where I will return my answer, we will check on time that your vector is Meaning, the sum of these two elements is the number of elements and is odd. If it is odd, then simply the last one was returning, meaning it would return three. And here, if it is and, then what will we do with the last one and the second last one? After averaging out, you will be returning it. Once you see your implementation, look at this thing. It is here. Let's come here. First of all, your answer will come. Okay, then what have you done? Then you can also say plus. Whatever is the factor of the answer, its size is actually correct because what was the function of it according to you, then what did you say that the size of the answer should be < and at the same time the size of the vein one should be < and at the same time the size of the vein one should be < and at the same time the size of the vein one should also be taken as one by name. The size should be small like this, otherwise we should be small like you. Why did you do this because if it is okay for you to propose here, please propose that in Namas One, there are thousand elements, you have only one element, okay and there is element in Janam 2. That's the smallest validity, so once people walked comfortably, what will happen after that, here he is pointing out further and said, yes brother, he is pointing out further, then I, there is no value ahead, so that's why If it is compared together then that is a good thing, will the error come? Okay, so to maintain this thing, what have you said that the eye point you have is also the painter of the eye is pointing to this one, so that is the story. Do n't go beyond its size, whom will it point to next and the one with the same nose should also be with you so that the point of your nose should not go beyond its size because there is no sense in whom it will band further. There will be an error if it is successful then it is ok now that you understand then what did you do here, come inside, check the same, band with the name of Jo Aayi Hai, Kya Woh Bada Hai Dums Tu Ke Like, if it is like this, then the name is Sukh Jai. Whatever is the answer, do Pushpam and make g4 plus, otherwise make I plus and push the value of I, there is no problem, I did this, after that, I welcome you. And I said that it is possible that now as I had taken the condition that name Suman had a value of ₹ 1000 and Naum is only one had a value of ₹ 1000 and Naum is only one had a value of ₹ 1000 and Naum is only one value, so now I don't know how to handle it. Said, let's make this also our dot size, every point of time, what is the size of the answer, it should not be too big, N, what have we made, what are the elements of both of them, what should be the last of them? Till the last size of both of them, we will not calculate beyond that. After that, what did we do? We checked the size of the answer and also checked the size of our names one. If both of these hurt with our eyes, it means that we are not able to do so. - hurt with our eyes, it means that we are not able to do so. - hurt with our eyes, it means that we are not able to do so. - Size of the answer: If your answer is small and the Size of the answer: If your answer is small and the Size of the answer: If your answer is small and the side of the vein is smaller than your eye, that means you have not gone beyond Namas One while doing your calculations, then push yourself back such things in the answer and Ego Plus. Similarly, you have also checked the formula for the second factor. It is also possible that if there is only one value in the name and there are 1000 values in the room, and there are 1000 values in the room, and there are 1000 values in the room, then you have set the conditions for both. After that Then, Apna Ne Simplief's condition is going on, in its condition, what Apna is saying is that if you divide Apna by the size of one plus the size of you, meaning if there are more then one then it will be zero. He said, yes. Brother and if it is there, then what will we do with the answer? In the vector which is Apna, we will take the last value plus the value in the last second, we will take these two as Apna plus, we will divide it by Apna and we will return it to Apna in double form, why in double form because Apna Ko Answer Whatever is there was returned in double. This zero which came in double it extra 4, it is fine as it is and then if it is not so, that is its own value. Simply, whatever is the last value, it will be returned as its own. There should not be any doubt in the vector, after submitting it, we take a look. Ok, tell us what will be its space complexity and time complexity. Look, the submission has been done very easily. Its space will be black shade and time complexity will be here. Are you asking him how much will this be of m+n/2 of m plus? Antivirus is there so we are going m+n/2 of m plus? Antivirus is there so we are going m+n/2 of m plus? Antivirus is there so we are going to its half size. He said, yes brother, the space complexity is your of m plus and divide by, you are fine and exercise yourself. I am not doing it at all, it will be due to time complexity because my net max is going till the same, of M plus and divide by you are fine, I hope you have understood well, thank you | Median of Two Sorted Arrays | median-of-two-sorted-arrays | Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106` | null | Array,Binary Search,Divide and Conquer | Hard | null |
1,926 | hey everybody this is Larry this is day 21st of November hit the like button hit the Subscribe button join me on Discord let me know what you think about well yes claim secret reward 10 coins so yeah if you're wondering why I always go to this page that for that reason so I would actually also take a quick pause um the one thing that I always um try to figure out uh or not trying to figure out I mean I just try to do once in a while it's kind of expressing gratitude and just like you know take micro victories and you know celebrate a little bit yesterday wow actually I just noticed that like the top five hour six out of seven is all from China but um but yeah um so I finished 45th yesterday which is you know pretty okay I feel like I do better than that often but it's still a nice thing to kind of you know celebrate yourself so I'm just going to share with that uh if you didn't appreciate it uh maybe it's too late to say this but you could have fast forward so it's only been a minute in all right chill uh no I'm just kidding promise it's fun right just wanna make sure I didn't have like a random problem up uh yeah 1926 newest exit from entrance in Maize wow I guess this is a recent Farm because in the picture is someone with a mask on that's kind of intense anyway um you have a matrix you're given the entrance this entrance just like uh okay one two okay what is the person dot okay so that's just another way of doing wars and numbers okay so you have the entrance and then you go up down left right and then you try to find the newest exit and empty cell that's the Border okay the entrance does not count as an exit hmm even if it's on the border okay uh that's an awkward sentence but I mean that's fine it's just another if statement or something right okay so I mean I don't think that there's anything super tricky about this one in terms of uh okay I'm just looking at the constraints R and c and there's a hundred I like using RNC for rows and columns because M's are kind of confusing um for this case it doesn't matter but there's some cases where it's not uh symmetric or you know like it's not they like one of the cons one of the dimensions may be significantly greater than the other or something like that and you have to be really careful you don't mess it up and I'm speaking of course from experience where I have messed it up uh every little tip I'm I give on this channel is from me previously messing up uh in the past uh so maybe multiple times I think so um I may be uh off by a you know a couple of problems but I think I was talking to a buddy in real life uh because I have buddies in real life from time to time um just to kind of give you a little bit of context uh this is Sunday so maybe there's so many story times today but what I was going to say is that um I play stuff about like 10 000 problems but over like 20 years right so it's not like I sat down and I find four of them I mean at least not at the same time I even took probably I took a break for about like eight years of solving anything except for me yeah I think that's lovely right so like you know but there's still a lot of primers you know and a lot of muscle memory and a lot of stuff like this so um so yeah and so sometimes the reason why I write something um and feel free to ask is because you know there is some mistake that I made in the past even though uh pipeline is relatively new to me in that regards but you know but even then it's been a couple of years okay so yeah this is the shortest path problem um I'm just looking up and down to see if there's any cost meaning in the shortest path problem whether there's a cost or a weight on the edges right which means the cost to them thing so otherwise if because there's no cost and there's no um free effects and when I say free I mean like it if there's a cost on like obstacles or something like this then potentially you could have zero one BFS which is a I don't know a fancy BFS if you ask me but um but here a BFFs will do and once you recognize that this is a uh a bright first search algorithm everything is actually kind of straightforward to be honest in the sense that um and I don't mean to diminish people who may struggle with this but it's just that the hard part about that is recognizing that and I think this is a pretty cookie cutter version of that problem in that if you have done enough breakfast search on a grid um you are probably getting this pretty quickly I mean like I said maybe there's some if statements that you're missing and you know you have to um be you know in that case you'll learn how to be more deliberate and careful about edge cases but the core part of the problem is going to be the same okay four minutes or five minutes for me to say all that but let's get started then so our language or is it good to do right and as long as this is zero this or greater than zero this should be fine so constraining this is at least one so we're Gucci for now um an entrance so maybe I just call it sxsy I've got entrance say and then you know as this is just general um uh a breakfast search stuff um and maybe just a distance as you go to like to say infinity times uh C4 um and the reason I get this asked this question like the way so I did do this is because it keeps it um it keeps it an integer um there are things where if you use math dot infinity or whatever math.enth math dot infinity or whatever math.enth math dot infinity or whatever math.enth which is a foe um because it's a throat sometimes you ought to promote stuff to uh being a double writer but in Python you know um yeah and in those cases you regret doing that so yeah um okay so then of course distance of sxs um maybe I can do something like NQ as a function x y and then that's just distance or maybe D distance of x y z to T a pen that's why oops yd what something like that right now while length of Q is greater than zero after we end q a success Y is the zeroth element then yeah x y d is equal to Q dot pop left and of course I need to set up directions and that's as long as you get all four directions I don't you know doesn't really matter um okay and then yeah I mean turn negative one every Loop put down here if x is equal to zero or X is equal to um do I have X oops um maybe this is better ten but then we return d right oh this order completes messing me up okay otherwise then we just you know look at the neighbors check the check to make sure that we're on the map check that it is not a wall or whatever Plus then we can and also that it is not used uh D plus one and that's pretty much it um one thing that you can do is a little bit of a Time Saver is of course um at this here as well at the if statement here I depending on the problem it depends on how you want to do it but um yeah I think this is okay though because this cannot be sxsy this cannot be the beginning because the distance would be zero if I do it correctly let's give a spin this looks good so far let's give it somewhere unless I missed some Edge case which is and I guess we'll Discover it together uh cool I get time limit exceeded oh did I use dice true or somebody in the past that's weird why does this timeline exceed in the past hmm now I'm not sure the idea is right maybe I just forgot to set done is you're going to choose somewhere oh right okay so that's just because I forgot to set done okay all right well um okay yeah I mean this is a way as I said a very vanilla um implementation of the of web first search PFS I don't really have much to add here it's going to be repressed year as in many breakfast search and of course in this case both V and the uh or V is going to be all of R times c and e is going to be the number of edges is going to be you know roughly four times R times C so which is still all of our times c um in terms of space because we use this it's also going to be linear and that is going to be R times c um it's linear in the size of the input right because R times C is the size of the input so yeah um so linear time linear space and that's pretty much all I have for this one so let me know what you think uh excuse me stay good stay healthy to good mental health I'll see y'all later and take care 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 |
864 | Hello friends welcome to code Sutra in this video we'll be solving lead code 864 shortest path to get all keys this problem is not actually a tricky problem but this problem is something that requires step-by-step approach and that requires step-by-step approach and that requires step-by-step approach and there are multiple steps that is involved in this problem but if you understand or break down this problem to step by step the solution is actually quite easy to this problem but what is the pre-request side to this problem the pre-request side to this problem the pre-request side to this problem the prerequisite is that you should already be knowing the breadth first search algorithm if you don't know the BFS algorithm I have mentioned a link in the description please first go through the BFS algorithm only attempt then attempt this problem then only it will make sense okay so let's first understand the problem statement once I have understood the problem statement half of the solution is solved so in this problem statement first we are given a starting point that is indicated by at this at indicates the starting point where the person is and the small alphabets that is a and b indicates the position of the keys that are present in this given grid this a and this B are different keys that is in this example there is one blue key and there is one orange key that is indicated by A and B then we all also have logs in this problem that are indicated by the capital letter a and b so the thing is the small letter indicate keys and the capital letter indicates the locks so what are the problem constraints that we have is the first thing is you can travel in only four direction or you can travel in all the four Direction say for example we have the person here he can travel in all the four Direction so that is the first constraint what is the second constraint you cannot travel through a wall the walls are indicated by hash and once you hit a wall you cannot travel through wall so that is the second constraint that we have what is the third constraint we have the third constraint is you cannot go through a lock without having the key for example say you had this orange lock instead of here we add this orange block here so then we would never be able to travel why because we cannot travel through a lock without having the corresponding key so and finally we are given the number of keys will be maximum number of cases six so these are the four problem constraints that we have and what is the solution that we have to find the minimum number of steps that you have to take from the starting point to collect all the keys in the first example it is equal to 6 it is equal to 8 to get the first key you will have to travel two steps and from this two one two three four five six then six one two three four five six so it will be eight so the first example we require at least eight steps to get all the keys similarly if you look here this example actually explains the problem very thoroughly the thing is you cannot travel through this lock and go collect this key the idea is you cannot go through this lock why we don't have the orange key so the only path we will be able to take in this example is we have to go through all the other path so what do we have to go through this path then get the key and stop the key idea here is you should need not open all the locks but you just have to get the keys so answer for this will be to get the first key you will be requiring three steps and from then again there you will be just requiring six steps that is you need not open the law so I hope you understood the problem statement now let's dive into the solution before diving into solution let me explain BFS in a very brief manner in BFS what we had is we will visit all the Neighbors First and then we also have a track of visited neighbors how is it tracked it is tracked with a Boolean array right say we had this array we kept a track of everything whether I have visited this or not visited this so if I have already visited this we were not allowed to visit in the BFS algorithm right so this is the BFS algorithm but will it be sufficient for our problem let's look into it let's let me take another example let me take this example right can we take this path that is the person will travel this and can he go like this no right he cannot go like this why because this we have a lock and we cannot travel through a lock without having the key so we cannot take this path and find the b key so the idea is first we have to go to the a key and then only we can come back or we can take this path also but we don't have the big b key so the only option here is we go to a key then come back again and then go back but if you look here this cell is being Revisited right so instead of just having a Boolean value for this visited or not visited we also need to have am I visiting this cell with the keys or without the keys let me explain this again the first time we came to this cell became empty-handed we did not have cell became empty-handed we did not have cell became empty-handed we did not have any key with this so if you are coming again to this sell without any case it doesn't make any sense but if you are coming to this cell again with one more key or any other key then it makes sense right why because we now have the key and it opens up a new option right similarly you can come to this point again if you have another key that is you have both a and b key then you can come to this cell again right so let me explain this first position was 0 and we did not have any Keys what is the second position that we had the second position was one comma 0 but we now have no case again in our hand then again what was the other option that we had that was 0 comma 1 again we did not have any Keys the next option if you look here the position is 2 comma 0 but we do get a key with this that is key a now again we will be having three options but one of them is zero one comma zero which we have already visited if you look here one comma 0 is already visited but the thing is we have now got a key so we can actually visit this again this and this are very different so instead of just having a Boolean array what we should have is we can have a has such and this string what we will be having is a hash set of string and what does the string contain the first part will be the key part which will indicate which all keys we have how do we come about this I will explain in the next part but the first part will have the number of keys then we will leave a space in between then the position I then again a space and we will have the position J for example let's right we have a b key and we will leave a space and the position is 0 comma 1. so this will be our string and this will be added to our higher side so once this is added to the headset this indicate we have already visited this position this cell with this key configuration so don't come here again so that is the key idea that we'll be having but can we just use the key configuration that is one idea is we can just keep all the key configuration that is we will keep this key configuration but that would be a bad idea because every step we have to use a string and append the string and also we have to maintain this in the same order but that will be actually quite complicated what is the next idea is actually a very beautiful idea this can be used in many other problems also so please do listen to this very carefully now we can use the binary representation of a number how we can use 0 indicating we don't have this key and one indicating we have this key 0 indicates no key and one indicates yes we have the key and what does this indicate this indicates a be C then D then e and then F the good thing here is in the problem we are given that the maximum number of keys is only six so this will be our representation and what we can do is once we have found a key suppose we found the Key C what we will do is we will just update from this C we will just update what will this number be this will be 1 2 4. so this number will be 4. so what is the number 4 indicate 4 indicates that we have the key C suppose we found a key one now key a now this will be updated to 1 0 1 and all the remainings will be zero this number indicates five so just by saying this number we are able to identify we already have a and c key let me give you another example say let's pick up a random number uh like seven what are seven indicates how can 7 be represented seven is represented as one and all the remainings will be zero so this indicates that we have a b c b and a key we have all the three keys so just this number indicates so the idea is instead of storing in the format of a string what we do is we store in the format of a number just by converting using mask and this will range from 0 to 64 that is 2 to the power of 6 why because that is the maximum number of case that will be having so in this state what is the particular state of a cell we will be having one that is case configuration which is a number from 0 to 64 indicating which all keys we have then we'll be requiring I and we will be requiring J so we will have a new class this may seem like complicated why are we even having a new class cannot be stored this in Array yes we can store this in a array also but we would prefer storing it in the format of a new object that is state which will indicate the key configuration and it will indicate the position I and J so here if you look we require only three things here that is one is modified breadth first search algorithm and the concept of mask and the final state if you have understood all the three things then the problem becomes very easy in the next step it is a normal breadth first search algorithm but has slightly modified approach that we have here so if you have understood all the steps let's solve the problem and find the step-by-step approach the first thing is step-by-step approach the first thing is step-by-step approach the first thing is we'll find the number of keys why this is important because it is also given that we will not have c key without having the a key so if you just have two keys instead of the number ranging from 0 to 64 this number will get reduced to very short number that is you just require these two so the number can be just 0 and 1. so the second thing we'll be doing is we have to find the starting position in this problem in both the example the starting position was 0 comma 0 but this is not always the case the starting position can be enabled so we will we have to find the starting position also these are the first two steps that we'll be doing we'll be using a for Loop and we will iterate over all of the cells and we'll be finding both of them the next thing is we have to define a state class which will be having the configuration of keys and in tie and in G now just like a normal breadth first search algorithm we will be starting with a queue and we will add the initial State now this state actually makes sense how does it make sense 0 indicates that we don't have any case and I indicates the initial position of the person that we have then while the queue is not empty we will do the bridge first search algorithm we have four options one is we can travel in all the four direction if we hit a wall then we will be stopping we won't do any iteration further on that we take no action if we hit a wall we will continue with the next Loop and we will not do any operation but if we have a key what we will do is we will update the key configuration that is for example if you have found the c key this will change to 1 0. so that is the idea of masking that we'll be doing as soon as we find a key then however if we have found a lock the key ideas we will check this configuration for example you found d right capital D you found this lock but say you don't you have this number which is equal to two do you think we have the key D no right so if we don't have we just have to stop there why because we cannot continue further on the path that is the idea so we'll be checking the key configuration and we if we don't have the key configuration we will be stopping there then after we have visited the cell and we will be visiting the next cell and we will be adding it back to the queue so this is the idea and finally if we have all the keys with us so this number what it will become is 60 three once we have hit 63 we'll be stopping there is no need to go to the next cell that is the idea here and we'll be returning the number of steps if we don't achieve this 63 or where all the cells are one or if we just have two keys it is sufficient that we hit the number three once we have found all the case we will be stopping there and we'll be returning the number of steps I can understand this problem is a very tedious problem which requires a step-by-step approach which requires a step-by-step approach which requires a step-by-step approach this problem might be overwhelming but these require only three new things that we need to find if you have found this problem very difficult do consider going through these problems these are easy level problems and then the difficulty increases but we have these problems are using the same pattern or BFS to solve this problem if you have any difficulty please do join the telegram link that I have mentioned in the description you can ask me questions there and we will also be discussing the description and the solution to all this problem the telegram link I have mentioned in the description let's dive into the code without further Ado the defining here is a state which indicates the key configuration and the initial position and here if you look here we are finding the number of keys and the total and the starting point for example if you have Phi case this total case indicates we have five keys and this starting position we are finding it out the next thing is we are adding the state what does this state indicates is we don't have any key and this x comma Y is our starting position so it is 0 comma 0 we are saying that we don't have any keys and we are at the starting position 0 comma 0 then we are creating a queue with the particular State and we are adding that to the queue now if you look here we also have a has set indicating the visited we are adding this to the headset and what does this indicates is we have already visited the position 0 comma 0 with the key configuration zero so we will not be again coming to this cell without having any case but if this number is 5 can you come to this yes if the number is 5 again we can come to this so that is what this is indicating then we will iterate through the queue if we don't have any a case will be stopping uh if you don't have any elements in the queue we'll be stopping however if we have any cell in the queue what we will be doing here is we will travel in all the four Direction and we will get into the option the first option is will encounter evolve once we have encountered a wall it doesn't make sense to continue further so what we'll be doing is we will be going to the next Loop then again if we encounter a key we will be updating our key configuration what we are just doing here is we are updating that particular value say we found c key we are updating the third bit from the left to one that is what we are doing here that is the first thing if we have found a key then again if we have found a lock what we are doing here is we are trying to check the keys if we have that particular key or not for example we found D capital D we are checking if the bit at the fourth position is one or zero if it is equal to 1 we will be continuing if it is equal to 0 we will just go to the next Loop then again what is the next thing next condition is we should not have already visited the cell with that particular key configuration that is what we are checking here if we have not already visited this we can safely visit this and we can also add the configuration with the position to the queue and finally we are increasing the number of steps this is one tricky thing here what we are doing is instead of storing the number of steps like we did in the queue what we are just doing is we are iterating over all the elements in the queue at one step and finally updating the number of steps after each iteration and finally we will be returning steps if the current key configuration we have reached that is all of them are once if all of them are once we will be returning the number of steps if at all if it is not possible will be returning -1 thank you for will be returning -1 thank you for will be returning -1 thank you for watching the video please do like share and subscribe | Shortest Path to Get All Keys | image-overlap | You are given an `m x n` grid `grid` where:
* `'.'` is an empty cell.
* `'#'` is a wall.
* `'@'` is the starting point.
* Lowercase letters represent keys.
* Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
For some `1 <= k <= 6`, there is exactly one lowercase and one uppercase letter of the first `k` letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return _the lowest number of moves to acquire all keys_. If it is impossible, return `-1`.
**Example 1:**
**Input:** grid = \[ "@.a.. ", "###.# ", "b.A.B "\]
**Output:** 8
**Explanation:** Note that the goal is to obtain all the keys not to open all the locks.
**Example 2:**
**Input:** grid = \[ "@..aA ", "..B#. ", "....b "\]
**Output:** 6
**Example 3:**
**Input:** grid = \[ "@Aa "\]
**Output:** -1
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 30`
* `grid[i][j]` is either an English letter, `'.'`, `'#'`, or `'@'`.
* The number of keys in the grid is in the range `[1, 6]`.
* Each key in the grid is **unique**.
* Each key in the grid has a matching lock. | null | Array,Matrix | Medium | null |
318 | okay hi guys welcome to our channel code with sunny and today i am going to discuss one of the interesting problems of the lead code and the problem name is maximum product of word's length an index number is 318 and problem is categorized as the medium type note that i've already give it a like over here the design is quite simple this problem is actually an interesting problem and the reason is that we can build up the solution from the base level start thinking from the very deepest level and then we will build up to such uh build up our solution to such an extent that finally we have a good run time for this solution okay so talking about the problem statement we will first discuss this problem then look over the constraints and then we will together build it up the best solution of this problem and i will explain at every point of this video at every point of this solution why i have done this thing and now how we can approach to this idea okay so talking about the problem statement given a string array words return the maximum value of length of words of i into length of words of g and where the two words do not share the common letters if no such two words exist return zero note that the two words should not share the common letters it obviously states that words of i word of i and what of this should be distinct and the distinct is like we cannot have any character which is present in both of the words that is let's say a character c is present in the word of i then that character c should not be present in word of j otherwise we cannot just product their length and maximize our answer okay so if two words do not share in common letters then we need to consider these two words and if there are no such two words we have to return zero note that in your mind okay so talking about the examples i will discuss examples over here for now let's look over the constraints whether this constraint is going to help us or not you can see words length that is the size of this word array is going to be at most one thousand so can we have a of n square solution yes we can have a of n squared solution that is if we need to consider two words uh choose any two words from this words vector what's array we can do that you know of n square time but there is a problem over here and what is that problem what's the phi dot length is also 1 000 we cannot check the if we choose two words and if you want to check out the common letters if there exist any common character present in the both of the strings we cannot check that efficiently that is we can check that efficiently but he cannot do that with help of brute force and the reason is what's up y dot length is going up to thousand okay so i will explain how we are going to optimize this to have a good solution for now let us talk about the tags associated with this problem many people associate this problem with the tax or bit manipulation i don't consider this problem to be categorized into bit manipulation you can consider that but i don't and the reason is quite simple you can just build up a boolean vector and or you can say the boolean 2d vector and you can also solve this problem but that solution doesn't have a good runtime i will show that also but if you consider like using the uh operators like bitwise or you can have the good solution but categorizing this problem entirely into the bit manipulation i don't think so because this problem can be solved with the help of various methods okay so let's move on to understand this problem with the help of examples and we will together build up the best solution for this problem okay so let's move further okay so talking about the implementation that is we have to choose any two words let's say i have chosen this word and let's say i am choosing this another word you can see my first word is abc w and my second word is f o and you can see these two words are have the characters any of the characters is not matching in this that is if you choose any character from this string let's say character x can be any of them among a b c w this x is not present in this string also and if that happens for any two pair of the string chosen among this vector of strings i am going to just product of the length of this one abcw length has 4 and f 0 has length of 3 so my answer would be current answer is 12 so this can be our maximum answer but we need to check all the pairs you can easily see if my vector of strings has array of length n i can choose any two pairs any two distinct pair of the string in o of n square time how i am going to do that start i treating i from i equal to 0 up to i equal to n minus 1 and for every i start iterating g from i plus 1 to the n minus 1 so we will have any two pair of distinct strings and now comes the major role let's say i have the string s1 which is nothing but the words of i okay so let me complete it down the writing of this stuff what and i have another string s2 what is the words of j now we need to consider or we need to find if there exists a common character between these two strings or not how i am going to check that efficiently the first way that you the first method that strike in your mind is so for every character of this s1 try to check if there exists another the same character in s2 or not you can easily see if i will iterate in s1 the maximum length of s1 can go up to thousand so for every s character of s1 i will have to iterate up two thousand and in worst case i am talking about and in this h2 let's say i in worst case i also have to iterate up two thousand so my iteration goes up to 10 power 6 for if s1 and s2 for any one pair s1 and s2 and there are o of n square pa that is n square pairs almost so my time complexity goes up to o of n power 4 and what is the maximum value of n is 1000 and the maximum length of the string would be of thousand then my worst case iteration goes up to o of n square four and power four but you can easily see this n is thousand of n power four is like around ten power twelve iteration this will give us a tle verdict then how we can optimize our solution so this is going to be like very much important so let us talk about how we can optimize our checking that whether there exists a common character between s1 and s2 or not in o of one time note that i'm talking about o of one type so let's move further okay so we can just calculate the checking of whether there exists a common character between s1 and s2 or not know if one time by just some pre-calculation time by just some pre-calculation time by just some pre-calculation and what is that pre-calculation okay so and what is that pre-calculation okay so and what is that pre-calculation okay so talking about the pre-calculation talking about the pre-calculation talking about the pre-calculation for every strings this in the area of strings i have the length as n i'm going to maintain a 2d vector and 2d vector of what boolean vector so boolean vector of size n into 26 and you can easily see i will have 26 distinct characters for every string possible characters okay so i'm just going to mark it down if suppose there exists a character a in the ith string i am going to mark it out bool okay let's call it as matrix as mark then i'm going to mark it as mark of i'm talking about the if string that is if there exists a character a in the ith string i'm going to mark i of this character a as what true and does that makes any sense or does that help us in any possible way or not yes it is going to help us how it is going to help us suppose i am already pre-calculated pre-calculated pre-calculated this mark 2d vector which is for every ith string i am just going to mark it out if there exists some character c in this ayat string i am going to mark this mark of i of this character c as true okay and i have already done this entire precalculation now what i am going to do is suppose uh okay so i'm going to iterate in f and square time note that this precalculation has been done already that is for every string i'm going to do that for this and this will take us how much time watched case time if i will do this pre-calculation the if i will do this pre-calculation the if i will do this pre-calculation the worst case time is iterating for every string and then for every string's length and in worst case it will take off and square time now still it is good okay now talking about how i will maximize our answer now for every pair of strings in of n square time i'm going to do that again how i'm going to do that i start iterating from 0 to n minus 1 and then j from i plus 1 up to n minus 1 this will take us off n square time now i have a pair of strings s 1 and s 2 s 1 is words of i and s is words of j and i need to check whether there exists a common character between s1 and s2 or not this is going to be important how i am going to do that and this here comes the role of this mark 2d vector now this will take us of n square time now for every pair of strings i will iterate up to 26 times that is starting from character a up to the character z and for every character that is for s1 and s2 i will check if there exists a common character i will say no this these two pair of strings cannot make our answer and suppose in the case where i will check all the 26 characters and still i haven't find any common character then i can say yes i can make s1 and s2 as a pair which can be included in our answer so let us find their product of their lengths and let us maximize our answer with that length so this is our clue can this be run in a given time constant yes it can run so o of n squared will be the total number of iterations into for every pair i will have only the least amount of iterations which is 26 so my time complexity in this case would be of n square into 26 and this can be run under the given time constraints so this is one of the solution we can just optimize this solution with the help of bits and bits is bitwise or i'm going to also explain that so first of all let us move on to the code and then i will explain how this is going to work entirely so let's move further to the coding part so you can see i've already submitted some code this is the very first code and it takes a 112 ms then i will optimize this code with the help of bits then it takes 444 ms it doesn't matter so first let's look over this one okay so you can easily see i have taken my answer as initial and minimum answer is zero maximum answer is zero and it's worth size and i have a mark 2d vector and now i trade it in o of n square time because every string can have a maximum length of thousand and n can go up to maximum of thousand which is of n squared is the ten power six hydrogens uh ten plus six hydration around okay now for every character this is string i will have marked mark of i of that character as true and this will going to help us further to maximize our answer now for every i start iterating from g up to i plus 1 to this n and for every s1 and s2 check for check i check for the particular character and what is that particular distinct character amount that is we have we will have only 26 distinct characters i can check easily start iterating k from 0 to 26 for a particular ig what's a fine words of g and if there exists a common character matching character if there exist at least one character i cannot perform the multiplication of their lengths so i will go to the level h that is i will skip this part answer otherwise i will take maximize our answer and finally return our answer this will give us all test cases first now comes the role of this bitwise or and how it is going to help us okay so this has a runtime of 44 ms and there is not much difference over there what i have done is i have now make a integer vector of size only n so here is one benefit of memory we cannot have a 2d of size of memory of n into 26 here we will have only n size vector linear array okay so for every i have what i've done is for every character i have just done this one mark of i or this value and if you notice this value it is nothing but uh okay so how i can explain in the best possible way is suppose words of i j is character d okay so then d minus a is something like value equal to four or three i think b c d three okay so three then i will have performed the two power three one less than left shift operator is two power three then i will increment my mark of i with that value actually so if you notice down initially i have mark of i as 0 and if i will take the bitwise or with 2 power 3 which is 8 it now becomes 8 it means that if the binary representation will contain the 1 over here and similarly suppose again we will find out the c then binary representation contain 1 over here and again let's say we again find out the d then again this one would present over here how this is going to help us yes this is going to help us because if i will have some certain number like 0 1 2 3 error here i will have 2 power 3 and here i will have 2 part 2 then suppose if i will take the bitwise or like uh in this case i have taken this d then taken this c then my number would be like i'm just making my number with that bitwise or then my number would be incremented by 8 then it would be incremented by 4 so my number becomes 12 okay so i'm just explaining how this is going to help us in future suppose i have done this for all every string now coming back to this o of n square iteration now you can see the difference between the previous one and the current one is i am not iterating for 26 times i am just checking it out for mark of i and mark of j and if mark of i and mark of j has the bitwise and as 0 i can take the answer now here comes the important concept to understand that okay so first let me erase this stuff okay so suppose i have a string like a mark of i that is first step i have a string like d c b okay so if i will increment my mark of i s d c b to power three to power two and then to power one okay so if i will do that then you finally my answer would be mark if i incremented by eight four and two it would become fourteen and if you consider the value uh bitwise representation so 14 has the bit wide representation as 8 then 4 and then 2 and suppose here i have another string as only a then mark of 5 will be incremented by 2 power 0 then in that case i have the value as one and if you consider the bitwise representation of one here only i have one s over here and rest of all the positions as zero okay then now if you consider the bitwise and of all these two that is these two strings you can easily see the bits at the corresponding positions are different so i will have the bitwise and as zero and if that happens it means that i will have i will i won't have any common character then i can take our answer and suppose here i will string a character a and the character b also then mark of i would be incremented by that is position b would be 2 power 1 then i will have here as 1 then bitwise and will not come out to be zero then in that case uh this if a statement would not be executed my answer would not be maximized for the particular pair okay so this is all about the bitwise operations so if you have any doubts do let me know in the comments section of the video and i'll ask the viewers to like this video share this video and do subscribe to our youtube channel for latest updates thank you for watching this video | Maximum Product of Word Lengths | maximum-product-of-word-lengths | Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`.
**Example 1:**
**Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\]
**Output:** 16
**Explanation:** The two words can be "abcw ", "xtfn ".
**Example 2:**
**Input:** words = \[ "a ", "ab ", "abc ", "d ", "cd ", "bcd ", "abcd "\]
**Output:** 4
**Explanation:** The two words can be "ab ", "cd ".
**Example 3:**
**Input:** words = \[ "a ", "aa ", "aaa ", "aaaa "\]
**Output:** 0
**Explanation:** No such pair of words.
**Constraints:**
* `2 <= words.length <= 1000`
* `1 <= words[i].length <= 1000`
* `words[i]` consists only of lowercase English letters. | null | Array,String,Bit Manipulation | Medium | null |
316 | Hello to Ajay Hello everyone Diwakar Decide for uploading So today we are going to remove duplicate latest this question, see what to do on this question, you will get a string, on this there will be English small letters to work S English letters, okay I too that ABCD can be something like this, it is possible, it is fine and there will be no MT in it, this time it is good, okay, Papa, what to do, all the loops which are duplicates in it, have to be written only once, like here is the thing, it has come tight twice, so you can write B. Write only once Pallav, remove someone else, what can be the answers to this, if you consider this one, then BBC will become yours, if you consider this one, then yes baby, CM will go, okay idiots. If you write only once then both of these are the correct answers. What do you have to do among these two, which one comes first on the dictionary order, so this time this one comes first on the distributor, then this will be your answer. Okay, now for this, ABCD. Cancer happens, sometimes there is a letter in it, meaning everyone 's tree is latest, it is at its 's tree is latest, it is at its 's tree is latest, it is at its original place on the service, and it is also the smallest on the dictionary word, sometimes possible answer is not doing both of these possible by time, it is the smallest, let's see one more testis there if it is Some A B C D A B C If something like this happens here is from the duplicate courtyard here is also here also this is printed here CR here is the middle right here write all of you in What do you have to do either in the middle Take it or do it in the meantime, tomorrow I have to trouble someone, if you take it, now you have the choice for C too, now if I am this serial guy, he is the only guy, then he will definitely come, okay, both the future updates. There will be a password option and the second possible solution is this one, if you take the first one, then again change the second one to B, then CBI check and ABC four answers are being generated, how come there is no deletion in this and the original string. As in, exactly why should the order be there, that's why you have removed some friends. If we look at all these, this person is the first one on the dictionary order, so the answer to this is ABC question, so he was on the matching position and How can you clean it dry, let's see for example, if you were given this then it is Watson to find the answer, how is it that if I add one person, it will get cancer, just add one more person, N has happened. At this point, I am going to make some changes and here try your best to understand, now it is the name, I am focusing only on this, see here it was already like this, if you look at the revolver, the C which is there is big, like this right. If this ring is on some form of PSC, then on comparison, this guy comes first on the dictionary border, but how will we do this? See, my original question does not have any repetition of all the guys anywhere on the listing, so this is my answer. It is tight but if I can somehow achieve this from, then I will make a modal dictionary on the border. It is okay, I will make a small acting one. When can it happen? If there are one more questions of Ti after this one, then it is not necessary to keep C here. Ginger, it is not necessary to keep this Congress guy here, you can ignore him and delete him and keep this guy too, he will go to you for stars, okay, what if the guy before you was a big guy and he is after you. It is also coming here, so instead of keeping it here, you have an option to keep it later. Okay, so you can make this one leave home trick. Okay, let's go aside and let's see. Dear, I understand this. Look at this, if you have got on the input that how to increase the head of string chief, first of all you see, it is placed here also, okay, you said that it is Brian Sir, after that you saw that it has come, okay, I placed one here. The person who is previous to you is also at the most significant place. Right, the one who is close to the most significant place is bigger. It is on your comparison that if you come to his place, by whatever means, if he comes here to the most significant place. But if it becomes small, then the whole juice is a trick, it will become small, right, what are we going to do now, one will say, friend, make it big, I want to replace it, but when can we replace it, when we have the option to delete it. To do tight and use division one option when what will be its duty? After me, if you have come one more time after me who has come here, then delete this video, it is fine from here but if it is related to then I have done it. Till now my string has been made only like this, after this you came again but also a resting has come now on models from its if everyone ever sees tears then baby if you will unsolve this then given that if you keep doing this then this also It will be like this reporter but there is AB Smaller which we have also taken out tight, so now we will look at some more test cases and verify this idea, now our expert to solve this is this, look at the one before you, if it is very closed and the one after. I have come to you twice, 241, delete it will come later, okay, that's why let's see some more tests in it, okay and let's see how to interest, this is basically the string is mixed and this is its answer, let's see that one. Let's find out who came first. Okay, did you see Seema or did he come? When I came, what I saw was that he was kept at the most significant place. If I come in place of the one who is bigger, then he will be at the most significant place. Which will also be the overall whole string, after that any one comes here also any one comes in the whole string. If I compare these two, then this one is Ismail. Now what am I going to do, I will try it. How can we do a drop test of replacement when its There is an option not to come here, I saw that he is here too, he will come in the night, he can't do this right now, hey, six was removed and put more after Again I saw that it has come here, now what did it say, now it is in the middle at the most significant place. If I replace it and come, then the most significant will start at the most significant place. Okay, this is the dictionary order on these two comparisons. The guy is private first, don't even say that he will say that friend, if B has the option of not coming here, then he doesn't ask whether he can come here or not, he has come here once and came here that Babar D. K Bose has chosen to remove him from BSP, why would he take this, I have come to the most significant place, told C, ok, Siyag, here, first behind K, now it is f4, it is small, if you replace it and write C, then it is most significant place. After the muscle comes, your work means the string will increase so much on the revolver it will become greater, now you don't have to replace it in the next exercise D, I saw yours, this is a small closure, it is right, next 823 saw, man, this is a big closure, tight because we have it earlier also. It has come that one class ago we have the right so here C anyway does not come this famous cannot come that it has already come on my string that also told that pay attention here big so I have to do something it is written in it That Delhi was there before this, he will say that if there was a deep anywhere after me, he would have removed this guy, let's see here, he has come here once, after that he never came near this in terms of time. There is no option, once he has to come here, then he cannot delete this video. Okay, but right now, what option do I have, even after Delhi, C is there, you are bigger than me, can I delete it and instead of ah, if it gives me a message? Can't delete because what we had to do was to remove some elements on this and keep only the unique gun and it was to be small on the dictionary border. You cannot delete it and lose it. If you do ancient then let's see if B removed the pick and removed the sticker. So after one here, this one will be dropped, after this, the one which was on the most significant place here, will now be given a bigger one there, okay, so the work will have to be done, I was going to do the work here also, 3 has not been removed, saw the edit in it and Stopped here, that is chair, next is closed, learn again, one more friend of C has already come, seen my result in full bursting, and spring answer, this is done, ok, and answer, you also have the same logic, it is exactly the same, next. Let's see, this one is the one who came first, or you also put it, again he also came, it is written, the earth came before this one, you are becoming smaller, so there is no chance of it, either-or it was seen that no chance of it, either-or it was seen that no chance of it, either-or it was seen that before that C is fine and on top of that, the stars can come later here too, is it C or is there a service, then he said, you also go later as per your wish, here BB and K are so much, whenever I repeated that one Off clans had already come, ca n't repeat it again, add it ok, so much string was the same, here what I did was at the most significant place only, first replaced it and made the whole sting quota them in the first comparison but again It has come here before, don't repeat, now it has come again. Okay, this is my answer tight real. Gautam is looking very curious, so how to implement this and also we will have to do constancy and optimization because what can we check. I think that whoever wants to become big before me should also come after me, so in this place, we will have to optimize the opportunity, if you ca n't believe it, then let's see how we will do this, if it is okay, then let's see for stress, yes, how can we work? We are the people, before I show you what I had to do, my previous work was to find out whether this person has come after me or not. To do this work, I can do it by maintaining an account, how to add, what is the thing in this whole sting. One two three four has been increased like that here and here it is there twice that it has come once and the DB is once tight that now when I come here I saw that I have added it to my data structure and put it What did you give, but it is okay, as I saw, now it is being folded that there are 4 C's inside this much, I saw a guy here, so I will delete the message and make it three C's, now only three C's are there inside this much. One, two, three, okay, so if the account grade salary, which means, later on, let's see its one orange shade tight now, if how will we use it on us, then understand the yagya noose more correctly. I saw this of BJD, before that. A becomes elder, okay, if B had come here, then this degree holder would have become the first, okay, he would say, if C had come any time after me, then I can remove him from here, Knight APK will do it here. But even before coming, before entering, it will decide that the sequence is three, then here it is already three years old, already remove this guy, he will come later, okay, so here also, if you see that To sit here, he saw that the guy who is already here is in the middle, he is bigger than me, if I come in his place, then see that he will come first. He clarified the bakery incident that even though I was here twice, I But once I saw it, its control was not decreased, then here I saw it was decreased, now even then I came here only once, saw that it is grade one, now if I remove it, then it will remain there later also, there is one cockroach left in the middle. We can use this, now we will put it in it will not be proud, it will come later, it also came here and what will it do after this, so on, once there was account one, if love work is going to happen here, then it should throw its work. I will do it, I have come to the seat, okay, here you can see that the person tied is smaller than before, in which the revolver will remain small, if the guy comes then he is also small, it will remain okay, first he is small like a shoe, now next Stop Jhala or why don't anyone add me here because C serves here first ok so this is an existing case right I am not going to travel and chat ok what am I going to do some tests here And I am going to keep it, who will tell me which other bandhs have come here and which ones have not? Basically I said that if Rushdie keeps the spread, he will also tender the chair of terrorism, it is fine, this is how the third party will go now. There is a need to move ahead, then later, SC and D are already there, so I will make it brilliant for you, that this is Mahendru, through use metro route, it is not closed, so the pass is fine, there is no encroachment, it is already through. That account also has to be decreased. Now I have to work at both places. As soon as it comes, decrease the account of B. Look here, this element is bigger than 20. Okay, if B comes here, then put this on the graphical border. The cases have gone to sleep on the dictionary order, it will become smaller now, but the account of D here, seeing the lack of D here, I did not do this decree of open, earlier when I had done the ignore process, I had not done the dormant decree of that, okay. By the way, one part will see Gautam once again completed, it is okay with both of them that after the vaccine and such bread, if there is no D even once, then this guy cannot be replaced, this gun will have to stay here, what did the team do? He has checked that he has not come to this pimples means that he has not come to this yet, so he himself added it here and started from Ok ok, at the end he has come again with 13 regarding his account where I have not decided. Kiya Panwar GK It happened that earlier it was SITU so did not do anything Complete answer ABC D TV It became and writes in testis and will work from this year Had an affair here so status For whom do you look at old utensils What has to be done? First, here comes the strike where our sequence will be here, there is a requirement to maintain a frequency, so here one will be created to maintain everyone's frequency, okay, and here there will be something like president, he is the one with bullion, hey that. Told that there is Congress element in it and it is not there. Let's check the 26 11 Jhal. This is the first strike. This one is a frequency account, so the account is the principal and this one is the plant's Mukesh. Which Mukesh does this to me? Okay, then first of all. So I will have to make an account, right, but it has come here once, one must have been kept on one index, that is, one account is one, or as if there was no need to create it, like this, the web of quarter inch has come here twice, two has been kept on the previous index. Will be this is basically one Next 9 news room to index B meaning description box return meaning tooth index Okay so ABC don't get confused 1234 T's account is throw your account is one and a round also one here this extended and here But once we come to Tigriya shop, here all your existing cases are also passed, body shoulder is passed, so easy door is lying nearby at all these places. Okay, let's start our contribution from here. C is the first one, so the first one. What will work frequency - will do this What will work frequency - will do this What will work frequency - will do this decrease the account your t-shirt and decrease the account your t-shirt and decrease the account your t-shirt and fix it ok if there is already one here before now otherwise add this one check before shrinking the war from before this If Bigg Boss doesn't do then check if Justin case no 's jewelry crop meaning till now piece that a 's jewelry crop meaning till now piece that a 's jewelry crop meaning till now piece that a joker was not here then he started it and added himself someone he has already reached you means access made next Also, ignorance is the first task, decrease the account, that account has become one, still he did not do anything, he also did not keep it, he is going to add tubelight or war, he is going to add electricity, see, C is lying here, it was bigger than this, okay, so when He gets the element, what will he do, his account will be visible first, is it necessary to stay here, is it installed after me, will it come later also, is it okay, then the account can be directly registered in three more days or so, this guy will remove the same from here and Here I passed the account that it is no longer there, it is fine, so it worked, clicked on which account is it on Vikhroli, then popped it and cross marked it here too, submitted the form in existing. It has been said that here only the next person will be born, the work account has been made Yo, he will come here, checked that the person before me is younger than me, it was not a big stop, saw here, if you have done smart work, then lead the fans in this. There is something else to add and here I am the only person, or-or what will he do, I am the only person, or-or what will he do, I am the only person, or-or what will he do, I saw that he is lying here right now, he is waiting here, or he is here in the meeting, it will be visible, so come everyone. First the account hero will do, what will you do that he will pause, now he has this guy here, he is the same guy, after replacing this one, he will come here, then it will become overall smaller, right, he saw that the account quantity of one has been kept, meaning topic. If the effect doesn't stay here then that light can never come later and I have to keep it, here he has the option, so what did he do, he started the torch, added himself, turned towards me and sat down. Next guy did it like I saw that you have created an account first so do this initiative of Abhishek so now who cares for whom it will work, it will be seen that I have read before this was a small one ok so here he started cutting something Started the torch and shrunk it. Next monkey D. Created an account a few days ago thinking that these 200 chords will be done, went to center TV and added something. Before this, quota element is there, just given or first task, decrease the fonts. One is done what is the existing gas or but true then it will not work can't come here this is the next closed suppressed account decide the torch started adjusts here it will pass through the cords from Paul and now want to come here It's the day, show me friend, there is a big element before death, I will come in its place, it will become small, it will spring so much from its account, how much is the frequency of kids, saw there, zero means friend, that's why you will have to stay here, there is no choice, it is here only. You will have to go, okay, you cannot replace it now, you cannot replace it, you will come here anytime, okay, I have made SP for the night, will decrement the account, the work has started, the case of check unit is kept in the same petrol, which means it cannot be CI. Here it is not possible to make any combination, even if I ever look at my screen, I have recreated such an image, it was already broken here, so my string was already present by doing this, I have made a mistake. One, let's try this game, let's do the elements, Jhal Tikeswar, we had to complete two tasks, one comment on this and one existing case, now let's make them, Jhal was a text, an interior has been made, we will make this There is an array for lineage and a boolean type exists. Okay, then there was the principal MB. I have to write all the characters in the comment, so here I have to read it now, so the problem is that you have to see that the character on pregnancy is - A. I am going to do character on pregnancy is - A. I am going to do character on pregnancy is - A. I am going to do this basically it will work on the belief value of both of them and it will map it, for now Jaan will just map the distributors and will make one of the curtains or back of the screen 108 and on such a sequence it will go to the tree and dad 25cm app will do, ok, we are explaining this one also, on this video, I will also come to another video, that is the character of pregnancy - 1 man has is the character of pregnancy - 1 man has is the character of pregnancy - 1 man has increased, this will create my account alien life, you all will pass now. When we go to do our work, then we see the whole year, before that we had to delete the account, we had to do the story of united, after that we have to shorten it here, how to do it, the first task is to decrement the account, set the phone to united. You will see that the phone has been previewed, is it an integer value, so we have to send the one with the figure and we had to add ourselves at the last but everyone does that and after doing that, the character comes first in pregnancy - let me character comes first in pregnancy - let me character comes first in pregnancy - let me delete it as a hotspot. A that if this unit unites this guy character - from this unit unites this guy character - from this unit unites this guy character - from if it will be two then we will continue now okay this is also done handle account united and if you want to see the cat then standard size screen Roy Zero and Tech Dot Let's believe this pick a little at once that here if it already has pimples, it is okay and the new one that has come is smaller than both of these, we can't make a product out of these two, let's accept this or pick. But it is lying there is greater than Control Elements and T20, there should be a cigarette in the account, then in the account Advocate 1 - Editor 102 means if we remove it from here 1 - Editor 102 means if we remove it from here 1 - Editor 102 means if we remove it from here then it will not make any difference. Okay, so here I give it acid WhatsApp and because I If I remove it, I will have to keep it tight as it is existing, then I can type it Jhal that tractor remove that Jhal that exit remove - A pick when to people as per the that exit remove - A pick when to people as per the that exit remove - A pick when to people as per the above has been submitted that really the wound was there with the stand Adding the person has been done properly, still the work remains. Make this technical tip trick. If some are closed from the CD then Agyeya said, create a character carrier and start clicking on it. Which character will work? What is the answer? That new four students price beating equal to incident length minus one first of this greater link 120 phone okay this work is done now make it in standard from us and fit it okay it's done we will keep it like this a that compilation airline remove Two yes say yes but if I did not give the size then 16 that peer were not point symbol 20119 a wasted price this pic that one has become an account is pregnancy that vaccine is coming right now jhal previous song pics art of seventh test case looking at the field If there is loot and that Akshay loot is Acid DB and Acid DBC, well, I think one thing has gone wrong then what mistake have happened here, after adding it, I did not do the exit traffic rule. Beach - Fan equal to through. Here Beach - Fan equal to through. Here Beach - Fan equal to through. Here I am doing two repetitions by A. How is it working? It is getting prepared in this way. If you have learned something from this video then do like it or share it with your friends. Share if more people know what this video taught, then support Wedding so that we can keep making such videos. Thanks for watching. | Remove Duplicate Letters | remove-duplicate-letters | Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/) | Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i. | String,Stack,Greedy,Monotonic Stack | Medium | 2157 |
841 | welcome to march's leeco challenge today's problem is keys and rooms there are n rooms and you start in room zero each room has a distinct number in zero one two to n minus one and each room may have some keys to access the next room formally each room i has a list of keys room's eye and each key is an integer blah where key opens the door with number inside here so initially all the rooms are locked except for room zero and it says you can walk back and forth freely but that's kind of irrelevant because we don't really need to run into cycles here uh we're gonna return it true if and only if we entered every room so this is going to be a classic that prefers search problem we start at zero we know that for a fact and what we'll do is go down every path here we can see that we can go to room one and then room two and then room three and that would mean we visited every single room in here which would be four rooms here we see there's like the list now so we can start with visiting room one then we can room three but you can see here with zero we'll go back to zero right and you might see like a cycle going on with this problem there's no reason to ever visit a room that we've already visited because we're going to go through every single one in there anyway so we're not going to get any new information so we'll have to have some sort of hash to keep track of every room that we visited if we've already visited this room then we don't need to continue at the very end what we can do is just look at our length of the hash and say if it's the same length as the number of rooms that mean that means we visited every single room otherwise we haven't so we can return to false so what i'll do is write a depth first search function and what we'll do is pass in the room which is going to be an integer first thing we'll do is add this room to some sort of hash so i'll call this visited and we're going to make it a set you can make it a dictionary if you want but i will make a set so we'll visit this room now for all the rooms inside or i should say keys inside of rooms room we want to do a different search so what we'll do is visit every single room site here but make sure that we haven't visited so if i not in visited then we will continue our debt first search otherwise we'll just continue and at the end here we'll call our debt for search starting with room 0 and we could just return whether the length of visited equals the length of the rooms so what i'll do is test both of these here so first one should be true and the second one should be false and it is so let's go and submit it and accept it there we go so time complexity wise it's all then because we'll be visiting every room at worst case we'll visit every room just one time and we have a set here so we have to have oven space as well that's it thanks for watching my channel remember do not trust me i know nothing | Keys and Rooms | shortest-distance-to-a-character | There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_.
**Example 1:**
**Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\]
**Output:** true
**Explanation:**
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
**Example 2:**
**Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\]
**Output:** false
**Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room.
**Constraints:**
* `n == rooms.length`
* `2 <= n <= 1000`
* `0 <= rooms[i].length <= 1000`
* `1 <= sum(rooms[i].length) <= 3000`
* `0 <= rooms[i][j] < n`
* All the values of `rooms[i]` are **unique**. | null | Array,Two Pointers,String | Easy | null |
209 | okay so this is Chung here again so I'm doing the lead called problems well since I'm also learning there are those algorithms from bit code so and today so we'll be doing this problem 2:09 the minimum size sub array some 2:09 the minimum size sub array some 2:09 the minimum size sub array some okay so let's take a look at the description first so you're given a target positive integer s and n positive numbers number of integers you need to get the minimum length of a contiguous sub array which the sum it's not basically it's not smaller than us if there isn't one return 0 instead right so for example here so the target cell target number is 7 so which means we need to find a sub array that we need to find all the sub arrays that's the some it's greater than 7 and we'll need to find among those sub arrays we need to find the minimum length of those arrays right for example this one here so 2 here because go you're starting from 2 this one the case to 3 times 5 it's not quantified further it for the result Y is not 4 so this is a 2 5 6 and then 8 right when it wins 8 and then if this is a quantified array well so what's the length off there this is a 4 right but then there is a like a smaller one right so that's what we have here so 4 plus 3 is also greater than not less than seven so but the length is two which is smaller than the four so and we'll get the minimum one okay so what should we do here so the idea here is to use a two pointer right so base what it does is the pointer one is so at the beginning the pointer one and the to the left pointer and the right pointer both of them were pointing to this to the first array right that's very the first element and then the right pointer will keep going and going until the running sum yeah we also need to keep a rhenium some variables to keep the current sum right so when it's reached two three so at the beginning the sums - and winds at the beginning the sums - and winds at the beginning the sums - and winds reach two three the sum is five and then skip keep going until the sum is it's greater not less than ten seven so it's five six eight right winds reach - it's five six eight right winds reach - it's five six eight right winds reach - here this is the left is it at the right the left pointer and right - right the left pointer and right - right the left pointer and right - pointer so once you have once the running sum is greater than then the target will try to shrink move this lab pointer towards the right pointer until that the running sum is it's not greater than then target anymore then we know that's the minimum length we currently have yeah and then once we cannot move after we can optimum in lab pointer then we just keep moving the right pointer forward until we reach the end of the sub-array I'm sorry until reach the sub-array I'm sorry until reach the sub-array I'm sorry until reach the end of the red and then we just get the minimum value from it okay so what do we do here all right real quick mmm first let's check let's do a quick check we check if the we check if there's an if it is a valid there's a valid number valid result if there isn't we just return zero so what do we check if the sum if the ass is greater than the sum of nums right so what does this mean it means the total number of sums there won't be any sum there won't be any after adding all the numbers in the Sun in the numbers array it's still smaller than the nest then they won't there isn't any sub arrays that can be greater than the nests yes we can conclude to that we can get that result because it says here there's n positive integers right so we know it will be it will never go down so but if this is like there's like some nuns there's some negative numbers in it they will be gonna they're gonna be harder I think I believe there's another problem which is hard for that and then we can yeah we can discuss about that later on so back here so when this is not valid when the total sum still smaller than then I target we just return zero right we know it's it we won't get any sub arrays and here so now we're gonna define two pointers like what we discussed left and right out there both which both starts from zero and then we're gonna have a running sum here right to keep current sum and also of course the result right the result you know since we're getting the smallest length of sub-array so indeed smallest length of sub-array so indeed smallest length of sub-array so indeed every time when we see a lot with getting the smallest number of something we already setup the result to the maximum number right that's the small trade here small next size here so that every time we went to a minimum of the result corner result will always get a smaller number so now what do we loop right so basically we just keep moving the right pointer okay let's do a the length here we come to a length of that of the neck nums here what the right pointer is smaller than ain't right we just keep doing moving it and then push to a right plot plus one here to the end so what do we just keep adding the current numbers without running some here first right and while it's running some right what is running some is it's greater or equals to the target right then we know it's a valid sub array right there gonna be a value somewhere so what do we just keep updating this results it's a minimum right result right from the current pointer which is right - left current pointer which is right - left current pointer which is right - left right - left and the class one right - left and the class one right - left and the class one right because it's a length it's not it's a line so we need to plus one in the end so we keep doing it once every time we every time when we update this result and we all try to move the left pointer forward right we keep doing it until the running sum is less than s then we stop right after the move if we stopped we just move try to keep moving the right pointer and in the end we just return the result yeah I believe that's pretty much it is oh yeah sorry my bad yeah okay I'm sorry so once we move the every time when we move the left pointer we also need to substract that's number from the running sum so we can have the updated running sum for the recurrent sub-array some sum for the recurrent sub-array some sum for the recurrent sub-array some write the noms left pointer ringing son let's see it's the index sorry it's not it's in there it's not the number yeah it's hard to type in while you were talking yeah cool so again so the concept is we keep two pointers at laughing right and then we keep a running sum every time when we keep adding to the we every time when the right pointer moves right we just keep adding this the current value is current value into this running sum and if and then we will try to shrink the array size right the race is once every time we try to shrink the result we resize will update this the current length to the result and then we just shrink the array by subtracting the last element the current lapped element from running sum and then we just move the left pointer and then once this is done we just keep moving through it point forward until you reach the end out of the way and then we just return the final result cool okay I think that's it all right thank you guys I think woah yeah please if you guys have any comments please let them let me know and I will definitely improve my explanations yeah while I'm doing this like the videos here and also my English yeah I hope so cool alright thank you bye | Minimum Size Subarray Sum | minimum-size-subarray-sum | Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`. | null | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 76,325,718,1776,2211,2329 |
441 | Jai Hind Is Taylor Am Going To Discuss A Program In Question Orange In Points To Problem Statement Has Given A Total Of And Coins Which Have To Arrange Next Year's Shape Wear Every K Through Must Have Exactly Coins Sweet Means First Law Must Have One Coin Control must have two coins through must have three boys on switch off to find the total number of please subscribe and for this problem noida 32bit signin subscribe and know it's a strip of hinge sticker 100 first to have one question wear left with point from control Hetu Coins No Way Left With To Is This Affair - 3rd Year Old Youth Choir Status This Affair - 3rd Year Old Youth Choir Status This Affair - 3rd Year Old Youth Choir Status To 9 Through Must Have Three Points But Were Left With Only To Pose We Have Two States Which Can Only Be Used To Pose Now In This Example Which Can Only From To Roads Which Must Have Exactly Coins First Floor And Se Control Through Effects Of Staircase Rose It's Difficult But Were Left With Two Poses That's Why It Is Not Included Feature Hostpot S2 Name Let's Move To The Second Examples In Second Example With d13 Stars Then And Now Let's And Inch Imphal Staircase Rose First To Have One Coin Se Control How To Have Two Coins Third Romer Stayfree Pause So Let's Account Dam 325 06 Veer With Only To Pause Clear And Through Must Have For Ones But Were Left With Two Points On Wick In Thy Used Only Two pauses will sleep Example of a good to switch successful Staircase Russia must have exactly tired This number's gestures must have exactly coins first to have one coin to control of two point third which is ₹3000 hotspot turn which is ₹3000 hotspot turn which is ₹3000 hotspot turn 265 The Problem Statement and Now Let's Discuss multiple approach to solve this problem in which there is solution and let's start with the one used for this approach to solve the problems 2002 This Problem What's the Meaning of Vibration Let's Understand the Example Subscribe and Complaints from This Point Subscribe 151 We Need to To Inform And They Will Drop Policy Note Subscribe Mid Day Meal Scandal Now We Are Third Oh They Can Only From To Complete Daily 100 To Who Is The Short Notes On Using 10110 Problem Share Quotes For 1000 First Edition Of The Valley Of Giving - 90 Se Start from One Where Nationalized in One Variable Account Within There Value 181 Available Accounts and Live with Number of Points 8083 More Benefits 10.02 Difficult in the Road Subscribe 10.02 Difficult in the Road Subscribe 10.02 Difficult in the Road Subscribe Blue Hai Instant Relief Account and When They Came on Top 10 Look Play Return Account – One Top 10 Look Play Return Account – One Top 10 Look Play Return Account – One Boy Dress Account - One All Posts In Boy Dress Account - One All Posts In Boy Dress Account - One All Posts In First Edition Divya Account Is One And Not Distract One From A Date And Were Left With For A New Way Of NH-24 NH109 Left With For A New Way Of NH-24 NH109 Left With For A New Way Of NH-24 NH109 Swimming Develop Account For Next Question Divya Contest U0 Side Reaction Subscribe Cr Should Know The Value of 1000 90 updates 12345 subscribe this one 90 Switch off the return minus one can only from two subscribe from five lines to judge approach to solve this problem and now let's see how they cannot optimize and solution that in appearance approach vihar solve this Problem Using A Positive Vibration So We Can Improve Good Bye Using Binary Search Samadhi Is The Time Complexity While Using Binary Search Suve In This Problem Vihar To Find Number Of Complete Rosary Can Form From Being Description Coin Sulabh That One Total Number Of Science And Use Cross Way Can Form Without This Number Before Using Binary Search Let's Understand One Important Point Shyam This Problem Give Every Day Through Must Have Exactly What Means Subscribe Control Must Have To Go Through Them And Furious Videos For Kids Room Must Have At Least K * Key Plus One Buy Room Must Have At Least K * Key Plus One Buy Room Must Have At Least K * Key Plus One Buy Two Points 500 Yards Zameen Se Is Software Talking About The Thru Sotu Completely From Firoz Needed At Least Six Scars Not Understand Wikinews Binary Search Tree To Solve This Problem Subscribe Medium Plate Form Using Subscribe And Start Earning Celebs Caught And Subscribe And Share Subscribe toe's ninth run life while the value of stars in equal two and software calculate slowly and so when they first calculated using one and five from the best 30 duets calculate currents of mom the three Russians completely it means required number of questions so widgets here and Compare This Current Time Shrink To Equal To And A Plus 2 And 9 Dowry 66 Definitely This Condition Is Not True Is Develop Current Committee Will Give This Also Updates Reviews And Minus One Subscribe And Relief Operations And Subscribe China Also Calculate Demand And Scientific Calculator May Start With Steve Waugh And This Is Divine After And S2 Solitaire Is Dynasty Growth Leaf Withron In All Its Calculate Current Even Happiness Divine Current Time Also One Log In This Condition Is Not True Knowledge Subscribe Leaf 910 Statement And Develop Start With J Plus One So Let's Move valley of mid valley and the to main self and development s 2nd value of current time automatically in 200 again this condition is not true and develop current prosperity belief and 90 start update to a free end in next hydration with serious condition and belief chart is equal to and no one can stop this flu and will return divine faith and belief and as later mishu decode sauvir valley of the well and with it they can only for class 5th 210 how they can solve this problem using binary search and now let's talk About Cyber Space Complex It's Time Complexity Asola Gain And Space Complexities We Are Using Only On Students Were Using Space Only For These Vegetables Should Accept For This Video Tutorial And You Will Have Discussed Two Approaches To Solve This Problem Is No Any Rate Approach You Can Leave Your Comment For The Other Student Of Peoples For Watching This Video Advantage Me Aadhi-Adhuri Approach Is Sharing Comment Aadhi-Adhuri Approach Is Sharing Comment Aadhi-Adhuri Approach Is Sharing Comment Section So Thanks For Watching This Video And Don't Forget To Like This Video | Arranging Coins | arranging-coins | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** Because the 3rd row is incomplete, we return 2.
**Example 2:**
**Input:** n = 8
**Output:** 3
**Explanation:** Because the 4th row is incomplete, we return 3.
**Constraints:**
* `1 <= n <= 231 - 1` | null | Math,Binary Search | Easy | null |
137 | Hello everyone welcome back to my channel once again so here we are going to talk about today's daily problem and today's question is single number 137, good question if you want to understand your optimization because in this question you Whatever is being asked, you can do it very easily, within the required complexity, right, but here it has given you a kind of challenge that you have to do exactly what is required in linear time complexity, okay. We will see, in this way we will also discuss that where each element is three times A, the frequency of each one is three except one, there is one element whose efficiency is only one and only one, the frequency of all the other elements is and you The same single element has to be removed. Okay, if you have read this much then you must have understood it in a simple way. We have put the 'You Can See' update in the map and We have put the 'You Can See' update in the map and We have put the 'You Can See' update in the map and from there we have checked the frequency of update here. Vacancy notification but you read this challenge you cool implementation with liner and time is ok and using one n constant extra space so if you are going on the map then your if we talk about space complexity then bigof n be And in this, time complexity will be bigo of logging in, right, so your challenge is that your standard has been set in this that you have to get rich till there, then I am not there, you may be a little behind, the solution is not wrong, this I think will also be accepted because 3 * There is 10.5 also be accepted because 3 * There is 10.5 also be accepted because 3 * There is 10.5 in this, these people will be the solution to this, if this is not what should have been your best solution, then you can take it to the level if you want, now it is obvious that if you are watching this video, then I think. You must have done this solution easily. You have to focus on the next solution only. You want to know. Okay, so what we have is that now we have to reduce both of them. Okay, we need some solution like this. Which is to reduce both of them right, then after this you have another one which comes to mind, if the map is taking your in, then we have one of those order map, if we do it with not map, then the average time complexity of this if we If you see, it becomes Big of N because this is the lion's pay, Mapcha reduces your tree, Red Bloody pays you, internally, so in this you will be logged in. For these operations, your big will be opened here, where we will update. Will do and there again the same thing is there again note equal two three then return but one thing if you see your time complexity you have improved but space complexity is big of n this is not an improvement ok I mark it with rate this is Bad, this is bad and here this is also bad. If it looks like this, then it is okay. So this space complexity is telling that in your solution, there should be only and only variable kid off, in this way, it should not be of container type. It is okay to do this, after this, first I am telling about the color approach. Some people think this because here I have given that each element is three times. Okay, so let me tell you again about the color approach. Why is this color so I felt that maybe it is more important to discuss, only we should not discuss the best approach, optimal approach, even the color, if you see it in the form of a common question or not, then this one fits in this question like this, then we probably think about it. Also we should discuss so what is here that you have each element if I write It would be absolutely wrong, how do I look now, what did I do in this date, how what would happen is by taking three and three mangoes from here and this x + y3 * taking three and three mangoes from here and this x + y3 * Dog zero, but if you look, you can see like this, let's name here zero, then you are also going, just what is this answer, is this correct, will it not be zero, not possible, okay, it is wrong, so wherever in AL, in this way You are doing it and 22. When your method is done, then you must have thought about this solution in a big way, then you will understand why it is going wrong and there may be other reasons but I simply understood this in a simple way and I thought Now let's talk, okay, but where we will talk inside the big one, we will stop and leave, so if you look at the number I have, like I will take six here, now on six, if we Here we have changed the beat, here we see the frequency of numbers. Yes, here we have seen all the frequency of numbers. Now we will see the frequency of beat, why because you must have seen it in the question, Tu is 31 - seen it in the question, Tu is 31 - seen it in the question, Tu is 31 - 1, so its highest which is This number is up to 31 beats which is your like right, so if we have the same thing as map and order map sir, you are looking at something, now to store the frequency, we will do it in a similar way which is where Store the frequency of the beat, what will happen if we have only 31 or 32. Now let's be safe, pick one of size 32. I need a container of size 32, which will do the liner time. If yours is less here, then store the vacancy in the liner time with me. Now. What will happen to it in this way? 32 * Bigu of N which is What will happen to it in this way? 32 * Bigu of N which is What will happen to it in this way? 32 * Bigu of N which is almost your liner, Big of One, so you can do a vector for it, One because it is absolutely constant time, less memory and is not a big size, so we We can keep it, so if we approach it with pause, then both of us are getting rich. Now we understand how that approach will give the right answer and what will be its logic. So if we talk about 6, then if we talk about 6. See Beat Vijay, in the beginning we have put some zeros, after that 4 2 6, this is how your beat will be formed. Now six, three times, A, okay, three times, A, what will happen, the beat is set here, okay, as we are talking. If this video is set, then this is also set here, this is also set, so when it is set, just this approach is fine, something similar to this one Pro, here we will talk about what will happen that here Whatever number of frequency it will be, it is always in multiple of 3. If it is of three, if it is set in any number, then it will come three times. Okay, it will come three times. If that number is the answer number, sorry, then of the second beat. Whichever frequency will be that percentage, now you will three and where you will get one less, right here on this beat, the verse of the answer, video talk about you, that bit is the set of the answer, here is its set beat, so when it is set, then the answer is on this beat. Because of this, the value of the answer will be tu di power i will increase. You know how to do simple conversion. If we have given you then we will tell you how to convert the numbers or how to bring the numbers into beat. You will understand this thing. It may be that we do not discuss this thing much, so we are the ones who are talking that if it is set then you have given the power, the answer will be its contribution, we do not have the answer, it is not even that number but we will give it the beat. We are catching the beat one by one. At which position is the set beat? The number of the set beat is more than a multiple of three. You will get only one more. This is fixed. You do not need to check anything else. There are two and zero and there is no need to apply it again, it is confirmed according to your logic that either if you do three percent then zero will come or one will come, how come there is no one for you, then we will check the same thing, okay and you Whenever we get one, we will enter the answer plus single tu de power here and finally when we do 32 beats, our total which will be the value in the answer will be calculated, this thing will go to the calculator, is it okay or not, this is a little If it is a different task, then we will talk about it first. You must have understood it. If you haven't understood then repeat it a little later. Otherwise, if it is clear then you can ask on the Discord server i.e. clear then you can ask on the Discord server i.e. clear then you can ask on the Discord server i.e. in the comment box below. Now let's talk. How to check whether the rectangle beat of a number is set or not? So, we have the probability here that the probability is zero and whatever is one, we want to check whether it is zero by going here, okay, here it will be zero. Our answer is also some zeros. Okay, if our answer is one then also our answer is some one. If you give zero then it will be zero. If you give one along with zero then it will be zero here. If you give zero along with one then your sorry. If you give zero along with one then it will be zero. If we are talking about and then one with one will give zero. What we are keeping at the top is the same thing that I want at the bottom. See, this is from here. Now if you see, there is one at the top, there is a zero, but here it makes a difference, right basically what is the point whether you have zero at the top or There is one, if there is one seat below, this one's condition is fine, look at this one, it is matching yours, so if we set the number here as a temporary number, mother lo, we have made it on this beat, take me out on the G beat and put it in the number With the life number, if we take more, then it is set whether I will get this or not, then we can do this thing, so basically we will take more with the life number, now here with the life number, if we take more. If this one is giving minset and if it is set then frequency update vacancy will be updated, after that we have already seen further, okay so now each and every point, I think must have been clear, complete step by step. Let us understand once again what we will do, we will trade each number, okay, we will trade all the bits till its 32 beats, then we will check each beat of each number, whether it is set to the other side or not. So the frequency will be updated and finally after updating all the videos of all the numbers, we will check that this is how much more than the multiple of 3 you are getting, where percent three is equal to one, we will add our value in the answer. And finally, in this way, the answer calculator is easy, so I have kept Bitcoin, your account is fine, Bitcoin is all zeros and now we are going to the number, going to all the beats and you will get this 22 with the power I and taken the value. Where Nautical Tu Zero means what I said, what was our frequency update in the step, then the frequency in Bitcoin got updated, after that we did the answer from zero or even keep it above and after that it is okay on every beat. No, it means that the beat of the answer is set. Okay, so the answer computer can be done in different ways here, whatever is your operation, is it wrong, I have told you wrong, this thing is also correct, I thought that exactly the steps of the approach. We have coded it step by step, so I have kept it and it is coded in a good way, if you understand it, then it is not good, then it will be right for you, okay, so see you in the next video, Tilon by this. keep this much in the video | 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 |
412 | hi this is topher with the lonely dash and in this leap code video we're going to go over how to solve the classic question fizzbuzz given an integer n return a string array called answer that is singly indexed and where the index if the index is divisible by both three and five we're going to put the string fizzbuzz into our answer string array if the index is only divisible by three we're going to put the string fizz into the answer and then if it's divisible only by five we're going to take the string buzz and put that into answer and if none of the above conditions are true so if we have an index that is not divisible by three by five or by both three and five we're going to take the string of that index and put it into our answer string array so what is that really going to look like well let's use an example here i'll drag up there we go n 15. so if we were given an integer n and rn is 15 we're going to need to figure out how to index n and an index singly indexed anyway is the number one and all of the integers going up to of course n so our index is going to be 1 through 15 in this case now we're also going to need to know what our output is so our input is 15 because that's what n is and our output is going to be this string array so our string array we're just going to kind of well come down here and it's going to be blank at least at first so it's going to look a bit like this now this is very basic it's what it'll look like in python but for our purposes today it's gonna do now we're gonna go through each one of our indices here just like the questions asked and make a determination if one of these meets one of these conditions so let's start with number one it's the first so number one does one divisible by three and five no is it divisible by three of course not is it visible by five no so it is one of those indices that don't fit any of the above conditions so we're going to take that number one and we're going to add it into our string array as a string so we'll put quotes around number one and it's there now similarly same thing will be number two because it's not divisible by three or five so one two and now we're moving to number three does the number three index meet any of these conditions well it's divisible by three but not by five so it does not meet this condition we're gonna go to the second condition is it divisible by three yes so instead of taking this three and sticking it into our answer string array it's gonna be replaced with the word fizz or i'm sorry the string fizz now four is the next one it's not divisible by three or five is the next one it is divisible by five but not by three so if we look up at our conditions here if our index i is divisible by 5 we're going to put in the string buzz and so on and so forth until we get to the very end and that is going to look a bit like this so our final answer after going through all of our singly indexed parts of n is going to look like this one two fizz fourth buzz fizz seven eight fizz buzz 11 fizz 1314 and finally we get to 15 which is the only number that we have of our index of n that meets the condition that it is divisible both by 3 and 5 and so we put in the string fizzbuzz now let's talk about edge cases when you're reading this question a question of edge cases will come up and you'll ask yourself oh well what input could kind of mess me up well could the input be negative because that could kind of mess us up we look over here at our constraints box and we notice that n is going to be equal to or greater than one which means it's not going to be negative we could also ask ourselves hey uh what if this is a string instead of an integer well that can't be the case because the question tells us specifically that it's going to be an integer so in all honesty i don't see any edge cases here that could mess up our question we know it's going to be an integer we know it's going to be positive and that will work in every one of our cases that we've talked about so let's move on to some pseudo code given an integer n return a string array answer that is singly indexed well let's start because we know that our output is going to be a string array we need to first create an empty string array or a list if you're thinking in python so that's the first thing we're going to do second we're going to have to figure out um how to index our n so for each of n we're going to do something and in our case we are going to add the string fizz buzz add the string fizzbuzz if it's divisible by three and five okay so we're looking over here and basically we are just taking each one of these conditions and adding a line so if i is divisible by three and five fizzbuzz add fizzbuzz i don't know why i put a comma there add fizzbuzz if divisible by three and five if it's not let's see add the word fizz if divisible by three add the string buzz if it's divisible by five and then of course add a string i basically if none of the above and that's all we really need to do in order to solve the problem except thirdly we're going to have to return the string array because we need to have an actual output in order to solve the problem and that is the basics of the pseudo code let's get to writing code okay now you'll see that i have copy and pasted our pseudo code directly into the python 3 emulator of the lead code website there's a couple of different ways i like to write my code based off of my pseudo code the first way is writing a bunch of code and then tabbing over the pseudocode so it's next to the code and the other way i like to do it is just by writing a bunch of code above and then you can kind of do a comparison above and below of what our pseudocode does for our code for purposes of today i'm going to do it above our code so let's follow along first we need to create an empty string array in python that's really easy we know that the question tells us the name of our string array is going to be answer so answer equals and an empty list so that takes care of the first thing second for each index of n now when we are doing the indexes uh in python we use the range function so for i in range one comma n plus one so the range uh and by i said function but it's really a method the range method in python gives two arguments the first argument where we have our number one is where we want our range to start the second argument is not inclusive uh and it is the ending point so in our example earlier where we were talking about n equals 15 and we want the numbers 1 through 15 if we just left it at 1 through n because n is not inclusive it would not include the number 15. we want it to include the number 15 so we have to add 1. so this represents the number 16 that way since it's not inclusive it goes all the way up to 15. so first create an empty string second for each index of n which is for each i in range of one through n plus one we need to add fizz buzz if divisible by three and five so if our index modulo 3 equals zero and index modulo 5 equals zero and that's what we're looking for here so our modulo is kind of like a dividing operator but slightly different it says if i divided by 3 has no remainder well it just says there's no remainder so that means it is evenly divided by 3 therefore it is a divisor of three or a divider of three ah i gotta figure out how to say that properly but these two represent that each of these indices are divided by these two numbers three and five so if that's the case we are going to append the word fizz buzz to answer that just adds it to answer so if these conditions are met we're adding fizzbuzz to our answer else if i or our index modulo 3 equals zero we're going to append the string fizz to answer so if it's not this well else what if it is actually divided by three or divided divisible by three then we're going to take fizz and put it into our answer well what if else if l if i modulo 5 equals 0 we are going to append the string buzz to answer and then if n our index is not divisible by three and five if it's not divisible by three and then it's also not divisible by five that's everything else so we are going to append a string version of our index and that's what the str method does and that's it we're basically done writing the code with the exception that we need to return the answer so we're going to return our array which is answer and that ends up our third return the string array so let's test it let's see if all of this works out fine we'll hit run code bam it does work 45 milliseconds and that's it that's the basics of the code writing in python for fizzbuzz you | Fizz Buzz | fizz-buzz | Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_:
* `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`.
* `answer[i] == "Fizz "` if `i` is divisible by `3`.
* `answer[i] == "Buzz "` if `i` is divisible by `5`.
* `answer[i] == i` (as a string) if none of the above conditions are true.
**Example 1:**
**Input:** n = 3
**Output:** \["1","2","Fizz"\]
**Example 2:**
**Input:** n = 5
**Output:** \["1","2","Fizz","4","Buzz"\]
**Example 3:**
**Input:** n = 15
**Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\]
**Constraints:**
* `1 <= n <= 104` | null | Math,String,Simulation | Easy | 1316 |
1,700 | welcome back to my channel and greetings of the day we have an interesting problem to solve ahead today we are going to solve it called Problem 1700 using Java the challenge is to solve and figure out number of students who are unable to eat lunch but area offers two types of sun pictures circular and square they are represented as zero and one in our implementation the students are in queue and they could pick either square or circular circles the sandwiches are placed in a stock order the students the front of the queue prefers to sign it at top of the stack they'll take it otherwise they go and stand the back of the queue or instead wait the condition here is they take only the sandwich at top of the stack this continues on to large students write rated and take top sandwich the top 10 which is not consumed by any students then number of students are unable to eat would increase the sample example given here two of them and now we get into action here in this problem we are expected to find the number of students who are unable to eat the sandwich of the stack of sandwiches that is given there are two types of sandwiches and the student is expected to pick one of them after before week 12 went to coding this problem we take a look into the organization of the students and standards in this type let's take this exam we have sandwiches in the following order of the stack so the first sandwiches of one and zero one and students are in the following queue students have a condition when they arrive at the queue expected to pick up only the first stand which is there on top of this track if it doesn't match their fish they don't pick up they waited for the order of the sandwich that comes on top of the stack now let's talk through this example in an iterative fashion say we are going to Loop sandwiches available in the stack so with the first student arrives he or she likes to bed one Savage is it available here on top of the stack yes the student perfect and we Mark student as so we just removed from the stack here as well next to student likes to have sandwich one on the top is zero so we skip the student s now student wants to have one but on the stock of the stack is zero you skip the student also this student wants zero gets there on above the stack we add student sandwich we remove the sandwich Mark the students date and will remove it from here next may I trade through the sandwich it's now zero on top of this track so this student doesn't want a student doesn't want that not the student matches with the first one so be removed so had this one next we have three sandwiches in the stack zero one button stack of zero here none of these totals WhatsApp so they are unable to eat so finally the result will be number of students unable to eat let's just do the same iteration here write it through these sandwiches on top of this track is zero so the student can take it student can't take it student could take it so we removed here that student has taken and we remove the subjects next one is one on top of the stack to the store that I take it the remote here and so we remove the sandwich from the fabric stack next on top of this stack is zero the student can't take it but the student can take it so be removed as well as some next we are left with one on top of this stack and we have only one student so we remove both of them and the number of students who actually cannot eat yes okay with this background we go ahead and implement our solution let's initialize account of number of students who prefer to eat type of search counters for number of two times each type of shot and type zero it will initially zero we need to fight out from the RS that we have here in and type one equal to save okay I need to iterate through the students and find out how many students want to eat type zero sandwich and how many students want to type one study so find out count of students who wants to eat if of sandwich eat a particular type for and I equal to zero students length it shouldn't wants to eat I'm General sandwich and we say that channel increment yes it would be like one kind of sandwiches the student will prefer to eat and with increment to on top of one we will need to keep track of number of students who are unable to eat so keep track the students unable to eat we Define an integer actually we can either initialize it to zero and keep incremented as students consume the sandwich or we keep this to the maximum length of students and then keep decrementing it as the students consume the sandwich so we'll go with the other way of decrementing ask the student consumes it and then we start iterating through the sandwiches across every store all right through the sandwiches I'll check if shouldn't is able to consume that the type of sandwich is of course going to be type 0 and type 1 we call it this one as circular sandwich and we call this a square such foreign the one that is there on top of the stack of course that's the condition the student has we'll pull out the sandwich on top of the stack into a sandwich and use this variable to see if the student prefers to take it if sandwich yeah it's of type zero and number of students to consume it is also greater than zero or if it is of type 1 and number of assurance of type 1 is also greater than zero then we iterate through the students and see if they are able to concept so if we were titrate through the students list check that there is at least one student who prefers to consume the sandwich but this currently available on top of this track and if there is a student we Mark the student as A10 student list at decrement the counter on unable to eat basically we say the student has been able to eat so let's activate here okay zero okay less done student start length K plus if students of J equal to sandwich then student picks it we Mark student of J yes so that we Mark the type of sandwich as minus one which indirectly indicates that the student has consumed it Marcus student has eaten immediately following that we will decrement this so we have one student out of the way student eight search next we also need to decrement the counters on number of students has been able to eat type 0 and type 1 sandwiches so if the consumed sandwich is of type zero we decrement the type 0 counter otherwise we decrement type 1 code we will come out of this Loop with a break and stop looking for students sandwich ES we will next handle the last case that is a case where we have sandwiches but no student wants to consumer so here that is as an example two we had not to one we had sandwiches but none of the students like to consume so with no student refer to consume it current sandwich from top of shark then break it means to a sandwiches are unable to be even so this is the end of this okay now before closely we will return the current value of unable to eat this will close the implementation before we go and run it we'll perform a sanity check this needs to come here before this function is perform a quick check foreign look into the console there are two test cases which we had discussed in our whiteboard let's go ahead and run check our luck hopefully there are no symptoms fantastic so first case or first example the expectation is zero we have all consumers the second case we have two students not been able to eat that's it thanks for watching you've been so far hearing from Vidya if you like the kind of videos that I'm making customer subscribing bye | Number of Students Unable to Eat Lunch | minimum-time-to-make-rope-colorful | The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step:
* If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue.
* Otherwise, they will **leave it** and go to the queue's end.
This continues until none of the queue students want to take the top sandwich and are thus unable to eat.
You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the `ith` sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the `jth` student in the initial queue (`j = 0` is the front of the queue). Return _the number of students that are unable to eat._
**Example 1:**
**Input:** students = \[1,1,0,0\], sandwiches = \[0,1,0,1\]
**Output:** 0
**Explanation:**
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,0,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,0,1,1\].
- Front student takes the top sandwich and leaves the line making students = \[0,1,1\] and sandwiches = \[1,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,1,0\].
- Front student takes the top sandwich and leaves the line making students = \[1,0\] and sandwiches = \[0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,1\].
- Front student takes the top sandwich and leaves the line making students = \[1\] and sandwiches = \[1\].
- Front student takes the top sandwich and leaves the line making students = \[\] and sandwiches = \[\].
Hence all students are able to eat.
**Example 2:**
**Input:** students = \[1,1,1,0,0,1\], sandwiches = \[1,0,0,0,1,1\]
**Output:** 3
**Constraints:**
* `1 <= students.length, sandwiches.length <= 100`
* `students.length == sandwiches.length`
* `sandwiches[i]` is `0` or `1`.
* `students[i]` is `0` or `1`. | Maintain the running sum and max value for repeated letters. | Array,String,Dynamic Programming,Greedy | Medium | null |
119 | hey guys I think that we should start working on these let's codes problems these systematically which means we should do some of your questions together and find the patterns that we can earn from it so today I'm looking at the recursion this is one of the problems in the explore tab of this code if you tap it click the code you will wait a minute like explore the first one is uh a tree Krishna one so I'm doing recursion one so the principle of recursion it's very simple um I'm currently in progress of recurrence relation and this is the second problem of recursion relations the first one is a Pascal's triangle I have already finished it so the Pascal triangle is so we should do some we should print and print out the items of each row in this format so it's free I did it with the recursion so recursion just get a parameter of rows which row how many rows there ours and doing it recursively for the first two if it if zero and one we have the hard-coded zero and one we have the hard-coded zero and one we have the hard-coded results for the other cases we get the previous result and calculated the next one and push it to the final result array and we return so that's the recursion solution for the Pascal's triangle and we are now we have Pascal's triangle too so let's take let's see what the problem is we give a non negative in XK we turn the cave index row of the Pascal triangle notice that I wrote index s from 0 ok hmm so we are different from the Prius questions we don't need to the we don't need the final a total the all bureaus we just need to define Allah Rose final rose right so for given input is 3 0 1 2 or 3 we have 1 3 1 mm actually this is very simple because we could do it recursively so get Row 1 X if row index equal 0 we return 1 for the other cases we should get pre of role equals pit row index minus 1 and now we can calculate it calculates the final row right so actually issue B what is it what a is actually hmm anyway we just create a new array because the result equals 1 because the start and the ending item must be 1 and we need to yeah calculated the atoms between them and the for let's I equals 1 ice more than row index because the one in excess from 0 and the items that the length of each row actually should be the row index plus 1 so this should be plus 1 and minus 1 and this is the this is Ireland sum minus 1 again hmm and I am i right wait a minute so if we got get the index of this one uh-huh so this should be 2 and the 4 3 4 2 so issue okay so it should be not minus 1 i plus result push 3 row i minus 1 plus 3 row not pre but brief row i right and then we resolved push i plus a pop push 1 and finally return result it should be downright we round the code yes or should be right so submit accept it see the more details it's not fast okay what's the problem here mmm so we're getting the grow of like the before thrilled we first get a second row and then get this first we'll get the row here actually the time complexity doesn't change very much if we do something like this right yeah I think there's not so much improvement here maybe because we just various recursion of course every question could be written in eighteen iteration well I think this is good enough and could you optimist Arthur Graham's use on LK extra space actually we are using especially R actually use K square space because we have a stack like we when we get to the row of the third that like visceral first stack it and call the row of getting this row so we stuck a stack it and but the stack doesn't actually accumulate it should be a garbage collected so in JavaScript yeah when this is done so they actually the problem is that we have K okay big okay that the time and the space cuz extra space plus K so two K so actually this is okay extra space mm-hmm let's this is okay extra space mm-hmm let's this is okay extra space mm-hmm let's take a look at what the fast solutions are like this one is super fast aha I mean actually we can do direct calculation here for each element maybe actually this can be calculated there should be a way but yeah let's look take a look at how it is done get Rho reduce yeah use the native reduce maybe cool mm-hmm yeah I don't think if you mm-hmm yeah I don't think if you mm-hmm yeah I don't think if you radically change this much but well let's try it okay so actually if we get the role of the third one the reduce is very simple we just reduce them or reduce by sum them up so let's reduce okay prief row reduce first we'll just say your deuce actually the first parameter if reduce reducer is that yeah we just use a okay beasts item this is not cool result okay we can use this one returned results but we need to result push no we actually that brief we use provoked a brief zero so or so we actually use result push brief loss item and the returned brief return item this is okay so for this one plus zero Oh mm-hmm reduce wait a minute wait a mm-hmm reduce wait a minute wait a mm-hmm reduce wait a minute so it should be redo the sum of the first one and the second one okay because the uh we can just return the item but we only push if the second not the second one so if brief is not equal to zero we push and finally we push one I don't think this change is much yeah anyway this problem is done we will then take a look at the next one reverse linked list reverse a singly linked list input mm okay well I'll record this in another video see you next time | Pascal's Triangle II | pascals-triangle-ii | Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** rowIndex = 3
**Output:** \[1,3,3,1\]
**Example 2:**
**Input:** rowIndex = 0
**Output:** \[1\]
**Example 3:**
**Input:** rowIndex = 1
**Output:** \[1,1\]
**Constraints:**
* `0 <= rowIndex <= 33`
**Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space? | null | Array,Dynamic Programming | Easy | 118,2324 |
827 | Hua Hai Hello Everyone Welcome Difficult Whether Poison Meeting Cure Ireland English President And Withdrawal Subscribe To And Vid Oo Ka Powder All Possibilities 100 Witnesses To Select Query For President subscribe The Channel Liquid Subscribe subscribe to subscribe Video 1234 Paanch Cigarette Answer Subscribe 12345 Updated on 9th Buy 20% Update 2009 Updated on 9th Buy 20% Update 2009 Updated on 9th Buy 20% Update 2009 In The Maximum Subscribe Must Come Similary All Possible subscribe to The Amazing 12345 67 Subscribe and Unlimited Silent Once Again So Addison Click on the Red Button Dad You to Love You to Subscribe Number * * Update Way 2K Who is the Best Question That All Are Doing And Best Friend To Maximum Media Flat Or Plot Owners Video Emitting Link In Description Box Or Tube Skin Thumbs Solution Question Subscribe To Have Let's Tried To Understand Ardhastak Samhil Hai Now Highlighted The Research Of All Divine Qualities subscribe for More Video Subscribe Alone Will Agree With You Know What Is Subscribe like Share and subscribe the Ek Anokha Humse 1200 Find Out The Largest Area Under This Possible In This Great Update Awal Video Subscribe Crotch Veer E Want You To Sacrifice Ne Bigg Boss Top Left Right And Bottom All the universe and misses subscribe and acid All the Video then subscribe to the Page What is the area of from the per and What is the area of from the per and What is the area of from the per and ireland t20 format silent is descent 119 left ireland test one e want from the bottom since importance boundary adulteration from yesterday morning The total area twitter review generated oneplus one plus one 3217 that dance numbers question how can we make hooda wearable to update area of all the hooda wearable to update area of all the hooda wearable to update area of all the god festival subscribe and subscribe to subscribe our main bhi din hi point network type inter wills to The Identity of the Island Andhe Land Which Gives Pen Drive Voice Typing Tools to Withdraw subscribe and subscribe the Video then subscribe to the Video then I want you but first element and force elements get updated to the Video then subscribe to the Page if you liked The Video then to finally and similarly when will see nuvve sign new id se zameen ki aunty abhi ad free from one to earth spa world vidro ki a nuv comes with simple thing ko illegal and that protest at present in the great Video check valve and IAEA office amazed at the door and subscribe with oo a time complexity of or feeling information is model of science and time complexity of for identifying which one will listen maximum area is dependent on plugin for writing from all Dual app a vital Complications Screens Awards and Square Is Quite Contentful Payment Clear Don't Worry Edit Will Be Cleared in the Call Recording Call A Report in Do Define Updates ID vs the Area Till Hotspot on to the Island Do Subscribe and Sacred Values for the Subscribe and Sacred Values for the Subscribe and Sacred Values for the Area Difficult Iodine Undhe subscribe And subscribe The Amazing spider-man subscribe this one vid oo that you return to the palace Media Sciences Life Subscribe 0.5 Inch From These Bills That Alarm Juicer Tell You More Than This Particular Method Will Go To The Water From This Point Speed Ko Don't Point Speed Ko Don't Point Speed Ko Don't forget to subscribe and subscribe to is also Govinda Sai Idea to the great and I don't 151 return from all its forms that even now no end top direction to both directions to right direction laptop action in all directions from distant view of writing s Approach E Want What This Method For Dan Forest That Both Sides And Friends Me Print Lip A Novelist Talk About And Bracewell Gautam Share Defined Available Result Exactly Time Answer And By Default Between Equals To The Area Code To The Subscribe To According To Decoration A For Apple B For Your Lesson And Positive Verses Of Current Grade Difficult 20 Water Updated On That Define Another Set Of Winners Podium Ireland Spontaneous Am Ready For Example In The Left And Bottom Now Hard Reset My Friend You Is Mike Ordinance And Will Win This Is Armed With Grade A Boy - One Ko Mujhe I Armed With Grade A Boy - One Ko Mujhe I Armed With Grade A Boy - One Ko Mujhe I Plus One Ko Mujhe Aayi To Maje Minus One Adhik Id In To My Set Nominated To 10 Of All Subscribe Total Classified.in Adhere To The Subscribe Total Classified.in Adhere To The Subscribe Total Classified.in Adhere To The First To Visit Don Dawood From The Price Of A That Akshay Updates Time Complexity of this approach is order of inspector I hope you enjoy depression kiss you did you forget oo like share and subscribe our channel thanks awadhesh for more updates deposit see you tomorrow with another question on kar do | Making A Large Island | expressive-words | You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`.
Return _the size of the largest **island** in_ `grid` _after applying this operation_.
An **island** is a 4-directionally connected group of `1`s.
**Example 1:**
**Input:** grid = \[\[1,0\],\[0,1\]\]
**Output:** 3
**Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
**Example 2:**
**Input:** grid = \[\[1,1\],\[1,0\]\]
**Output:** 4
**Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4.
**Example 3:**
**Input:** grid = \[\[1,1\],\[1,1\]\]
**Output:** 4
**Explanation:** Can't change any 0 to 1, only one island with area = 4.
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 500`
* `grid[i][j]` is either `0` or `1`. | null | Array,Two Pointers,String | Medium | null |
1,961 | that's all the code 1961 check if string is a prefix of an arrrow the question is that you'll be given a string something like I love de code and it will be given an ARR of words we need to check if the string can be broken down into the first in words in the array so I love lead code there is I love lead code at the start of the array and you can ignore apples so prefix right I love lead code as a prefix in this are similarly in the second example the string is I love lead code is there in the array if you combine these three words but it's not at the beginning it's not the prefix needs to be at the beginning how am going to do it I'm simply going to go through word by word from left to right and keep checking if that word is the next word in the string I'm going to do that first I'll initialize I with zero this will help me pick the word from the string so when I'm at the start I'll check the first word length of the first word and I'll pick that big a chunk from the string and compare it if it's same I'll move ahead if not I'll return false I'll go to the second word and compare it with the uh where I would be at index one and I would check for until the length of the second word in this areay right so in this case also it's same so I'll move to the third same at this point I reach a place where so there is no world space for any more World here so although I'm with this but I'll not compare anything with this I'll simply return two and at in this process at any point if I find a word not matching like it would happen in the second example with the first St so I'll take the length of apples which is five characters I'll take five characters and compare it I not find it to be the same I'll return false there so let's do it I is zero for word in words so I'm going word by word from left to right and J would be I + length of words right and J would be I + length of words right and J would be I + length of words so this would be the end of string end of the word that I'm looking for in the string so if J is greater than length of s which is uh that is J has J is beyond this length of s then in that case I'll just break out of this Loop because I will not continue this and if J is less than length of s less than or equal to length of s in that case what I'll do is I'll go to the next line and check if the part of the string from I to J is not equal to the word itself then I'll return false else it will proceed it will reset I to be I + length proceed it will reset I to be I + length proceed it will reset I to be I + length of the current word and finally I'll return if I is greater or equal to length of s so if that is true which means that the entire string is the prefix when which case would this be false in a case where the words has finished okay there are fewer words but the string is not yet finished that case I would be less than length of s right so I can even do it just I is equal to length of greater than L let's run this and see okay it didn't work out as expected we will need I is greater or equal to length of s and that worked and submitt it and that worked for all | Check If String Is a Prefix of Array | maximum-ice-cream-bars | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\]
**Output:** true
**Explanation:**
s can be made by concatenating "i ", "love ", and "leetcode " together.
**Example 2:**
**Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\]
**Output:** false
**Explanation:**
It is impossible to make s using a prefix of arr.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 20`
* `1 <= s.length <= 1000`
* `words[i]` and `s` consist of only lowercase English letters. | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. | Array,Greedy,Sorting | Medium | null |
1,531 | Hello everyone welcome to my channel code sorry with mike so today we are going to do video number 77 of our diy programming playlist ok number 115 is hard marked but will make it easy just a few things you have to understand in this you will be able to To write your code on your own. Okay, so let's see what the question is saying. You must know what RL E means, what is the meaning of run length encoding. Let's say there is an example, this is a string, A B C, it's okay. So if you want to write its R, then write it like this. Look how many times he has come. He has come twice. Write it like this. B. If he has come once then you will write B even without writing 'वन'. Do not write B even without writing 'वन'. Do not write B even without writing 'वन'. Do not write 'वन' if it is ever situated. So write C twice. write 'वन' if it is ever situated. So write C twice. write 'वन' if it is ever situated. So write C twice. That's it, my run length encoding is fine. Okay, here's the question. Pay attention here. Given string s and integer. Given you a string s. And given you an integer. You need to delete at the most character. Maximum K characters have to be deleted from s. True, that the run length encoded version of A has minimum length. It means that from this string s, you have to delete the minimum maximum K characters. After hitting delete, when you run it. If you find out the length encoding then its length should be minimum. Okay, you have to find out the minimum length and tell it. Okay, find the minimum length of run length encoded version of s after the delete after delete at the most. So let's understand from this example what is here. It is saying that you can delete a maximum of two characters, okay, so now this is a string, because of the value, you deleted one of this and one of this, then you deleted two characters, let's see what the string becomes. Our ABC is CD, if you write its initials, if you write the encoded version, how will it be written, A B C3D, look at its length, how much is Ek Doti Ch Pa, its length is five, so the answer is five, we can bring a better answer, let's see. How do you delete this B and this C? Okay, so what will our string become? A B C D. Let's write its run length encoded version as a3 B c2d. Its length has become even bigger, right? If its length becomes 'Ch' has become even bigger, right? If its length becomes 'Ch' has become even bigger, right? If its length becomes 'Ch' then this is not the better answer. Let's see when the best answer will come when we delete ' when the best answer will come when we delete ' when the best answer will come when we delete ' B' and 'D' then see what will happen if ' B' and 'D' then see what will happen if ' B' and 'D' then see what will happen if ' AA', 'B' is deleted, 'CCCD' is also AA', 'B' is deleted, 'CCCD' is also AA', 'B' is deleted, 'CCCD' is also deleted, okay. k = 2, so the deleted, okay. k = 2, so the deleted, okay. k = 2, so the maximum you can delete is two characters, so now see what will be the answer - a3 c3, so now see what will be the answer - a3 c3, so now see what will be the answer - a3 c3, look at its length is four, that is, our answer is four, so this is the length we are sending. That run length is the length of the encoded version of the string, isn't it? Its length is not its RL, we calculated after delay, the length after that is four, this is the minimum, so this is what we got, its length was six, its length was five, then the best answer is mine. Okay, so the answer is four, so let's see how we will approach it and how we will move forward. If we build the thought process, then look, first of all, go to hell with DP. We have to first see what our mind, which is our most initial thought, tells us to do. Ko is saying that a little while ago I had shown you, remember I told you in the beginning, friend, if I had deleted this A, it is okay and if I had deleted this A, it is okay, then what would have happened to this A later I said no, if you don't get a better answer than this then let's do one thing, delete it and so on, we are seeing options, one thing I had understood in the beginning itself was that brother, there are options. That you can delete a character or not, so I saw the option, whenever the option comes, I try to make a tree diagram once. What is the meaning of tree diagram, recursion, then to make a tree, time. Let me try, if let's assume that I am currently standing here, then I have the option whether I should delete this a or not. Right now the value of k in the beginning is two, let's assume that two characters can be deleted maximum. If yes, then it is fine. If we assume that I have deleted this eighth character, then it is okay that I have deleted this eighth character, or if I have not deleted it, then I have kept the index. Keep I means not deleted. If I have deleted it, then it is obvious that our string is Something like this will happen: A B C string is Something like this will happen: A B C string is Something like this will happen: A B C D and the value of K will become one because we have hit delete and if you have not deleted then A string will remain the same B C D. Okay and here you are. It will come okay and the value of k will remain two of two, till now it is clear, okay then here when you have come here, then you will have two options either delete i or keep i. Okay, similarly, here also you will do something like this, delete I and keep I and so on, you will make a tree diagram. Okay, then look at the time of delete I, when you had deleted it, this is an obvious thing, isn't it, when the character itself is deleted. If you do this then you will not add anything to the length, that means the length will not be added at all. Look, what is the ultimate length of the encoded version of the string to send to you, so when you deleted it, there will be a little count in the length, that is fine, so at least you have deleted it. That is fine but when you are keeping then pay attention there, I mean, I am saying pay attention to this branch, what I am trying to explain is a very important part, okay so look, pay attention here when you are here. Come, have you kept which one did you keep, the last character which was 'A', you have kept it, okay, character which was 'A', you have kept it, okay, character which was 'A', you have kept it, okay, so now it is an obvious thing, when you have come here, then you have to keep a count of 'A', come here, then you have to keep a count of 'A', come here, then you have to keep a count of 'A', not the last previous character. The one which I had not deleted, I had kept it, which character was that character, was it this or that character, I had kept this one, so brother, we will have to keep a count of it, brother, what is its count, if the current character is the same. If it is then we will keep increasing the count because look, when the count increases, you will know that the count is just a2 or else if the count increases then it will be called a3, then it is okay, so I have to take that out too, if you want to pay attention to that, then you will have to keep the count also. And what was the previous character, you will also have to keep in mind, understand the requirement, that is what I am saying, develop your code as per the requirement, develop the thought process, I am repeating again, when you kept this character, let it remain, did not hit delete and you are here. But since you have come, I told you, brother, obviously tell me what has to be done in run length encoded, how many times a character has come, its frequency has to be kept, then it has to be kept only one frequency, so this is the current situation I am standing on. How will we find out its frequency? We will keep counting its frequency and just before this there was another A, so now we will reduce the frequency of A to two. Okay, so now we have understood what things we have to pay attention to. What was the previous character? Why are you keeping in mind the previous character? Brother, we have to find out the frequency and we will also take care of the frequency. Okay, till now it is clear. Now pay attention to one thing, it has been made clear in the question that what is the length of your s, what is the length of s. Right, it will go only up to a maximum of 100. Okay, from row to maximum, I think the length will go from one to 100. So, look, I am doing one thing, earlier I was giving you a big example, now I am giving you a small example. Let me show you with the value, this is your a, okay, so currently your i is here, see, I told you that delete is very easy, deleted it and moved ahead, this is the main, we have to pay attention to the key, okay so. It is done that you have kept this A. If you have kept this A then you have added one length. Now one length will remain. Okay, now look, pay attention. What was the frequency of A here? Frequency of A. There was one here, now I have come forward, okay I am here, mine is here, so first I will check whether this is yes, then here also the same two cases will be there, delete I and one will be keep I. Okay, if I keep this eye character then leave it, I am saying that my entire focus is on keep eye, okay pay attention here, if I keep this eye character, okay, then first of all I will see that brother, is this my previous character? Is equal to Yes Is I's Just Previous Character Who Was A Was Okay Previous Character A Was Neither Look Now I'm a very important part here Pay attention to the Previous Character I's Just Previous Character of I's Which was Yes Was Both The same character is gone. Okay, so before the I, what is the frequency of A before this I. There is only one frequency of A. Okay, if there was only one frequency, then there would be no need to write yaad one along with one when run length encoding was done. So but when it became more than one, then we had to write two or three or fo or f and so on. Okay, so what happened here, before this i, the frequency of A was not zero. The frequency of A was more than zero. One. Now again one more A has appeared, meaning more than one, now my frequency is done, so one more number is going to be added to A, it will be two, or maybe further Y is found, then maybe it will become Th, okay but funda. But that is not important, what is important is that there is another member along with A, whether it will be two or three or four, it will be seen. Okay, now he is not alone, meaning one more length has been added in our run length encoding. Okay who is that just next to a? Its frequency is okay so now pay attention to one thing here how I found out first of all I checked this, was the character before this a the same yes it was the same first thing second. The thing I did was to see that before this, what was the frequency of What you said is that now its frequency is more than one, then one more length will be added to our run length in the encoded version which will reflect only one frequency, okay so it can be two or three or four, right? And so on either F ho and so on ok now pay attention to one thing so I will come here again a will come and aa I will be out of bounds ok aa if I am out of bounds then I will return zero Okay, here I did not get 1 P 0, from here I neither returned it nor got passed, nor did this return come, 1, then 2 came, the answer is my 2, it is okay, so and that 2, what is my a2, right? Run length encoded version, what will be its run encoded version a2 is correct, its length is two, okay, so I was telling you the answer of this path, the answer will be two from this path, okay, now pay attention to one thing, this is a very important part, friend, this part. But pay attention very carefully, look, here I came on I, so what was the length before coming, how much was the frequency, there was one of A, only now one and when this came, the frequency became two, so I looked here, added one. I did it okay, but going by the values, my example would have been bigger A Okay, so pay attention to one thing, here there would have been one path to delete, one path to keep, okay see. Pay attention, you have kept it, okay, let's assume that you have kept one length, you have kept it, okay now A comes here again on the second index, okay then you will see that there is a frequency already before A, its okay, so you And you will add the length because after a, one has come. Sorry, not one. If the frequency of a comes to two then it will become a2, that is fine, then when another a is seen again, a3 will become but still the length is two, then one more a. If shown, it will be a4 but the length is still two, its run length is a5 of the echo version, sorry here it will be a5, then the length is still two, then a6 will be, still the length is two, a7 will be, still the length is two till a9. Length will remain two, then as I will see that it is before i, let's assume that this current i is here, okay currently i is here, what is the frequency of a before this i, first of all I will check that yes before this i. Is the character the same? Yes, if it is the same, then I will check brother, what is the frequency of a before this i. The frequency of a before this i is no. Now another a has come, now another a has come, meaning what will happen to a? It will become 10. Now the length has increased, so what will I have to do? I will have to do one more addition on my length. Remember, earlier there was a and two, then the length was only two. Then remember. One was added here, it was of A, then why was this one added, because I had seen the frequency of YET, after that when three came, I did not add, still the length is two, see, then four came and so on now. A has come, 10 has come, this is the frequency, because before this A, there was no frequency of 1, so now one more has come, with the help of that, the frequency of A has become total 10, so one more addition has been done to this zero, this is ok. Because of zero its overall run length encoding length has become three, isn't the first and second okay till now it is clear, similarly what will happen after 10, then it will be 11, still the length is three then it will be 12, still its length is three. Then it will be 13, still its length is three, isn't it? How long will its length remain three? Till a99, its length will remain three. Okay, that means let's assume that we got a very big test case a and so on in which the total is 100 a. 100 A is fine because the maximum length can be 100. I told you that here let's assume that it is 100 A. Let's assume that I came here so I will see whether the characters before this are A, that character is A, yes. And what is the frequency? Their total frequency is 99. So as soon as I came together, my count became 100. Now A's count will be 100. Now look at its length. Look at how much it is. Now its length has become four. Remember. Till a99, its length was three, one, two, three, as soon as it became 100, now its length became four. Till now it is clear. Okay, so we will just have to pay attention to this thing that brother, what is the frequency of a before the aa on which i is. If Before that, the frequency of a is one. If the frequency of a before i was one, then along with the a in a, one more character will start getting added along with a. Now the frequency will be two, now it is okay till now, then it is okay. So I increased one length in that case. Okay, I increased one length in that case. But if the frequency of A does not remain before Aa, then now the rectangle character is again A. If it comes then look at the frequency this time. If it becomes 10 then its length becomes three. If it is clear till now, then this part is a bit tough. Handling this thing of this question was tough, rest of the remaining parts are very easy. If we assume that your example would have been something like ABC, it would have been fine. So it is because of the value that you are here now. Okay, so you have seen that the delete case is different. Let's look at the keep case. Okay, so in the keep case, you must have seen that now you are on the I. So the previous character is yours. A must have been okay, your previous character must have been A, so your previous character is A, so you saw that A and B are not equal, then why increase the frequency, then there is no problem, right, a will come once and sister-in-law. Apna will come once, okay, when it becomes come once and sister-in-law. Apna will come once, okay, when it becomes come once and sister-in-law. Apna will come once, okay, when it becomes equal, because of the value, this would also be a, then we have to pay attention to the count, how many times it has come, okay, and the most important thing is that we have to pay attention that a is taken as a. A is A. What was the most important part that came here? So what was the frequency of a before i. Okay, we have to take care of that. If the frequency of a before i was a nine, okay, that means if the frequency of a before i was one. If there was i, then one more a has come, then what is the frequency? Now my frequency has come to two, so what happened to a due to two coming, now we will start showing its frequency add. It is in the run length encoded version, if only one remains. Then there is no problem, okay, but now the frequency has become two, so I increased the length by one more, along with a, another person has come who will depict the frequency and if it goes till two, 3, 4, 5, 6, 9, then it is okay, isn't it nine? Okay, as soon as it reached 10, then I increased its length by one more, one zero will also be added, then after 10, till 11 12 13 14 999, its length will remain three, but as soon as one more one comes, see what will happen, then the length will be one. It will increase, it becomes 100, one more length increases again because one more zero is added, till now it is clear, so let us see how we will handle this thing, the easiest part is that you know you have to give a solve name. You must have caught it in the beginning itself because you had the options, it is okay that you have to send the index, even this must be clear to you, what is the previous character and also you have to send it, I have already told you. I told you why, because the frequency has to be counted brother and what is the frequency, that too has to be sent. When you know, then you will definitely put it, okay after that, remember when you used to delete, the K also got changed by deleting the maximum character. If you can, if you delete a character then it will change, so you will keep passing it as well. Okay, so see, the most important part in this was that which parameters are required by you, so it is very obvious that in the string you If you are hitting iterate then it is obvious that it is also obvious because if you have to delete it then it will definitely change. After that, why were these two important and why did these two come. Think for yourself, when any character is the same then it is so. If it is the same then you will have to count the frequency, if there is four with A then what is four, what is frequency, then this frequency came from here, okay and which character is it, that is, how to count the frequency when you know that there was an A before it? Before this there was a, before that there was a, so the previous character is also needed, isn't that why I say that there is a reason behind everything, if I write the code and show it to you without the reason, then you will not be able to learn anything right here, which one have I mentioned? You should also know why the parameter has been used. Okay, now let's move ahead. Okay, so the easiest case was about deletion, so I write it in advance that if I have deleted aa, then there is nothing to be done in the length. There is no edition because I have already deleted it. If I have deleted it then I will simply call solve again and say brother, I have deleted the I character, so now go ahead and bring me the answer. I have deleted the character. If you do this then the previous character will change, what will not happen? For example, look here, AB is CD, right? By default, now i is here and its previous character is this, so if you delete i, then i will move forward. Has the previous character not changed? Because b has been deleted. If the previous character of this aa remains a, then the previous character will not change. In the case of deletion, it is okay. So here the previous character will remain the same. It is okay and the frequency. Will there be any change or not? It is an obvious thing that the frequency will not change. Let us assume that a b c d was i here, okay then the frequency has changed. No, I have deleted it, so where is the frequency from, there will be some change, some will not change, okay? The frequency has remained the same because it can also happen that A is B. Okay, so let's assume that A is here, this is the previous character. Okay, so let's assume that B. You have deleted it. The case of deletion is going on. If you deleted d then aa came here then who should have been the previous one of aa, it should have been a only because aa character has been deleted ok so the previous one is a which is fine and what is the frequency of the previous character. It is stored in it has not changed, it was still one, it is still one, now when you come, then you will check whether the previous character is equal, then the frequency will be increased, okay, but I want to say here. That in the case of deletion, the frequency will also not change. Right, because we have deleted the rectangle character and hit delete, then brother, you will have to do k-1. I think this deletion you will have to do k-1. I think this deletion you will have to do k-1. I think this deletion part must have become very easy for you. I think it is easy. Now I have mentioned the keep part, how to handle it when I keep i. Okay, now let's move ahead. Now let's see in the case of keep i, that is, if I have not deleted aa. For example, let's take it as AB CD. Was and because of the value, you are here, because of the value of was, okay, so if it is a deleted case, then this deleted one will work here, but now let's see in the came, meaning you have not deleted it is okay if you have deleted it. If you did not delete it, then first of all I used to say, brother, please check which character before this is equal to the previous character, is it not B, is the previous character A, is this my previous character, then it is equal to A? If not, then Yes, frequency B will remain one, right, frequency B will remain one and when I goes ahead, the previous character for it will become Y. Right, so what I am saying is that if I change this to my current character. When I do keep, I will check that if it is not equal to the previous character, whatever my previous character is, okay if it is not equal to that then we do not have to do anything, simply return sorry, whatever the variable of keep, I will store it in it. I will do one plus one, why did I add it, pay attention because B is alone, now I will keep B, na B, which I showed for the first time because the previous character was A, B is the new character, so I will write this one, I will write one. Here I added the length, it is okay for that, after that I will call solve, now look, pay attention, i + 1 will have to be done because I have to i + 1 will have to be done because I have to i + 1 will have to be done because I have to go further in the index, after that I have to see what will be the previous character currently it will become B. Because when aa comes next, the previous character for it will now become b. Right, then who is the previous character? Currently, s is off. Aa is okay. After that, what did you send? If you used to send frequency, then obviously s is b. I can see its frequency for the first time. If there is one, I will send one and I have not deleted anything, so the value of k will not change, so it is mine. In the key case, when a is not equal to the previous character, is it okay and if it is equal to the previous character, then how? They see how to handle it, so see, I have written it a little clean, this was the delete case, you will remember that after that there was the keep case. In the keep case, what did I check whether it is equal to the previous character and if not. Then this one is simple, if the bus is equal to the conductor, now we have to see the frequency and the count, right, so for that I will explain it to you here with an example, due to the demand, currently you i is here and your previous character. This is fine, so the obvious thing is that what was the frequency of a before this i. It was one. If the frequency was only one, then run length encoding. If a was to be written, then the frequency of a was only one, so it would remain the same because a1 is not written. It was said that when the frequency was one, if one was not written, then its length would have remained the same. What is the length of our run length coding? One is okay, but if its frequency is one before aa, okay and now aa is also the same character. So how much has the frequency become, it will become two, so now see, the frequency has become more than one, so to depict it, we will have to write the frequency Y, whether it is a2 or a3 and so on, okay, so what I said here. What will have to be checked is whether the frequency of that previs creditor before this eighth index was one. If it was one then it means that one more a has come on the rectangle character then its frequency will increase from one to two. Okay, so what I said, if the frequency is one, then it means one more addition is taking place in our run length coding, so here I write one more addition, right in our run length coding, so its value I write one. Let me tell you that there is going to be another edition, now it is okay, now I can call recurse, not solve, how will I call recurse, I take a variable named keep, here also we should have kept the variable keep i, the name would have been better. It seems okay, so what did I solve in Keep I, since the value of one more addition has become one, then one will be added here, why brother, one more addition has happened because the frequency is now more than one, plus now our recursor. Make the call, now look, if you call recurs, then i + 1 will definitely be look, if you call recurs, then i + 1 will definitely be look, if you call recurs, then i + 1 will definitely be sent, okay, after that look, pay attention to what is the previous character, okay, since we have looked here, pay attention, now I will go ahead of me, okay, so the previous character. There will be some change, now the previous character is the same, right, so the previous character will not change because we have not deleted it, okay, so what will happen here, the previous character will remain the same as it was, okay, now after that, the frequency after the previous character. Now let's see, the frequency has increased, the frequency has become plus and if it has not been deleted, then it will remain the same, okay, the frequency will increase, whatever was the frequency earlier, it was one, now or after this, if the frequency has become two, then the frequency. I did two and moved ahead. I am fine, so till now it seems very clear, but now pay attention to one thing, when the frequency will be two, then further frequency will be three. Okay, if the frequency will be three, then what extra addition do I have to do now? Not in the run length encoding, it is still two in length. Now when the frequency becomes four, then there is no need to do extra one more addition in the run length encoding. Still look, its length is only two in the run length encoding string but when a was before aa. Before the index, if we assume that my aa is here and it is prevalent, if there was another aa here, the total would be 9a, there would be 9a here and currently one more aa has been found, meaning I am saying that before aa, the frequency was not there, now there is one. And a has been found, so now see what will happen, the frequency will become 10, then look, one more zero has come, okay, so what I am saying is that even if the frequency is not equal to i, then still another addition will come. Because just one more character has come, 10, now the frequency will become 10, so one more addition will have to be done. Okay, after 10, if the frequency becomes 11, then what should I increase? There will be one more extra addition in the run length encoding. No, still the length will be only three. Then it is 11, 12 and so on, it will not change till 99, still the length of run length encoding is only three, okay, there was only one extra addition, the same remains three of three, but if it becomes 100, okay, what does it mean that previously Previously before aa it was 99. The frequency of a was 99. Now here one more a has come so it becomes 100 so one more extra addition has taken place. Look, one more zero has been added here so its length. Now see what is the length of run lending. It has become four, one more addition has been made, so here I will also have to write that if the frequency before this was 99, then now with the addition of one more character, the frequency will become 100. Okay, so one more addition is equal to two. It will have to be done here also, it is okay, so in the same way, one will be added again and again in every case, okay, there will be one case when 'A' means one case when 'A' means one case when 'A' means frequency should not be there before the eighth character, then this number will become 10, okay. One must have been that before the I character, the frequency must have been one, so after adding this, the frequency became two. Okay, before the rectangle cutter, the frequency must have been 99, so by adding this, it became 100. Only in these three cases, the string version of our run length encoded version. There will be a change in the length, there will be an extra addition only in the same three cases. Look here, one more addition has been done, otherwise we will keep its value as zero. It is okay in the beginning, this was all we had here and we have covered the most important and tough part of this question. The most difficult part was that what is the value of Pi and here let's also see the base case. We have not written the base case yet. Look, what can be the base case? So come one index and if you are increasing it then it is an obvious thing. It will be out of bounds at some point or the other, hence we will have to write a base case for it. Look second, we are doing subtraction. We keep doing k -1 -1. It is we are doing subtraction. We keep doing k -1 -1. It is we are doing subtraction. We keep doing k -1 -1. It is possible that if the lesson goes to 0, then that is an invalid case, if you believe that. Said, brother, I am your string, which is b, you can show me by deleting the character, brother, deleting 2 characters means nothing, it makes no sense, so I will check in advance, brother, if you see, if you do the lesson. If it is giving 0 then I ca n't delete anything, okay I can't delete anything, this is an invalid case, okay so I send infinite here, why am I sending infinite because here I have to find the minimum, in the end what am I doing here? What will I do as minimum return? Will I return the minimum length? Brother, whether the minimum comes by deleting or by keeping it, whichever minimum comes from both the options, then since the minimum has to be found out, then the invalid case will have to be rejected, then to hit reject. I kept its value infinity so that it gets rejected and what can happen to another base that Aa which is greater equal to A, becomes out of bounds, then Bhai is out of bounds, so now we cannot find any length. Length will be zero and our return will be zero. This is clear. Take a very small example and do a dry run of this entire code. But this is your ready code. Recurse's code is fine. Memorizing it is also very easy. Pay attention to memorization. What I always used to say is, look what parameters are changing, here four parameters are changing, this is also happening, this is also changing, this is also happening, so the obvious thing is to do memorization. For this, you can either use a map, but the time limit may be exceeded in the map, that is why I used a, so I used four dimensions, it is fine for memorization, watch this video, it took a long time to explain, that is why I used bottom up. I will bring it out in a separate video, okay, so let's memoize, what was the first parameter, i was there, so aa means length, indexed, then what was the length, the maximum length of our hey can be 100, so I took 101, okay. After that, pay attention to the two second parameter, the character is there, but here it is an integer, so how can we write the character here? Okay, so let's do one thing, whatever character will be ours, let's assume that it is a, so a is converted to zero. We will convert b is b, we will convert b into one, c is we will convert c into two, remember how we used to convert, simply whatever character is, minus whatever character is from A, we will get zero. Character B is right. Yes, this is also done by subtracting two from A, one will come, this is the calculation of A, nothing else, you must be aware of this, already by subtracting A from two will come, okay, so instead of storing the character here, I will store the character minus A. So it will be converted into integer and how many total characters can there be? There are total 26 characters in alphabet, so here I give maximum 27 values, okay after that yes, so please note that here you cannot pass characters. It is okay to pass character minus A instead of character so that you can use the integer to check. It is okay instead of character. Okay, so now coming to the third parameter, what was the third parameter? The third parameter was my frequency. So the maximum length can be 100. The maximum frequency of our string can also be 100, so I have taken 101 here. Okay, after this there was the value of k. So the maximum value of k has been given as 100. Maybe it is okay, so the maximum value of k I have taken 101. Okay here, friend, it is quite simple, here you also mean that memorization is also simple, four parameters were taken and were being changed, we will memorize all four, okay, so quickly let's code it and while coding, one more important thing. I will teach you now, you see, okay, so let's start it, quite a few questions, okay, return, first of all, let's write the function, return solve, okay, what all were you passing, remember, let's just pass the string. After which index is there, starting from zero index which is the previous character so right now I don't know which is the previous character so I take a normal blank character ok after that index number sorry which one is my frequency Frequency is zero, right now there is nothing, I have passed after that, okay, so let's solve, write our function int solve string and s int i, okay after that int, which is the previous character, remember I said character, previous character. Isn't it right, but I told you that at the time of memoization, we will convert it into integer, so let's leave it as integer, okay, and when we have to extract the character, how will we extract the character? Whatever character it is, we will make it minus A. Okay, so what is the maximum value that can come in the character, z can come, so z - A, what will z can come, so z - A, what will z can come, so z - A, what will happen to me, 25 will be right, so here I take a big value, 26 is blank, so instead of blank, I took 26, okay int previous. Character taken, frequency taken as int, okay, now look, pay attention, first of all, let's write the base case. I told you that if brother's lesson becomes 0, then it is an invalid case. Return int will be max, okay. Till now it is clear, after that if I become greater than or equal to n, it means some length cannot be extracted now, the string of run length encoding has ended, return zero, ok, now look, there were two options, brother, delete the rectangle. If you delete the character, nothing will be added. There will be no addition. Length will be simply solved. Will call for further i. There is no change in the previous character for P1 because the eighth character has been deleted. There is no change in the frequency also. Because the eighth character is deleted, if it is delayed then we have made it k - 1. We have cleared it till now, then we have made it k - 1. We have cleared it till now, then we have made it k - 1. We have cleared it till now, after that let's see what we can do for the keep aa case. First of all, if s is off, that means if my previous character is equal to the current character. If it comes out then s of i is equal to the previous character. If it is not equal to the previous character then let us accept that it is okay if it is not equal then there is no problem but remember we were representing the previous character through an integer so s of i is equal to that of the previous character. We will represent Ko - A like this. will represent Ko - A like this. will represent Ko - A like this. Okay, so what we are checking here is that the current character and the previous character are not equal. If not equal then there is no problem, we will have to put under i = two no problem, we will have to put under i = two no problem, we will have to put under i = two current character. Because that previous character is not equal then one is added to it and called solve s aa pv it will definitely happen and for the next character index who will be the previous character then who will be the current character then who is the current character a aa but yes If you want to represent it in integer then - A is done, it is represent it in integer then - A is done, it is represent it in integer then - A is done, it is fine, since this is the new character I saw for the first time SI because it was equal to the previous character, otherwise its frequency is one, it is fine and if no deletion is done then k. K will remain the same, okay, now comes the tough part, brother, if our current character SI is equal to the previous character, okay, then what do we have to do? I told you that first let's take a variable, int variable. Let's write the name a one more addition is ok e ill take 0 for RL run length encoding if the previous frequency of mine was equal to one or if the previous frequency of mine was equal to mine to a sorry 9 Or my previous frequency would have been equal to 99. Okay, so now the current character which is the current character is also equal to the previous one, so the frequency will become two in this case. In this case it will become 10. In this case it will become 100 from 9999, so that means. There will be one more addition in our run length encoded version, okay, so I make its value one here, brother, make it one, okay and add this to the value of keep coming, one more addition plus solve s i pv, you will do it. Okay, after that will the previous character change or not because we have not deleted anything, right, the previous character remains the same, okay the frequency remains plv, okay and why did k frequency pv because see, the current character is equal to my previous character. In the case of others, now we have plowed the frequency, it is okay here and did not delete anything, only k is left, what to do in the last return, whichever minimum is found from the two, whatever is found from the delete i or else. By keeping an eye on whatever comes out to be the minimum, that will be my best answer. Okay, so it's an obvious thing that it will pass, otherwise let's memoize it. If four variables are changing, then four dimensions have been taken. 101 was the length and its After this, our previous character was the previous one, I had said total, here I have sent a value of 26, so I make its maximum 27, right, I take 27 and the maximum of the frequency is 101 is the frequency, it is possible that the maximum value of K may be 100. If possible, let's take 101, it's okay, before doing everything, I will check that if t of a comma previous care comma frequency comma k is not equal to -1 then is not equal to -1 then is not equal to -1 then return means there is already some state solved in it. If it was, then return it here, okay, and store it here also before returning it, right? And don't forget to do this. Let's run the t my size of t and see, we should be able to pass the cases, the video is quite long. I just went because this tough part had to be explained well, I had to explain it in a lot of detail, here A is not defined, A dot, let's make the length, okay, this video has become long, that is why I will make a separate video of the bottom, I am okay, enter here. What are you saying? Previous does not match. Previous underscore will be taken care of. Is it here also? Previous underscore will be taken care of. Okay, let's see if we are able to pass it. How but it is not passed here. Deadly signal is coming so I actually So big, here in c+p, actually So big, here in c+p, actually So big, here in c+p, I cannot define it because if I define it inside the class, then it will be stored in the stack, its space and there was too much space, so I have used heap, what is heap and how is it going in heap. I write this, I have defined it outside the class, so whatever space it has is allocated in the heap, so the heap has so much space that it can take such a big space. Okay, so this is an issue of c+p. space. Okay, so this is an issue of c+p. space. Okay, so this is an issue of c+p. Yes but I have seen that people have not faced this problem in Python or other languages but I people have not faced this problem in Python or other languages but I people have not faced this problem in Python or other languages but I faced it here so I defined it outside. Okay submit. We should be able to pass all the ts cases after that. Time complexity is simple. Actually we have solved this question. Now look, pay attention. Time complexity is very simple. If we visit as many states as there are, then one i is visible here. I mean index maximum length n is into previous character. Right, what is the value of the previous character? There can be a total of 26 values. So keep 26 values of the character. can be a total of 26 values. So keep 26 values of the character. can be a total of 26 values. So keep 26 values of the character. Here the frequency can be maximum. What can be the maximum frequency? It can be 26. Okay, no, sorry. It can be 100, which means it can be equal to the length. The value of k is equal to n. This is the same number of states we can visit. If we remove 26 then how much will it become. N will become s. N is s*k. Okay, I hope I was able N is s*k. Okay, I hope I was able N is s*k. Okay, I hope I was able to help. Any doubt raise in the comment session try to help you out see next video thank you | String Compression II | number-of-ways-to-wear-different-hats-to-each-other | [Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string `"aabccc "` we replace `"aa "` by `"a2 "` and replace `"ccc "` by `"c3 "`. Thus the compressed string becomes `"a2bc3 "`.
Notice that in this problem, we are not adding `'1'` after single characters.
Given a string `s` and an integer `k`. You need to delete **at most** `k` characters from `s` such that the run-length encoded version of `s` has minimum length.
Find the _minimum length of the run-length encoded version of_ `s` _after deleting at most_ `k` _characters_.
**Example 1:**
**Input:** s = "aaabcccd ", k = 2
**Output:** 4
**Explanation:** Compressing s without deleting anything will give us "a3bc3d " of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd " which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3 " of length 4.
**Example 2:**
**Input:** s = "aabbaa ", k = 2
**Output:** 2
**Explanation:** If we delete both 'b' characters, the resulting compressed string would be "a4 " of length 2.
**Example 3:**
**Input:** s = "aaaaaaaaaaa ", k = 0
**Output:** 3
**Explanation:** Since k is zero, we cannot delete anything. The compressed string is "a11 " of length 3.
**Constraints:**
* `1 <= s.length <= 100`
* `0 <= k <= s.length`
* `s` contains only lowercase English letters. | Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1. | Array,Dynamic Programming,Bit Manipulation,Bitmask | Hard | 2105 |
111 | hello today we'll be working on leak code 111 minimum depth of binary tree so the minimum depth is the shortest path from the root node to a leaf node is a node with no children or in other words both the left and right are null so let's start by working through the different types of inputs we could get all right so the root node could be null and if this is the case we could just return zero the next case would be if we only have one node so in this case the root node is also a leaf node because both the left and right are null so we would return one because it takes us one node to reach a leaf node our next situation would be if only one child is null this is the case we'd want to Traverse down the valid side until we reach a leaf node so we'd ever come across one side being null and the other having it we would just ignore the null side altogether and then our last situation would be if both children are valid we have to Traverse down both sides and then compare the total amount of nodes in both paths so that's our thought process for traversing the tree now we'll talk about returning the shortest path so the idea behind this algorithm is that once we hit a leaf node we'll start building up the totals for the paths so once we reach a leaf will return one and when we return into the previous calls We'll add one to the return value so if a previous node has two valid children we'll compare and return the smaller of the two all right hopefully all of that's making sense and I hope that the animations helps to clear everything up on how we're moving through it and how we're returning the values so let's go ahead and step into the code and show you exactly how we're going to implement this so the first thing we're going to do is check if the root is null and return 0 if it is next we'll create a function called depth which takes a node our base case is if both the nodes left and right are null then we'll return one next up if the left node is valid and the right node is null we'll Traverse the left node and return the result plus one this if statement is the opposite so if the right is valid and the left is null will Traverse the right and return the result plus one so if we get past those if statements it means we have two valid children so we'll Traverse the left and the right and add one to both results we then return the smaller of the two by putting the results in math.min putting the results in math.min putting the results in math.min and then we call depth and pass the root and we return that from our function to get a bit better with making recursive algorithms iterative let's Implement an iterative solution so same as last time we'll return zero the root is null will create a stack to keep track of our calls in a map called depth to store our visited nodes we'll loop as long as we have a value in the stack we'll then pull out the item at the top of the stack by getting the last index with stack dot length minus one now we need to Traverse the tree so the node to the left isn't null and we don't have a reference to the nodes left in depth then we'll add the note to the stack Loop will start over and make the left or current node so if the node's left is null or we've already captured it we need to see if we can move into the right these are the same conditions as the previous statement but for the node right so this out statement is where we capture the values for our path and remove notes from the stat so remember our conditions we have two cha two valid children one valid child or no valid children so our first condition is going to be for two valid children we have the node right and left in the map we'll put our current node in the map and assign it the smaller of its children's values plus one so these next two conditions are if only one child was valid the left is valid and depth doesn't have the right node we'll put our current node in the map and assign it the less Value Plus one and we do the same for the right child the right is valid and depth doesn't have the left we'll put our current node in the map and assign the right Value Plus One else both the children are null so there are no valid children and we will set the node as the key in depth and give it a depth of one so this is our base case and our recursive algorithm so our checks throughout this algorithm are looking to see if we've already have a value for that current node okay so after capturing a node's depth you can remove it from the stack by popping It Off lastly our root node will be the final node added to depths so we can grab the value of our root node from depth and return it all right I hope you learned something today do you have any questions please leave a comment below and I'll catch you in the next video | Minimum Depth of Binary Tree | minimum-depth-of-binary-tree | Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 2
**Example 2:**
**Input:** root = \[2,null,3,null,4,null,5,null,6\]
**Output:** 5
**Constraints:**
* The number of nodes in the tree is in the range `[0, 105]`.
* `-1000 <= Node.val <= 1000` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | 102,104 |
969 | hello how's it going so today we are going to do the code 969 pancake sorting so um give an array of integer sorter rate by performing a series of pancake flips um in one pancake flip we do the following steps choose an integer uh and reverse the subarray so for example three two one four and can perform pancake flipping and uh yeah the question itself like so the output is uh the k so if you write a helper function called flip k so basically you're in your result you have to output the k so if you perform four two four three consecutively you will get a one two three four sorted so uh because uh the original array is three two four one and then if you flip four it means you reverse the whole thing you get one four two three right and then if you flip two uh which means you flip the first two elements then you get four one two three uh and next step you flip four so basically you reverse the whole thing so you get three two one four right and uh last but not least you get re you flip three which means that you flip the first three uh num numbers and uh so basically you get one two three four right so basically uh you're just giving up like a non-sorted array and you have to non-sorted array and you have to non-sorted array and you have to uh somehow like get it sorted to one two three four but then your output is actually the flip functions like the k number so there are many ways uh to do the pancake but i just want to quickly share my algorithm so basically because i have to sort it so i would just fix at each step let me just copy my original this is the original input so because i have to keep it sorted so my algorithm actually uh start loop from the back to the front and at my each step i will get the largest number and bring it to the back for example right now my eye starts from the very end and my largest number in the ray is 4 and i somehow i have to get the four here but using the flip function i can only like change the first three so change the first few elements so how can i get the largest till the end so my algorithm is bring the largest find the largest number and bring the largest number to the front of the array so basically reverse this part bring four to the front of the race so uh you will become four two three one after it's becoming four two three one i just need to c flip the whole thing and bring the four to the end so the rate will after reverse the whole thing you will become one three two four also i am done with this index and i decrement my index at this point i also want to find the largest number from zero to i and my largest number is three so i also try to bring the three till the end how do i do that the same bring the largest number to the front and then reverse the this subarray so i will flip this two numbers and bring it to the front so the ray will become three one at this point i can just flip a rake i raise to bring the largest number to my eye so the ray will become one two three four uh two one three four sorry okay right now i'm done with this index i decrement my eye and at this point i do the same i find the largest number and bring it to the front right now it's at the front and then i bring my front number to 2i so it will become one two and i decrement my eye so i loop from back to front and do the whole thing so uh so this is my flip function so i'm giving a k so basically i can flip uh the first k uh first k plus one numbers so k is actually index so basically while my start is less than the k then i would just switch the start and k and increment and decremented indexes i don't return anything because my array is like modified uh flipped in place okay that's my helper flip function so in my main function as i said before i loop through the end from end to the front so for eyeing range length of array minus one that's how you loop from back to front and then i call what remember in my algorithm i always have to find the largest numbers index right so for example in my original array when my i is here i have to find the largest number force index which is three right so that's my helper function to find the largest number index so initialize it as zero and whenever i see a number index of the value is greater than my largest numbers index that i update my largest number index and return so this is basically a simple helper function to find the largest numbers index so what i do in the main function i will call my helper function find the largest index get the index right and i initialize my result array and append that index plus one so for example uh right now when my eye is at here what is my uh index here what is my largest number index it's going to be force index which is 0 1 2 it will be 2 right so but like k is 1 based so i have to append index plus one and also so basically and i call flip array index so basically i bring the my largest number to the front right after doing that remember in my algorithm after bringing it to the front i have to flip the whole thing so three to four becomes four two three after this thing i have to flip the whole thing right so i my result append i minus one i plus 1 so basically my ira | Pancake Sorting | number-of-recent-calls | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | null | Design,Queue,Data Stream | Easy | null |
133 | hello everyone welcome to my channel let's write up the solution for clone graph so the first thing we are going to do is to create a hash map so the reason we do that is to be able to access it the clone nodes using the original node so in java we can do something like this and the type will be both nodes a node and we're going to create it outside of the method so we can access it when we have recursive course and we don't have to put it in the every single time and inside the method clone graph method first we can check if the node is null it is possible that the original graph has no node so we can check it here and we can just return no and next we can put the node and its clone to the map so to do that uh we can do map dot put and we need to have the key first and the value so again the key is going to be the original node current node and we're going to create its clone node and add it to the value so in this case we can do something like new node which will create a new node the value inside is going to be the same as the original node so node.vowel as the original node so node.vowel as the original node so node.vowel and after that we can check uh the current node's neighbors so we can iterate through the list of the neighbors so we can do a for each loop so we can do node never we can call it neighbor and the list we can access the list by not dot nodes dot neighbors and inside the for loop we are going to check if the hash map already contains or already has this neighbor meaning we are going to check if the neighbor's clone already exists so we can do not map dot contains key so we are going to check the key or original node because uh the neighbor object is an original node so if the map doesn't contain the key neighbor then we're going to call this function again chronograph with the neighbor node and what this will do is this goes back to the beginning i check if it's not null and what this will do is it's going to create clone node and put it in the hashmap and it's going to check its neighbor so this is basically a depth first search so after this recursive call and when it returns it's going to have the neighbors clone right so now we know the there's going to be a neighbors clone so what we can do is we can update the nodes clone current nodes clone and we can say that the neighbors clone is node's neighbor current node's neighbor so to do that we are going to say map dot get node this will get the clone node of the current node and once we get the clone node we're going to get its neighbors list and we can just say dot neighbors and we're going to add to the neighbors and linked in linked list there's a function add we can just add to the list um inside that we are going to add the neighbors clone now we know that it exists so to get the neighbors clone again we can use the hash map it's going to be in the value of key value pairs so map dot get and we're gonna pass the key which is going to be neighbor so neighbor is the key map dot get will return the value of the key after that we can just return to clone node of the current node so to get the clone node we can use the hashmap again map.get map.get map.get current node is node so this is basically it the code looks really simple but we have a recursive code so there are many different operations started down behind the scenes but the code is actually pretty simple if you like to see the detailed explanation of this problem click on this next video or click the link in the description you | Clone Graph | clone-graph | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node. | null | Hash Table,Depth-First Search,Breadth-First Search,Graph | Medium | 138,1624,1634 |
87 | Hello Google, let me tell you the steps, see the steps, like the first string is great, okay, so we have to cut it at any random index, cut means split, two participants, first part Hindi, second part right, what to do after that, now separate on this part. And from this part, let me tell you first of all, here I have 0134 here, spring way bill play with D index because splitting the string and then peppering again is S1 and the second one is S2 what is that name done okay Where is our I here we are hitting it split from here, okay, now what I said yesterday, either do it, then first we say, let's see the swapping condition, let's see the Mount Abu condition, our first in this What has to be done? Look, if we are not swiping then look, you have to do partition. Our string will be divided into two parts. What will come first part? Look at the first part. If we have cut from here in this one, then where will it be from now, meaning it is not necessary. That will be done from here but it will have two compares. If you are not doing it then its first element is first how to do the function tomorrow. How to do the function tomorrow. We will give the function after passing one, right L2 and 8g and we have to say that L1. Whatever is from L2 to R1, is it equal to L2 to R2 or not? This is what we have to compare, so we will talk about this in the beginning, but now this is where we have to do the operation of splitting, okay from L1 to Lake I. What will its right become? L1 + I is not L. its right become? What will its right become? L1 + I is not L. its right become? What will its right become? L1 + I is not L. One plus string. What will its right become? If we are not swiping then the first part will be compared to its first part. What is the first part of this one? What is our L2? The lake will go till here, see I means we have given two indexes, so in this also we will increase the next two by how much, okay this is from L2 to lake plus i, this is ours, starting from L1 + i + 1. ours, starting from L1 + i + 1. ours, starting from L1 + i + 1. Look, L1 is ours, this is where our second will start, whenever we are doing it, ours will start L1 I Plus One, this is our original, where is this, where is our start, here this L2 Plus I Plus One Start dividing by , both of them should come equal, which should come to dividing by , both of them should come equal, which should come to dividing by , both of them should come equal, which should come to you, how should both ours come, okay, if we swipe, ours will be less, then what will we put in between them and condition will be imposed and the condition is either do this, don't forgive or else. If any one of these two gives a proof, then our answer is correct. Okay, so there will be another condition between them. Now see this one, if we are swiping, then see, the starting point will be from the first one. What is the starting point on this one ? Three will remain from L1 till ? Three will remain from L1 till ? Three will remain from L1 till where it went, it goes from L1 till I and from L1 till where the album starting keeps us from seeing that it will be from here and its second partition will come from where will it be L1 + I + You are partition will come from where will it be L1 + I + You are starting from 1 second, which I am writing below, just see the index, what is it, isn't it our gray, this is the representative for gray, where is the index of gray from, the index is from L1 to the side of lake F1 and one From where to where is the index, from L1 + I + 1 and with whom to compare, now if we from L1 + I + 1 and with whom to compare, now if we from L1 + I + 1 and with whom to compare, now if we square it, look exactly, last time we had kept it exactly that take it from L2 to I, this time from L2 + I + 1. that take it from L2 to I, this time from L2 + I + 1. that take it from L2 to I, this time from L2 + I + 1. Our change has happened, what has changed, where is our gray, this time we are behind, right here, where have we come, we have to compare with the one behind, that is, with whom we have to compare, look friend, with whom we have to compare with here. Okay, so what is this index, our r2 - I and you minus I am starting, what is happening is that look, this is r2, so how far back from this I have to go, I look here, what is the value of I, two indices were to go further. So here we will say that it is defining, going back there is where it is going to start and how far it will go only further, if this first oxide is going then it will go till there, where is it going to start, this is also our L2. Did it start from or not? Where did it come here from? Where did we go to start? How much mines will have to be done in r2. Look, this one has gone till here. What is the meaning of this one? Look, we have taken out this one here and placed this one here. Starting from this one r2 -1 r2 - I So how far is ours where we have to see the second -1 r2 - I So how far is ours where we have to see the second -1 r2 - I So how far is ours where we have to see the second string for one less than the first string we were starting from, our condition will be, all we have to do is what we will collect tomorrow and apply it. In this we will just write these things exactly and after that our logic will give its answer, so first of all I find the value of N, it is very important, only this has to be put and look in this, I have to read from the very beginning and there is a function to compare and right. And what do we have left, so what do we have to do with the random index by returning it? If we have to split Apple from the party, then where will we start, zero means start cutting from zero, right, and till how far should I cut, till what I said. We will write the thing from left one mine, here what is L1, from L1 to L1 + I, so okay, we will L1, from L1 to L1 + I, so okay, we will L1, from L1 to L1 + I, so okay, we will do this One plus has come, we have to go till here, what we have to compare from L2 to L2+ I. Tax And here it should be like this, helper, this time what we will say is that from our L1, this thing will be from the album, take L1 + eye cap, with what to sharpen it, to crop it, that is, r2 - to compare with eye and till where. We have to know where will the whole second start from, what will we return if we have done the next one, I am running it, the solution is working fine but we will have to memorize our condition, we can write right one left right function so it is working. Find this question and solution of this problem | 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 |
146 | political problem 146 lru paths yeah so let me first explain this problem and then I'm going to explain in whiteboard about what kind of a digital structure I'm going to use and then I will write the code in the code editor yeah so first this is a lru Class lru cast means at least recently used yeah this means inside the case there are some values yeah for example this is a test let me write a test so yeah I have a one to two this is my first value and the 223 is my second K value pairs if I already visited this K value pairs one and two yeah it means this is value is a most recently used and this 2 and 3 is at least recently used yes so if I exceed the capacity for example I want to add another T value pairs for example it is a three and a four but the capacity is only two what would I do yeah I saw the first put this three and four inside and will fly inside where at which place should I put it inside because if I put it inside it should be the most recently visited and then this is 2 and 3 is at least recently deleted I need to take this two and three out and put three and four inside yeah but other dictionary is not ordered if we have a ordered dictionary it is okay but I'm not going to use all the dictionary to solve the problem because for this problem I'm going to use a double A linked list because if we have a double linked list we can easy to yeah implies this get and put function to deal with the recently visited or most recently visited or the list recently visited yeah let me go to the Whiteboard to explain why I'm going to use this kind of a data structure I need double A linked list with cash is a basically a dictionary in Python and then I'm going to write the code in code editor yeah as there may be more than 60 lines of code yeah it may make any kind of mistakes but I'll debug it yeah because this is also for the real situation if you are writing yeah more than 50 or 60 lines of code it may have some box especially for this kind of linked list problem yeah now let me go to the Whiteboard to explain the data structure for solving the problem and then I will go to the code Editor to finish the coding yeah I already draw a double A linked list now let's adjust go to the doubly linked list and I will explain what I'm going to do after that I'll go to the code Editor to finish the coding yeah so this is the double linked list I'm going to use so for example if we have an empty double A linked list we only have head and tail yeah this is a head from the left side and this is still from the right side level capacity say is our capacity is only three yeah if we were to insert a node so these two misses a k and the value is 6. yeah if we were to put the K value not this is a k value node inside at which position we should do we should first Define our most validated node and the least visited node so I will always Define the most visited node at the right side next to the head and the list visited node at the and finally the most visited at the left side this is the left side and the least visited node at the right side next to the tail so this is the least voltage node and this is the most visited node so for the first node if I were to insert this 2 and 6 2 is k6 is value so if I were to put this not inside I first put it inside because anyway this is also the least visited or most visited it's the same if I were to put another one 1 and 4 I should put it at the this position it should be next to the head because this is the most visited if I were to insert another 123 I should put 2 and 3 not at this place and left to the head because this is the most visited yeah next if I were to insert another node maybe this node is for example it is a one and four what should I do so this is what we are going to use the put method if we are going to use the put method to put a uh one and four naught so this one is K and four is value if we were to put the inside so first of all we're going to put it at the position next to the Head yeah and then connected to this three and the two naught after that what we're going to do we're gonna remove this list recently used not so this is basically the function of lru test we should remove this one yeah and if we want to get a value for example we wanted to get a k value pair if we were to get a k of one and then we want to get the value of 4 take this node yeah after visit this node this is our get function after we're using the get function we should also take out this node 104 and move it next to the Head yeah so this is basically what we are going to use we're going to have a double A linked list and we're also gonna have a test so this case is used to store K value pairs so K is a yeah the K are rotate inside of the description is a number and the value is a not so inside the node it's a doubly linked list not inside the node there are also K value Pairs and there is also previous at the next because it's a double linked list why we use the doubly linked list because we can use the get function and put function in o1 we don't need to Loop through the list yeah if we need to take out one node just take it from the tail yeah if we need to put it to the most visited position we just put it next to the Head yeah this is a circle one and also we use a test because cash is O with o1 because K value appears we can take a k with value it is also A1 this is why we use Test Plus double A linked list yeah now I'm going to imply this kind of a method to my code yeah now let's go to the code editor try to finish the coding yeah this coding is a little bit yeah longer than other than even hard problems because hard problems is not so many lines of code but this problem May be seen as a hard problem because there are more than 60 lines of code and it's really difficult to write bug-free code for difficult to write bug-free code for difficult to write bug-free code for this problem yeah now let me Define the node as I said we are going to use a doubly linked list so I'm going to define a list node yeah so for the listener I'm going to use the F Insider function inside class we can use this init with the self and the K value pairs yeah why I need a k value pairs because I wanted to connect this K value inside the doubly linked list node to the K value inside the dictionary inside of my test I would to connect so the case would be initialized as 0 and here I will use a veil through the initialized to zero and inside I'm going to use a self Dot okay so they're equal to the pay and self dot well should equal to my Bell and the self dot previously equal to noun and the self dot next should equal to noun so this is basically the Define of the doubly linked list not yeah now I'm going to prepare my variables for this class lru class so instead of the init I'm going to Define some variables so first of all the capacity should itself dot capacity should equal to the capacity inside the function and I'm going to you define another variable self.size because I'm going to variable self.size because I'm going to variable self.size because I'm going to check if the size exceeds the capacity or not it will be initialized from zero and we're going to Define our test so the class will be a dictionary then I'm going to prepare self dot head and the tail because from the beginning I'm going to prepare some dominant this is a source for easy calculation for easy operation for the doubly linked list so self dot head equal to self dot tail equal to this list node yeah the list node I divide so I'm not going to put any value inside because it does matter it's just a domain node yeah let me go to the Whiteboard it means here I just prepare a dummy node for the head and another Domino for the tail and then I'm going to put a yeah put the knot inside if I use the put function if I use a get I need to get the K value pairs I use the K to get the value for the not now let me write the uh yeah we should also connect to the domain node so the self dot add dot next should equal to self dot tail and the self dot tail dot previous should equal to self dot pad yeah I'm not sure if I Define all the variables but let's write the get function if I need any variables I'll put it inside in it yeah basically I think it's enough for all of the operations our guide and put but let's just do it let's have to do the get function first so for the good function we need to check this K value if it is inside yeah if K not e self dot class so here I imagine I've already put some values inside so I just need to yeah use this get function first yeah so if K not in self DOT test we're gonna return a minus one this is what we are told if not exist we're going to return minus one if it is exist we're gonna get a nod here for the test the K value pairs the K is the number as I said before the value is always a naught so the node is a self DOT test and it takes the K so I got the node what I'm going to do with this node I'm going to take this knot out and connect it next to the Head basically it's here for example if it is this one I'm going to take it out and connect it to the head and with this first knot this one yeah so there are two steps but I'm going to use a function so this function will be called yeah so here I'm going to write a function this function will be called self Dot uh move to add this move to ahead means I will take out that node and move it to the head yeah and add it to the head so I'm going to take a not variable so the not is this nod yeah after that I'm going to have a return the return will be not DOT value not DOT well because this is my list node I have a bell and why because here if we use a get we're going to return a number it's not a nod so we have to return not the daughter well now this is basically the get function but we didn't write our API yet we saw the try to write this move to head function yeah now let me put it just below the put and self dot move to head I will take a node so there are two steps for the first step and I'm going to use a self dot another function I will disconnect this node yeah and inside I'm going to take this node variable after that I'm going to write another function self dot add to head because I'm going to add this number to the Hat I'm going to take this knot why I use two sub functions below this move too hard because this add to head we'll use the two times I will explain later why I use this for two times yeah and then we're gonna write the sum functions of self.connect the sum functions of self.connect the sum functions of self.connect now let me write a self.connect now let me write a self.connect now let me write a self.connect let me Define the disconnect node function so let me Define the self-daughter net let me Define the self-daughter net let me Define the self-daughter net first Define the self dot disconnect node first so the disconnect node should be here death with disconnect node and inside I'm going to still take this node and what we are going to do we just need to disconnect this node so for example this is another one for we are going to disconnect how should we disconnect so this is the node so the node dot previous it is this node yeah it is this not at all the previous dot next it should point it to is should point it to is should point it to is this not yeah so not DOT previous dot next so the pointed to not DOT next now let me write it from the code editor so inside the function not DOT previous dot next should equal to not DOT next similarly not DOT next dot previous so equal to not DOT yeah let me think not the daughter next dot previous should equal to not the dot previous this means we've already disconnected with this node and also we need to write another function added to add and for the added to head we can write it here with a definition of the function with a depth and a here we're gonna write a the add to head for the add to head basically there are four steps let me explain one by one so for example this is the node I'm going to add it to the head so first step I'm going to point this node through the pointed to the head and from the tail it should point it to this node yeah so this is one step this is the step two I'm going to finish this two steps first yeah so the not that previous three equal to hat not DOT next should equal to head dot next yeah foreign connect from the head to this node basically this line I'm going to connect this angle so how I'm going to connect so the head Dot next before heading down next it connected to this node but now I'm going to connect it to my node here so the header dot next should equal to naught add self dot self Dot add dot next should equal to not now we only needed our last step we only need to connect from this node to another knot yeah so how should we do because this node this connection has already been disconnected we cannot use it anymore so we have to use yeah not DOT next uh let me check how should we connect uh yeah this we still have this connection so the not DOT next yeah because we have a disconnection so the not DOT next dot previous should equal to I will not this is either not DOT next dot previous so you could order not so the last line will be not DOT next dot previous mod.lex dot previous should equal to mod.lex dot previous should equal to mod.lex dot previous should equal to the node I know it is annoying but we have to do like that because this is a basically what's the problem asking us to do we have to write the very basic data structure yeah at least for python we see so many lines of code foreign languages it might not even like more than 100 lines of code yes so we already finished this move to head yeah this is we've already finished our get function now what we left is only the put function now let me check for the put function similarly we're gonna do this if K not inside the self.cast yeah it's also two steps if it self.cast yeah it's also two steps if it self.cast yeah it's also two steps if it is not inside what we're going to do we're gonna take this yeah if K is not inside it means we're going to prepare a new node so for the new node I'm going to yeah use our list node so the K value pairs I'm going to take this K and this value yeah this means I've already for the put I've already prepared a new node yeah after I prepared this new node I think I need to connect this node to my double A linked list so where should I put I should put it for example this is the list if I were to put a new one I should put it at this place I should yeah if it is a new node I will put it next to the head because this is the most recently used yeah now I would to put it next to my head and what should I do I should use the self dot here I should use add to hat because I don't need to disconnect I only need to add two heads this is why I write a I write an end to head function because I will use it two times so self dot add to head with this new knot at the same time self dot size to the plus one because I used to put a new knot inside the self dot size so long so plus one and this would also update the self DOT test why because we need to prepare the case inside because for every time we are going to tag if this key is inside the case or not yeah so self DOT test with this k should equal to our new node yeah basically this is a checking if we can put this new node inside yeah so we're going to put this new node inside yeah if what about the size exceed our capacity because here we have another variable capacity yeah we have to tag if self dot size is more than self dot capacity yes if the size is more than capacitive this means we have to take out one naught for example the average capacity is three now it is a four we have to take this out yeah take this node 26 out how should we take it out we have to write another function move a tail here I will yeah write another function it will be called move Tail so here if a self.s size is more than so here if a self.s size is more than so here if a self.s size is more than self dot capacity this means I needed to Define another variable here I will use removed and I will call a function self Dot move Tail this means I will move the knot from the tail yeah but the tail is just a domain node I need to take the Knot Before the tail so what is that it is the self Dot basically I'm going to remove this node yeah what should I do and I'm gonna Define this move Tail function first so from here below I can Define my function move Tail and inside I take a node how should I move to tail basically I'm going to disconnect the node yeah you see we also use the disconnect node two times this is why I would to prepare two functions one is a disconnect one is added to hat yeah so for here we can I can disconnect the nod I will call self dot disconnect with this node this means it has already been removed and what I'm going to return with this node yeah why because I'm going to use the K value inside this node so this is why I need a return with the node so for here the put and yeah so for here the put we have removed is the node we needed to prove we needed to remove but we need also to update the self.cast update the self.cast update the self.cast yeah so how should we do that self Dot test with this k self DOT test dot pop we need to pop with a removed dot k because it's removed is assessor node and inside of the removed we have a k value pair we can First Take This K this means the k for the test we just need to pop this removed dot k yeah now basically uh yeah now basically we finished the attacking for the exceeding the capacity yeah now we have another condition if K is inside self.cast what should we do inside self.cast what should we do inside self.cast what should we do we can start to take this note out first because it's inside yeah we can copy this code cell DOT test key this is our new node what should we do next we just needed to yeah because this is not inside we do some operations this is inside but we also need to yeah move this node disconnect yeah we should update let me update the value first so not DOT Avail should equal to other value from here and then we are going to move this node yeah for example let me well I have to it takes more time even I cannot uh yeah let me it's not working here it's not inside but basically here this is not value I update the value of the knot first yeah the first step and here I take this knot out and update this value and then I just needed to disconnect this node and put it to my new positions and what should I do I just needed to use the move to head function self Dot move to head with this node bottom also go into return not dot valve yeah let me tap I have my node and I've updated the value of the node and then I move to the head and I just have to return uh let me suck I don't need to return because this is a put function I don't need to return so I just need to update the not DOT value and then move it to head yeah now let me run it to tag if there are any mistakes I believe it should have mistakes normally so many lines of code yeah self dot add to head takes one producer let me check self dot yeah so inside I should always use a self because this is a class yeah because this function is just below the class I should always use a self otherwise it will be wrong yeah now let me put the self inside of my functions now let me run it to select if there are any other mistakes the removed typo let me copy the removed now let me run it again yeah luckily for me it works now let me submit it to Sag if there are any mistakes in the old testing cases yeah I hope I can pass otherwise I have to record it again and again I can never finish it yeah basically the idea is a difficult to think about and also for the implementation of the code is also difficult because at least there are like more than yeah 50 more than 50 likes of code at nearly 60 lines of code as you can see the speed is very fast because everything is just a one because we use the hash table and with the doubly linked list and for every guide and put it is just one yeah thank you for watching if you think this is helpful please | LRU Cache | lru-cache | Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`. | null | Hash Table,Linked List,Design,Doubly-Linked List | Medium | 460,588,604,1903 |
1,601 | hi everyone in today's challenge we are going to solve this problem the problem name is maximum number of achievable transfer requests and the problem number is 1601 only case as usual first of all we are going to clearly understand this problem statement after that we are going to move to the logic part we are going to see how we can solve this problem what is the logic to solve this problem and after that we are going to move to the implementation part we are going to implement our loads you can see plus Java Python and JavaScript profile guys now let's quickly see what this problem is right the problem says we have n buildings numbered from 0 to n minus 1 all right each building has a number of employees its transfer season and some employees want to change the building they deciding right so guys simple thing we have uh n number of buildings right there are n wielding so let's write a n buildings point and here the labels are nothing but 0 to n minus one right so fine and after that in each buildings there are some employees that is our support line now in that employees want to decide or want to change their building right I hope it makes sense so let's say there are four buildings let's say building one building two building three and building four line now there are some employees in each building right let's say there is some nuclear five here six here's four here three right they want to change their building right okay you're given an array request will request a file from comma two represent an employee request to transfer from building from y to building to I right Simple Thing guys now let's say the burning platform building one here let's say this one employee from this building want to change their we can say want to change his building from uh this building to let's say this building uh four building right now what I mean by here that one employee from this building want to move to this four building so how would this address look like this ad will look like one comma four that means our employee want to change from building one to building four right one to transfer or want to move from building one to building four this is already Loop like right same thing they are given from to do so from one building to four building all the buildings are full so a list of requests is achievable only if for each building the net change in employee transfer is zero this means the number of employers leaving is equal to the number of employees moving in now guys what the means guys they means here they means uh like old let's say in one building we have only five room sides so that means the oh this old buildings whatever the buildings given and buildings are already full right there's no empty room available or we can say there is no empty block favor right so an employee can only transfer to that building if an employee is also moving from that building right this Burning platform this one building can only move to these four building if this employee are moving to any other building right private making sense let's say uh this one want to move to these four building so this any and any employee from this four building also should move to any other building then only that you can enter in this building right otherwise the space is only full the simpler cannot insert or cannot transfer to this building right now they have your same example if ns3 is so on and so on that don't we don't need to see that now the last thing is written the maximum number of achieval requests now we have to return the maximum number of achievable equations we can achieve we can move their right so let's see with example then you can have better understanding with this problem so here we have this example right so you uh we have request is nothing but this array n is going to find that means there are total five buildings and output we have to see how they come file right so guys the first equation nothing but 0 comma one so that means imply one to move or transfer from zero value to one building right so you can see from zero building to one building so you can see this we have represented by X you can see my color so this is nothing you can see this one like after that one employee want to trans uh transfer from one welding to zero building so from one to zero here you can see this is nothing but we can say a right we have given the name nothing but here one note a we have to see this one right from one to zero I hope you can see one two zero that means from this is nothing but B right then zero to one again zero to one this is what we have seen y right then one to two in the theory this one a we can say this one see right I hope it makes sense so we have seen all the we can see employees name a b we have given us some randomly name right now what we are going to do we are going to say uh how many requests this requests can be possible Right There are two or six requested so how many requests are achievable so see only so you can see if we consider only this thing that means it is achievable right when it plays going to this building and one employee coming to this building so both is going to remain same X enter here and buy or let's say X come here and any place from this building we come to this building zero so both remains same right number of implies you may say no any empty space no any extra space right fine so we have achieved two requests for so far now in the next exam next C can we move y here so let's see that money plug moving from zero B right from zero building moving to building one and one implies from building one also moving to building two and one from building to also momentum uh building zero so if I just remove all this thing now because we have already seen X and Y X and B they have been going okay now any place going from this building fine and moving to this building right so that means there is one extra space now we should not be possible so one implant there are some moving to another building to this one so here now balance so there is no extra space no less space right so this is now completely fine so here's one extra space five and here's one less space because when you have bent from this particular building right so we find there is one extra so there is also one plug going from this building to this building zero so that means one extra space over there that has been uh now defined it is we can see there is a fixed number of room survivors so fixed number of implies are there right so there's no extra space now and one employer come to this building so there was one less space because one employee went from this building now that also got full right so we can say now this circle has fulfilled all the builds buildings right so there is no we can say uh we can say less number of rooms available or the NXT employee will do so they are completely uh we can say fulfill right so we can say these three also can be possible Y A and Z right so we can say two plus stage nothing but total five so we can say total five requests are achievable now let's move to the next this is C only so if we move any from this three building to four then one employee this building will have one extra space right should also move from this building as well right but you can see that no employer moving from this so this request can't be achievable so we can say total requested Network five which can be achievable so you can see output as well five now let's quickly move to the next example like as you can see one employee is moving from y to this building one to building two and when you play moving from building two to building one that means it is a neutral so we can say it is possible so Y and Z is already possible 2 is possible now how many planes moves from the from zip so we can say nothing but statement now and you have seen the example as well so I believe you must have a better understanding now in the problem statement now let's see how we can solve this problem what is the logic to solve this problem right but nothing guys we are not gonna do much here because the logic is going to be really simple but we have to do nothing but we have to use all the combinations Simple Thing guys we have to use all the possible States so what I mean by here see you guys so we have this added right one zero this one right let's write all the same here gonna give up node B5 DF just but uh letter so that you can understand what we are doing let me move all this thing so let me write hello and here I am saying that 0 comma 1 one comma zero comma 1 here also one comma two comma zero lasting nothing but three comma four right so guys this is nothing but our array request array so what we are going to do we are going to say fine you don't need to do any user recursion this is zero index is one index is second index is third index is fourth index is fifth index is right now what we are going to do we are going to use all the possible combinations or all the possible state so first time we are just going to do this particular part we are going to say fine just uh do this particular request right or I will say that uh just try to achieve this particular request only so see whether you are getting uh we can say all the buildings are all now neutral or not right how we come to know that all the buildings are neutral we will see that particular part later but if we try to achieve this particular part and still a building is neutral so we can say fine that is a good case so we can say this request is possible like and here we are going to see this particular part now we're going to say uh next possible state is nothing but try to do this like this is this receivable if we do this both fine this is also possible then we are going to move to the next one if this is evil find this is also possible then we are going to move to this one means we are going to use all the combinations I know you know what is the combinations means like all the combination which can be possible from this all possible six length of an array right so there could be a we can say a six you can try auto combinations part they're going to be more than that particular things but we are going to use all the combinations from the six or after that we are going to check is this uh will all the buildings are neutral or not and for that what we are going to check we are going to create one array buildings building so in easily nothing what we can say there's all the values are zero right and these are nothing but indexes on zero and X is value zero one index value zero second index value zero third and x value zero for the index value fine now what we are going to do we're going to say if we're removing this using a first request so you can see on zero building one person or one replace going to one building right from zero to one so on zero building we have to decrement by one is moving from zero so there is space left for one employee right and move into which building one building so on one they are going to increment by one because they one strap layer came so this can say that if we achieve this particular request that means we can say we cannot uh getting all the buildings neutral so we can see this is not possible this is not achievable if we use single this particular single request item file and here if we take another request as well here we have what we are seeing that 1 to 0 right that means One impact from one is moving to the zero so that means One X space is getting left for one right an employee is moving from one building so that means we have to reduce by one so from one on that one index we are reducing so we are getting x 1 by minus one zero and moving to which uh building zero so we have to increment there so we are going to increment minus one plus one is natural zero so now if we see all the buildings are neutral right so we can say this to right so we can say these two are achievable right so we can say now total impressive nothing but two which is achievable so now to this we have to keep doing for all these so we are going to do then this one it's not like that we are doing with this only we are gonna separately also do with this one and also with this one means we are going to use each and every possible combination right I know you I hope now I believe you nobody's combination if you don't you can try searching on the Google it's a small math concept that combinations right which take all the possibilities right so that's all guys we are going to do this particular part and we're going to keep checking for each state of the combination whether it is neutral or no if it is a neutral so we are going to return other one otherwise we are going to return false right that means zero right so that's all we are going to do let's move to the implementation part there you can easily understand what I mean by these combinations and what I mean by checking the neutral state for buildings everything will get a better understanding with the implementation parts let's move to the implementation right so here guys first of all I'm the python so what we are going to do we are going to see okay definable functions all and here index is going to tell us that uh which request you are taking right now and after that what you're going to do you're going to say buildings right here we are going to say if index is nothing but we can say uh length of request right length of request so what we are going to do we're going to be fine if it is equal to that we are going to say okay check all the buildings are we can see neutrals or not right so because if whole and we can see here uh old value is equal to 0 for Value in buildings so this is how we are going to check if all the values are equal to zero for Value in buildings so what we are going to do we are going to say fine uh and you have to return nothing but zero otherwise you are going to return nothing but let's say infinite protein which means that means if this is not possible right now and we apply it minus so let me get a minus infinity fine and this is done if it is not equal to the length of request that means we haven't posted uh process all the requests so we are going to move to the next request and here we are going to check first of all let me use an uh here internet lre cache that is means nothing would be memorize it and for memorize it we have to pass this building as a double we can't pass a list because it is so we are going to convert into a list so we can say now new building I will tell you why I'm doing these things buildings and here we are going to say now new buildings right what you're going to do you're going to say request of that index of zero so we have to decrement by one isn't it okay and same thing new buildings is request of index of one that means to pitch building that particular employee want to move right so we have to increment by one because there is going to be one extra employee now right once this is done we are going to call this function again right but see I have converted into list and then again I will pass into a Double Y because we can't we can say change in the pulse because double are invitable right and one more thing uh there guys we have used a new building variable just because we want to but we want to use a knapsack like algorithm here that means either take it or not take it right so here we are going to say either you have to process this request or you don't have to process this particular request right so we're gonna say Okay first time if you're processing this request you have to implement weapon that means this process uh this request we have process and you know all this functions the same so index plus one and buildings you are going to pass Now new buildings but you have to convert into a couple new building set and same thing now we can say comma no comma we have to say this is all don't we need to sold we have to use maximum here so here comma we're gonna say now either you have process either you don't have to exercise this particular request so there was a sold same index plus one the building will remains same right buildings or I may see so this is what we are going to do we are going to return this particular part what happened to this I don't know what is this right so fine okay here what we are going to do we are going to say return this particular thing right return this would be I hope it makes sense right so that was the simple thing we are going to do now what we are going to do we are going to say fine uh we are going to call this function sold and here we are going to see indexes zero buildings uh we're gonna see nothing but let's pass this early empty so we need a setup and here we can say 0 into n right so this is another one we can say a buildings right now we are called written about this building so let's run this code right so you guys can see building spelling in mistakes so let's pass here building now let's run this one you can see guys all the desk is passed right so let's try to submit this code as well whether it's not to final note I hope guys it should work right so you can see that it successfully got submitted so we have successfully sold with the pythons but we have done nothing but we have to use uh just all the combinations so first time it will take a second time it will also not take this thing so it's gonna use all the combination for this and this is a next better way also which we can see now with we can see let's move to the Java now and here what we are going to do we're going to say fine uh let's define one function right so here first of all we are going to Define one array which is nothing but let's say given name buildings so there we have used a couple of n size but here we're going to find an array of buildings which is of let's say how many is maximum request can be there building can be there so maximum building can be there let's see vaccine building can be the 29 so we can use at Max 21 right and we are going to use it 25 right is to mix uh better but here we can use also 21 which will also work because at Max there could be 20 right so 20 also will be possible no 21 20 will also be possible like fine now what we are going to do we are going to create one function that is Network sold as we have seen in Python here we are going to see nothing but intend and enter request and here we are going to see index and nothing else right and here we are going to see if index is equal to request dot size that here because if index is equal to size we are going to return nothing but what because it counts zero in this buildings right so you have to pass here nothing but uh buildings building uh so you don't need to pass because it is probably variables what you can pass here you can pass it and only right and here you have to say if count 0 is equal to we can say n right if it is equal to n that means what you are going to say you're going to say or we can say right if it is true that means we can say written zero otherwise you have to return integer to Min value right once this is done we are going to say fine if it is not the case that what you are going to do you are going to use all the combination right so you can say buildings of index you can pass it let me just pass here request of idx of 0 right and here we have this one in decremented because employee is moving from this particular building and next is another buildings of request buildings so we haven't used I here right and buildings of request of idx of one you have to increment this because an implied is moving to this particular building right after that we are going to call into result one which you want to make sure sold and the request is going to also mean same Quest request and here index you are going to implemented by one right after this once you have to run this thing you are going to do the same thing again and white is so see guys here what we are going to do we are going to say fine you have all this function for this particular case right so first time we have taken it right the second time you don't have to take this right so whatever we can do we can say make this earlier plus and minus one is right this become neutral right so we have first time incremented second time first time decrementary second time we have incremented right so same thing is going to do for the building one as well after that one we this is done we are going to pull the same function again with the result to variable so this is natural we can say did not take right and this one we have taken so let's give a variable easier take now we can say no take right return you have to return math Road maximum either okay if you are taking it then you have to add one otherwise no take right so if it is a whatever the maximum value that is going to return after that what we are going to do we are going to call this function over here in this function maximum request so we can say solve n is going to be same request is also going to be the same and index is going to zero right now once this is done we are going to say written this particular thing before that we have to Define one function that is number count zero so we can say probably Boolean and count zero right and here we're gonna say intent right so we are going to say 4 enter is equal to 0 and less than n let me write n and I plus here we are going to say if this particular buildings of I and here if it is 0 then fine you have to increment your counts you can say count plus or we can say okay fine keep going otherwise later password so we can say later parts if it is not equal to zero right otherwise you have to keep return 0. right fine now let's run this so what we are doing here this function is checking all the values in this building till n should have value zero if it is not then you have to return fast right so this is giving an error what is that this is for function right so what is right let's run this code so let us solve what we have done we haven't given any space here let's see now hopefully it should pass right it should pass all the test cases so let's see you can see all the risk is passionate here to submit this code as well so by this we are going to assembly with Java as well and that's really cool what we are doing just we are taking and now taking it and we are written it if that is possible if building is a neutral right now let's move to the last notes third programming language which is C plus and here first of all I'm going to divide one array so let's say integer the rename is buildings empty right so by default you get take all the values in zero right so that's why we are not making it zero now we are going to look here when I say four no four we are going to Define here also one function right so we can say print sold the function is going to take n and then it's going to take this Vector of request so we can copy this only right so I can write this much code just copy all these things fine and here what we are going to do we're going to say index wait so here we're going to say if this is the case if our n is equal to node n we can say and here we can pass our uh buildings dot size what size we have to say begin right or we can pass it directly here like this big on buildings right we're going to build this comma we can not begin we can say beacon of buildings and plus n right plus and after that we have to check which one zero we have to count zero if this is equal to n then what you are going to do you are going to write an 11.0 otherwise you're going to write an 11.0 otherwise you're going to write an 11.0 otherwise you're gonna return okay this is the case so I hope you are getting this if we reach to the last of the request that means we are going to check if building is neutral or not if it will be neutral always if all the values in the buildings array is going to be equal to 0 for our end building set after that we are going to say if it is not the case then what you have to do you have to increment by one uh you have to increment and decrement from the we can see employees moving to the middle plane moving right so which I mean nothing but we have to implement that building and where the employee moving and we have to recommend that building where employee buildings request of the syntax of zero that means here the employee is moving from this building then play is moving so we have to decrement this one and we have to copy this one I don't know why my short condition was working here so what I'm saying that here copy this thing paste it over here and here we have to increment it but we have to take index of one that means the employee is moving to this building now so once we have implemented this what we are going to do we are going to pause the same function in take by e and after that again same thing we have to do have copy this one I pasted it and here we have to now make it neutral light first time we have to take it now we are not taking it so we can say plus minus and here we have to just hold this function with a new variable that is node right once we have taken a note take we have gonna return maximum return Maximum take command line but see here guys that means we have we are able to resolve it right now once this is done we are going to call this function over here so and we have to return this one fine now let's run this code and see what that's okay if I don't know and I hope guys it should also work right but not it give a question size what is size it's fine we are going to use S variable right do we have any more error let's see so yeah there's one more error that in the use of Undeclared identify it means so we have used a smallity do we have any more error let's see so you guys can see that one more error that is nothing but sold which is nothing but we can solve very well so we can use like this right now one more I resolved fine we have copy this right so we can use like this now let's see I hope now it should work right now so here you can see guys all the desk is power selected to submit this code as well right with this video now successfully solve with the C plus programming language so you guys can see that it successfully got submitted so we have successfully implemented with C plus now let's move to the last programming language JavaScript right so here guys first of all what we are going to do we are going to say uh first of all let's say first building buildings is going to have a new array of five right no 525 now we are going to say 4 that I is equal to 0 by less than 25 and I plus and here we're gonna see if note if we are going to say buildings okay I we have to make it zero right that means there is no employee the all the buildings are neutral right we can see in simple terms now we are going to make a one function from solve and that's all function is going to have one parameter index and then we are going to say fine here you can see if note if you can see index is equal to request total length right if it is zero you have to count 0 but for that we have to say count 0 for this particular n or we can count here as well so we can say 4 let I is equal to zero I less than n i plus you can say yes you can make uh right what we can say directly here if any of the building if um we can see buildings of this particular I is not equal to zero then what we can get we can simply return minus let's say least minimum value so we can set four six seven eight right fine that means we are going to return this otherwise if this Loop over that means all the buildings are equal to zero that means this in neutral so we are going to tell about zero you have to use a correct spellings buildings of that particular request of that particular test of index of zero we have to increment it that same thing we are going to copy and here we're going to write a one we have to decrement increment it right once this is and we are going to say lactate 1 fine after that same thing we are going to copy I hope you are knowing what I am doing now I'm just making it neutral and here thanks to that I'm calling the same function again which means it is not big right after that we are going to return one minimum not minimum maximum returns if you're taking it then increment by one otherwise don't take then we are going to call this function so let's call this function so little soul with zero index let's see if there's nothing final note right so let's run this code do we have any error you can see guys all the test is passed right so we have successfully solved with JavaScript so let's try to submit this code as well hopefully we should not get any error in summation parts so let's see so finally guys we also submitted with this JavaScript program language as well so I hope as you understood the implementation part what we are doing just we are taking it or not taking it and if you uh have any kind of doubt in the problem understanding part in losing part implementation part you can write in the comment section I'm always there to help you and if you learn something new in this video don't forget to the link button and subscribe my channel meet in the next video | Maximum Number of Achievable Transfer Requests | maximum-number-of-achievable-transfer-requests | We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.
**All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.
Return _the maximum number of achievable requests_.
**Example 1:**
**Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\]
**Output:** 5
**Explantion:** Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
**Example 2:**
**Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\]
**Output:** 3
**Explantion:** Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
**Example 3:**
**Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 20`
* `1 <= requests.length <= 16`
* `requests[i].length == 2`
* `0 <= fromi, toi < n` | null | null | Hard | null |
1,822 | um hello so continuing today on uh lead code daily challenge today's problem is sign of the product of an array um so here what we have is basically we have this sine function and we want to return one if um if we get X as a parameter we want to return one if x is positive minus one if it's negative and um zero if it's equal to zero okay and what's this x well that's just the product of the array and so pretty much we want to return the sign of the product so um press forward this one if you do that do it you get 2 here minus six you get um minus since minus six multiplied by this it would be a positive number we don't need to carry to care about the product itself and from there on it will be positive right and so it's positive so we return one so that's sort of the idea here now how do we solve it well pressure forward you could just do a for Loop literally and just calculate the product right and so the simplest solution is just to have P equal to 1 which is the product initially and just go through the array um and so we will just multiply by the number and now here we'll just check the sign so if it's positive we want to return one um if it's negative one or ten minus one otherwise it's equal to zero we want to return zero okay so very simple let's run it and let's submit and that passes okay now one thing you notice here is actually we don't need the product when I was doing the calculation here I just figured out the sign and didn't need to calculate the product itself so let's actually do that same thing here so uh let's call this to the sign right now we know that if the number is equal to zero no matter what happens next any zero multiplied by anything it would be zero so we can just return 0 immediately here right um and then if the number is negative then we have to change the sign by multiplying it by minus one because if the sign was 1 it will become -1 because the sign was 1 it will become -1 because the sign was 1 it will become -1 because then the product is now negative if the sum was -1 which means the if the sum was -1 which means the if the sum was -1 which means the product was negative then multiplying it by a negative number will make it positive and so if we multiply by minus one the sign will become one right um but if the number is positive then the sign doesn't change because if the product was positive it will stay positive if it was negative it will stay negative right so here at the end we can just return the sign um okay this should pass as well and it does now in terms of time complexity this is over in time right we're just doing one Loop so over time um and then all one space uh yeah and that's pretty much it for this problem please like And subscribe and see you on the next one bye | Sign of the Product of an Array | longest-palindromic-subsequence-ii | There is a function `signFunc(x)` that returns:
* `1` if `x` is positive.
* `-1` if `x` is negative.
* `0` if `x` is equal to `0`.
You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`.
Return `signFunc(product)`.
**Example 1:**
**Input:** nums = \[-1,-2,-3,-4,3,2,1\]
**Output:** 1
**Explanation:** The product of all values in the array is 144, and signFunc(144) = 1
**Example 2:**
**Input:** nums = \[1,5,0,2,-3\]
**Output:** 0
**Explanation:** The product of all values in the array is 0, and signFunc(0) = 0
**Example 3:**
**Input:** nums = \[-1,1,-1,1,-1\]
**Output:** -1
**Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1
**Constraints:**
* `1 <= nums.length <= 1000`
* `-100 <= nums[i] <= 100` | As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome. | String,Dynamic Programming | Medium | 516 |
36 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem valid sudoku and i'm going to be recording this on the 4th of july so hopefully there aren't too many firework noises in the background so we are given a 9x9 sudoku board and all we want to do is determine if the board in its current state is valid or not and they tell us only the filled in cells need to be validated according to the three rules of sudoku so basically each row must only contain digits between 1 through 9 without repetition the same is true for every single column in this board it can only contain digits 1 through nine without repetition that means we can't have duplicates in any particular row or any particular column and the third part which is going to be the most tricky is each three by three sub box basically you know you can kind of see it in the drawing right three by this entire nine by nine grid is made up of nine three by three grids right there's one here and you know basically nine of them as you can see so basically for each of these three by three sub grids we also want to check that it only contains digits one through nine without repetition basically without repetition that means it has to contain every single digit from one through nine now of course the sudoku board doesn't necessarily have to be filled in you can see this 3x3 is not filled in but in this case we are going to say ok this one is valid because it you know it only has a 6 and it doesn't have any duplicates right but we do we don't only have to check each 3x3 grid we also have to check every single column and every single row now before i get into the solution let me just very quickly clarify what this problem wants from us you might over complicate it and think something like this what if we had a row such as this one it has one two three four five six seven eight that must mean even though this spot is empty that must mean a nine has to go here right that's pretty obvious but take a look at this column it has two three four five six seven eight nine that must mean that the value that goes here has to be a one so we have a contradiction we have to either put a 1 or a 9 but we know that both need to be in this position so in this case this is not a valid sudoku board right well that's technically true but for this problem we are going to consider this board yes it's valid because as of right now based on what the cells are filled in like what cells are filled in there aren't any contradictions we're not going to assume anything for any of these empty positions even though we know for sure yes a 9 would have to go here based on this row we're not going to assume that so it's actually a little bit easier than you might think so the algorithm is going to be pretty standard right we're going to go through every single row and make sure every particular row does not have any duplicates how could we do that we could do it a bunch of different ways but i'm going to do a hash set right so a hash set will be easy for us to detect if there are any duplicates so we're going to have a unique hash set for every single row in the entire grid right so then we can easily determine if any particular row has any filled in duplicates right this row obviously doesn't a five a three and a seven no duplicates right so that portion is pretty easy right number one is pretty easy to check what about number two checking each column we can do the exact same thing just have a hash set for every single column right every single column has a hash set and then we can determine if there are any duplicates or not right and for you know adding an element to the hash set is of one checking duplicates is also o of one so far we have a time complexity for just checking the columns and the rows we have a time complexity which is basically the size of the entire grid which is nine squared pretty much now the last part in theory should also be pretty easy but coding it up is a little bit more tricky there are many ways to do it i'm going to show you the easiest way we want to be able to tell okay for every three by three grid which there are nine of does any of them have any duplicates so again we can use a hash set to represent each of these three by three grids but the question is how are we gonna do it how can it be easy to code something like that and that's what i'm gonna quickly explain to you right now and after i do we can jump into the code the overall solution is yes though going to be o of n 9 squared we're pretty much just going to have to iterate through over the entire grid and nothing else but we are going to have extra space also of 9 squared because we're going to have three hash sets which are going to be this exact size so roughly this is the memory complexity as well so we want to represent each of these three by three grids with a hash set but how do we know if we're at any particular value right like i have labeled the indices right this is going to represent what row this is going to represent which column how do we know if we're if any particular value such as 1 happens to be in this 3 by three grid whereas a different cell such as four happens to be in this three by three grid how can we differentiate them notice how each of these three by three sub squares happens to be three by three right so one way is to basically make it so that we can have an index right so maybe zero represents this row of the three different squares right and a 1 represents this row of 3 squares and a 2 represents a row of this right and similarly for the columns right a 0 over here represents this column a 1 over here represents this column and a 2 over here represents this column then if we had two indices right if we can somehow take 4 and convert it to 1 then we know it goes inside this sub square right so basically we have nine different sub squares we're gonna have indices to represent them right a one means that this is the sub square that we're talking about right this one and the way the math is going to work out is since each of these is three by three we can just take the actual index such as four let's say we were given four right this is the square we're talking about we can take four which is the row divide it by three integer division right we're talking about integer division 4 divided by 3 is going to give us a 1. similarly we do the same thing with the column right 4 divided by 3 is going to give us a 1. right so if we take the actual coordinates 4 divide the coordinates integer division by three then we get the index for the row column and it basically identifies which square this is a part of now let's just check that the edge cases work out let's try a8 right this is the boundary what happens if we take 8 divided by 3 and 8 divided by 3 right well then we get 2 right integer division we always round down 2 that works out for us right let's do a different edge case maybe we try this square right on the boundary does this identify zero because that's what it should well let's take the positions the indices two divide them by three two divided by three we round these down so we get 0 that does uniquely identify or it you know correctly identifies that it belongs to this 3x3 grid so that's kind of how we're going to identify when we go through every position every cell in the entire sudoku board which of the three by three uh grids is it a part of and then we can add them to that right so we're gonna have a hash set where the key of the hash set is going to be a pair of values the row column not the actual row column right but the you know when we convert it to the row column basically row divided by three and column divided by three that's what the key of the hash hashmap is going to be and the value is similarly going to be a hash set where we can tell do we have any duplicates in this 3x3 grid or not right same for every single 3x3 grid we're just checking does it have any duplicates if not then we can continue if it does have a duplicate that means our sudoku board is not valid and then we would have to return false but if it is valid we're just going to continue so we're basically going to go over the entire grid right every single uh position in the entire grid if we find any duplicates we return false if we don't at the end we can return true so now we have enough information to actually write out the code so let's do that okay so now we can write the code like i mentioned i'm going to be detecting duplicates with a hash set but you could do it with arrays if you wanted to as well because we know the dimensions of this sudoku board it's nine by nine but i'm going to be using a hash set or dictionary just because it's easier so in this case i'm actually using a hash map where the uh key is just going is going to be the column number and the value is going to be another set basically the set is going to represent all particular values in this column and we're going to do the same thing for rows this is only so we can detect duplicates so let's create another uh hash map with rows and another hash map with the squares and remember the key for the squares is going to be a pair of values basically the row divided by three and the column divided by three so now we just want to iterate over the entire grid and we know the dimensions are nine by nine so i'm just going to hard code that in to these loops and so we know that a position in the sudoku board actually could be empty and they tell us that an empty position is represented by a dot so the first thing we're going to check is if this is an empty space then we can just skip it right then we're just going to continue to the next iteration of the loop the next thing we want to check is have we found a duplicate because if we have then we return false immediately so we want to know does this uh value if it's not empty it has it already been detected so if the board is in rows at this current row what does this mean we're saying okay the current row that we're in basically this is our hash map right rows is our hash map the key we're putting in is the current row that we're in so that's so this basically represents a hash set as you can see up above a set a hash set of all values that occur in this particular row number so if so basically if this uh this current number that we're at is already inside the current row meaning we've already seen this value before in the current row that we're in that means it's a duplicate right in which case we can return false but that's not it basically the exact same thing is going to be true if this value has already occurred in the same column before so we're going to change this to columns at the current column that we're at so if this value has already occurred in the current column then we're in that means we've detected another duplicate in which case we can return false and last but not least we have to check if this value has already occurred in the current square that we're in before so how do we get the current square that we're in uh right now well we know the key for that is going to be a pair of values basically as i wrote above rho divided by three and column divided by three so that tells us the current square that we're in and this will return a set as you can see up above of all the values that we have seen in the current square before and if this value that we're at right now is a duplicate that means it's already going to be in this hash set in which case we can also return false so this is basically our way of validating that this current sudoku board is valid if we have any duplicates that means it's not valid we return false if it is valid we continue and we basically update all three of our hash maps up above so columns of the current column we're going to add to it the current character that we just saw and we're going to do the same thing with the current row that we're in and we're going to do the exact same thing with the current square that we're in of course this has a pair of values as the key so this makes sure that our hash sets are updated and we'll make sure to detect any duplicates when we get to the next iteration of the loops so in this way we're iterating over the entire board and if we never detect any duplicates then we can outside of the loop just return true that means the current sudoku board with the current values populated and it is valid as you can see the solution runs and is pretty efficient so i hope this was helpful this is one of the easier ways the more neat ways of writing this code of course there are some more complex ways as well but i think this is fairly readable and the main you know the trick that we use is just this whole row divided by three column divided by three which just makes the code a lot easier in my opinion 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 | Valid Sudoku | valid-sudoku | Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition.
**Note:**
* A Sudoku board (partially filled) could be valid but is not necessarily solvable.
* Only the filled cells need to be validated according to the mentioned rules.
**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:** true
**Example 2:**
**Input:** board =
\[\[ "8 ", "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:** false
**Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit `1-9` or `'.'`. | null | Array,Hash Table,Matrix | Medium | 37,2254 |
217 | when you begin programming almost every new problem that we solve will teach you either a new concept a new data structure or a new algorithmic paradigm one such problem is available on lead code contain duplicates that comes under the easy category and it is a very good starter problem to help you understand about the hashfit data structure let us see what all of this is about hello friends welcome back to my channel first i'm going to explain you the problem statement and we will look at some sample test cases next we will see the most conventional way to approach this problem and see why that is not a feasible approach going forward i will tell you about the hash fit data structure and we will see how this problem becomes so easy once you understand it going forward we will also do a dry run of the code so that you understand how all of this actually works without further ado let's get started first of all let us quickly make sure that we are understanding the problem statement correctly in the problem you are given an array of integers and you have to return true if the array has any duplicates so if any number is duplicated just return a true if you cannot find any duplicate number then you have to return a false let us look at some sample test cases to make sure that we understood it correctly in a test case number one what do you see you have this array and you can see that the number one is a duplicate right so for test case number one you need to answer true because you were able to find a duplicate right and when you look at test case number 2 you see that none of the elements are duplicated right each element is unique so for test case number 2 you need to output false as your answer so this is how you can evaluate both the test cases now how do you go about solving it if you start to think about the problem the first approach is very naive what you can do you can start with each element in the array and then try to see if you can find a duplicate so you compare one with two they are different then you compare one with three it's different and then you compare with one again you find a duplicate so you will simply return true right because you did find a duplicate but this approach will fail when your array is very large for example i change this array to now the size of your array has increased right so how do you go about comparing to find does this array have duplicate for naught you start with the first element right and then you see can you find a one again you traverse through the entire array and you do not find a one anywhere right next what will you do you will start with the second element once again you will try to compare if you can find a 2 anywhere else you found a 2 right so okay this array has duplicate and you can return a false but what happens let us say this last two was not present then what will you do you will compare every element with two then you will compare every element with 3 then you will compare every element with 4 then 5 and then 6 and then 7 right so you are taking up a lot of time in this process and that is not something that we want to speed up our process right and that is what will make a good code correct so what can we do about it first of all try to understand where are you facing a problem you are facing a problem because you have to compare every element in your array right and to solve this problem we have a special data structure that is known as a hash fit now what is a hash fit a hash set is a special data structure that will never have any duplicate values so what happens is this kind of a data structure can store any kind of values you can have a string hash set that will have all the strings you can have an integer hash set that will have all integers but the condition is that this set will never have any duplicates so for example if i add 10 in my hash set then i add 20 and let's say i try to add a 10 again then you will not be able to add a 10 because 10 is already present so your hash fit will still have just two elements it will not have the third element 10 that i am trying to add so now using this property we can easily solve our problem what we do is we take up our array and we will try to insert each element in this hash fit so what happens if we take the first element and i add it to my hash fit i get a one then i get the second element and i will add it to my hash fit it does not exist in the hash fit so i will get a two then i try to add a three you can add a three then you add a four you can add a four also then comes the interesting part you get a three again right so how do you know that you have already seen it first what you do is you try to add this three to your hash fit now this data structure already has the element three in this right so you will not be able to add one more three and this will return a false and that is how you know that a three already exists and that is a duplicate as soon as you find a duplicate you can simply return true right because that is what the problem asks correct and if you traverse the entire array and no duplicates are found you can simply return a false so this way you can approach this problem efficiently correct if you're wondering more about hash fit a hash set is a utility function now in most of the modern programming languages like c plus or java or python this hash set is available as a standard library and you are able to use it directly you can also implement your own hash fit in the c language but that is a little tricky and to be very honest no interviewer is gonna ask you like how can you implement your own hash fit so whenever you see problems around duplicates always try to use the hash set data structure because in a hash set you can never have duplicates now if you have understood all of this let us quickly do a dry run of the code and see how this is actually working in action on the left side of your screen you have the actual code to implement this solution and on the right i have the same sample array with me that is passed in as an input parameter to the function contains duplicate oh and by the way this complete code and its test cases are also available in my github profile you can find the link in the description below proceeding ahead with our dry run what do we do next first of all we create a hatch set to store all the integers so you can see i have created an empty hash fit that will store all of my integers as and when i read them going forward what is the next thing that we do we run a for loop and iterate over each element in the array so in this for loop we will go through every element one by one and what do we do with it we take the element and check if this number is already present in the hash set if yes this function will return a true and it simply means that we found a duplicate otherwise what we do is we could not find the number and we add it to the hash fit so when i see the number 1 this number is not prevent in the hash set and it will get added so when my for loop runs for the first time i will add 1 to my hash fit in the next iteration i will get 2 so 2 will be added to the hash fit then 3 and then 4 when i reach 3 again i will encounter this condition check the number in the hash set this number is already present that means it is a duplicate so we can simply return true error answer and this is how your code will execute now the time complexity of this solution is order of n that is because we are iterating through the array only once and the space complexity of this solution is also order of n that is because if the array has all distinct elements then you will need order of n space to store all of those elements in a hash fact i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say that i know learning programming could be a little bit tricky in the beginning when you just start to write code there are a lot of things that you don't know about for example when you approach this problem and you do not have any knowledge about the hash fit data structure then you would be just confused okay what do i even do to get a feasible solution so in situations like these try to search around a little bit and try to focus on the problem your area of concern was that you have to traverse the entire array again and again right so try to find a solution around that problem itself how can you optimize your searches that is where the concept of a hash set data structure comes in try googling around a little bit try to read a little more and certainly you can arrive at the solution on your own next time so never shy away from the problem just be patient try to figure out a solution and certainly you will learn something new who knows this new concept can help you to solve even more problems right so what other problems did you see which involve the use of a hash fair data structure were there any problems in the past that you just skipped because you didn't know about the structure tell me everything in the comment section below and i would love to discuss all of them with you also tell me if you are facing any problem understanding this data structure what else can i do to explain it to you better you would be also glad to know that a text explanation to this content is available on the website you can find the link in the description below as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you until then see ya | Contains Duplicate | contains-duplicate | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** true
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Example 3:**
**Input:** nums = \[1,1,1,3,3,4,3,2,4,2\]
**Output:** true
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109` | null | Array,Hash Table,Sorting | Easy | 219,220 |
25 | hello everyone let's practice a very typical um record problems it's called reverse notes in k group it's a very relative typical linked list problem and it and given us a link list it asks to reverse the notes like for every notes in k in a group set of the k notes went to reversal let's take a look at the example in first example uh one and two a young group ks2 so we reverse one two into two one and three and the following group so we reverse them into uh first three and in this example one two three is a group since k is 3 so we reverse one two three two one but four and five there only two notes but k is three so the problem has got to not do any operation if in this group the notes are less than k okay so how to solve it like problem 24 there are two solutions one is iterative solutions one is recursive solutions so the follow up here is us two and solve the problems in our one actual memory space so we have to use iterative solution if we need to use one space but here and personally i prefer the recursive solution since it's much cleaner also it does not meet the requirement in the follow-up the follow-up the follow-up but let's take a look what's the recursive solution look like okay so i'm assuming we have these notes of course there are some other notes but i don't join here since it does not matter okay first i have a help function called lens it retains the length of the linked list okay next in my main function i written a dfs function takes three parameters one is a head pointer one is a lens one is k okay this is corner case as long as len is smaller than k can just retain it immediately according to the problem requirement okay then i have a local variable called tail so here now is head but after the reverse the detail will be it will be tailor node right so it says contact but it's also the future tier okay next i define two local variable once private one is temp cell initialize to now pointer okay next i will follow k times first i set temp variable to hand next since next i will break the head next pointer so i need to store the next node first okay then i set head next to preview pointer my previous is now here so it's no so head next will be a non-pointer okay so head next will be a non-pointer okay so head next will be a non-pointer okay next i set preview to head and set head to temp okay now i'm going to iterate second time move him to head next then head next point to preview then we move preview and ahead and next we start heading next into temp then we set head next to preview and remove preview and hand okay now my iteration finish and since it is a tail and our recursive function on the hand node so i call the currency function on the remaining nodes in mining place and i update my tail next to this new node now we get our answer like series new head 3.2.21 1.2 head 3.2.21 1.2 head 3.2.21 1.2 the remaining nodes and i can just return the previous pointer preview is our new head then it's done so it's a solution yeah that's it thanks | Reverse Nodes in k-Group | reverse-nodes-in-k-group | Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_.
`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[2,1,4,3,5\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\], k = 3
**Output:** \[3,2,1,4,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 5000`
* `0 <= Node.val <= 1000`
**Follow-up:** Can you solve the problem in `O(1)` extra memory space? | null | Linked List,Recursion | Hard | 24,528,2196 |
4 | hello everyone welcome back uh here is Vamps and with another live coding session and today we are going to tackle the problem of finding the median of two sources array and guess what we are going to implement it in Python but don't worry I will provide also implementation in other languages so first thing first what's the problem we are tackling so we have two sources array num1 and num2 and the goal is to find the median value after merging this array so the kicker is we want to do it in all log minimum MN time complexity so sounds challenging so let's look at tasks so if we got one three and two array after merging it will be one two three so uh our median value is 2 and if we have uh one two and also sorted three four uh yeah it become one two three four merged array and here is our medium value so 2 3 two plus a 3 divided by two is two and a half and it's our output as well for example number two so uh really a straightforward task but to solve it uh efficiently it might be a bit tricky so uh so finding the median of two sources array is fundamentally about partitioning those RIS in such a way that every element on the left partition is less than every element on the right partition and the number of elements in the left partition is either equal to or one less than the number in the write partition and we will be using binary search to find this perfect partition but here is the twist we are not applying binary search to find a particular element instead we are using it to find the perfect partition that split merged RI into two halves following the rule mentioned previously so we will partition num1 at Point partition X and number two Edge Point partition Y and these points will be so chosen that they divide their respective array into two parts Max left will be the greatest element on the left side and minimum right will be the smallest element on the right side and all right so let's move into the first part of our code so ensuring num1 is the smaller all right so if land one num1 num2 number one so ensuring yeah number one is the smallest array so we just swap it and why we do this so it's great question and we want num1 to be the smaller array because we will be applying binary search on it and it makes the algorithmaster by reducing the number of elements we have to look through so now we will initialize variable so MN will be Len num1 and Len num2 and low high will be 0 and M so uh what are these variables so here M and N are the length of num1 and num2 respectively and flow and high will serve as the boundaries for our binary search and step three will be the binary search Loop so why low less than High partition X will be low plus High divided by 2 without remainder and partition y m n 1 2 minus partition so what's happening here we are started our binary search group and the partition X and partition y points will divide num one and num2 respectively into two parts mentioned before a left half side and right half side so and now uh step four finding Max left and minimum right so Max X will be float Infinity partition x 0 as partition x minus one and Max y will be float in Infinity if partition y zero else num2 partition y minus one and minimum X will be float Infinity if partition X M LS Alpha will be nums one and partition X and minimum y will be float Infinity if partition y and else num2 and partition y okay so all right Are We There Yet almost so we are calculating the max left and minimum uh right and for the partition this will help us determine if we have found the correct partition where Max left is less than minimum right so now the part is to validate a partition and update our boundaries so it's also crucial so if Max less than minimum y and Max y minimum X m n modulo 2 0 then return Max and minimum divided by 2 and else it will be return Max of Max X and Max why and else if Max greater minimum y High will be partition minus one else though B partition plus one so uh that's all so here is the logic and we have reached the core logic and in this step we validate our partition points so if Max X is less than minimum Y and Max y is less than minimum X we have found the perfect partition and yeah so we can now calculate the median based on whether the total number of elements is odd or even however if Max X is greater than minimum y it means the perfect partition lies to the left so we update High partition x minus one likewise if Max Y is greater than a minimum X the position lies to the right so we update low as partition plus one uh yeah so now let's run it to verify it's working so hopefully it will so yep and given first example 2 as mentioned previously and second one two three four two and a half so quite easy but let's submit it to see how it performed so hopefully it will work so yeah it's working perfectly and we beat 68 with respect to random and also 69 with respect to memory I think uh previously I got even 80 milliseconds so between 94 but basically it's uh quite a efficient approach and really elegant so we dissect that a complex problem broke it down to its essential and then tackled it step by step so this wasn't just about finding a median it was uh quite interesting algorithmic problem solving master class so don't forget to check out the code in the description in the other languages as well and if you found this session uh valuable or interesting do smash the like button and share it around so uh we'll be back with more coding challenges tutorials machine learning Tech and much more so subscribe if you didn't yet so until then keep practicing stay motivated and happy coding | Median of Two Sorted Arrays | median-of-two-sorted-arrays | Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106` | null | Array,Binary Search,Divide and Conquer | Hard | null |
713 | Hua Tha Aayi Welcome To Learn Ko Repeat Join Vriddhi Looking End Date 28th September Light Ko Challenge The Name Of The Problem Is Sir Yeh Product Lagan Ke Net Slow End Rate Problems Is Yagya And Nurses Contact Number Of Candidates For All Elements According To 1500000 Subscribe to the palace name cigarette 20 rights of norms of is great 10 class greater than equal to 08003800808 so let's look at this exam ok sudhir and share intestine phase stomach subscribe palat 720 ne siddharth ke all vitamins 2-5-15 2012 ne siddharth ke all vitamins 2-5-15 2012 ne siddharth ke all vitamins 2-5-15 2012 660 That Solid Se Dash Have Not Given To More Than 8 To 10 Numbers In The Norms Are Eligible Candidates Win This Water With Account It Is The Number But Also Something Like This Side Effect From Left To Right subscribe And subscribe The Amazing spider-man Adheen Video subscribe and spider-man Adheen Video subscribe and spider-man Adheen Video subscribe and subscribe the Channel Chash Cylinder Number Do Aur Tu Kahan Sex And Similarly In The Starting With Her Only One Number 66 Pattern Right Clear Aisa In Total Phone Number Dara MP4 A Plus Female Plus Two Plus Path Subscribe In Total Strong In Total 20 Number But Can Be Coming Back To Not Eligible Subscribe To Land Acquisition Bill Cancel Subscribe Number To The Number First Time The WiFi Turn Part To Retail Pack To Sunlight Chief Middling Is Number Four Right Into Ver Left Right Left Dash Loot Staff For 19 In Third Number Dinesh Seervi Increment Main Left Counter Suvidha Start Me List 5352 16 Question Rediff Inst Of Mount Everest Or Turn On The List Containing All The Number Eight 's Debtor's Udaipur Doon 2.1 To Google 's Debtor's Udaipur Doon 2.1 To Google 's Debtor's Udaipur Doon 2.1 To Google Disk List And Taken To For the new list starting with and craft with yogic to the media straightforward gautam budha vanshkar 81016 drop spot and aggressive way all the number one is the calling apps update festival subscribe and subscribe the Channel subscribe to the number of elements of obscurism account spider Man into unnecessary from the best friend voter list maintain only subscribe gautam and the problem list will give time limit exceeded so let's see how we can do subscribe to this time when element witch first edit 10 2010 5 126 and logic wave from left to right click Relative in Difficulty Development and Captain Justin Point on Thursday Subscribe button on the right side a subscribe button that in you Neetu 252 Internal Affairs Her Loud Rating Window System Not Subscribed Will Remove The Number subscribe And subscribe The Amazing Please Like This 162 Back Green Mode The Number Of The Left Side To Stand In This Chapter Number On Rights And Writing Instrument And See Where To Find Difficult Close Loop Subscribe And Subscribe The Amazing Number Do Mein Dard Channel Pirate Jo Number For Dinesh Chand Second Hai That Product I Can have attended how can I have taken from five and icon is the first plate man actress number celery will put him in force trivalent combination in that case how can have taken 110 in five days uk 52 fuel returned jazba chahiye front end sonu bhaiya patient five days 125 Commando 2 And Adorned With 4 5 6 So Pattern Hair Soft ODI Test One Four Three Digit Navratri Numbers Application Hai Pathri Dj Ideal Number Prompt Fall Central To End After 251 To Back White Screenshot 3 To 4 Will Be 12.2 Getting There Right On This Hole To 12.2 Getting There Right On This Hole To 12.2 Getting There Right On This Hole To enter in the true sense like it man number four 750 plus 3 plus two plus one between equal to flash light co presentations plus two plus point stand between match point to my bittu physical test sense senior jewelry fold phone number eligible subir bill- 2010 fold phone number eligible subir bill- 2010 fold phone number eligible subir bill- 2010 News Subscribe 158 The Number Three Do Subscribe My Length Stree The All Eligible For Oneplus 3 In The Sun Earth Measure From That Support I Length Is Three Layer Create Account 16 Okay So When Mist On Milk Is 8.2 Property 1.8 Subscribe And Result Do Aa 8.2 Property 1.8 Subscribe And Result Do Aa J - I am a J - I am a J - I am a plus one member my account sweater can find the total number of elements with product's notification more subscribe this to-do list 2 eggs subscribe this to-do list 2 eggs subscribe this to-do list 2 eggs subscribe and subscribe this Video give check this Pimple's Anirudh current track of this scheme Adheen Will Continue And Loop Person In Wedding Next Flight Mode Limit Ok Subscribe 2012 Torch Light Aakhya Singh Name Surfing Day Tho Can Be Grade Date To Join This Close And One Will Never Be Able To Find Doctor Product Right Him Loud Remove its ink Acid 108 Subscribe Defined in 000 and equal to zero Size in lover point time when ride point is on left side 10 and it's a current product current affair that is equal to one then current political to current side * then current political to current side * then current political to current side * Norms of Chi Nave Samay Current Practice Greater Than Or Equal To K Right In That Case How To Remove The Life Of Student And Again And Check The Current Product Is The President Of Hai But It Is Not The Naagin To Remove The Name Of Limits Of To Darshan Allu Price Select Used Oil which is used in 202 Corrupt Requests Vote Bank Name 100MB Left Most Countries IS Another Five Key Andher Increment Appoint Blood Donation Self Removing Dalit Muslim Theorem Current Dependent The Mean Of The Time In Preventing The Value Of Side Samsung Ne Bigg Boss Pointer Toe I Current Product in Saudi By Loop Control in this Prad Me Guddu K and Welcome to my YouTube Channel I Current Practice Garlic Hearing Result Fifth Result Class The Water in Empowering Rate Suji - You Water in Empowering Rate Suji - You Water in Empowering Rate Suji - You Customer Slow Every Inch See Ruby Jain Including Administration Noida Extension Play Return The Results Found Pure Complexity of Difficult Words Only Once in a While But Time Will Be Always Open Subscription Jai Hind Se Ek Chapter Platform Ad Facility Only 10 Video Guys History Without Questions Please Like and Comment Section and subscribe the Channel Features Videos Thank You | Subarray Product Less Than K | subarray-product-less-than-k | Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
\[10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6\]
Note that \[10, 5, 2\] is not included as the product of 100 is not strictly less than k.
**Example 2:**
**Input:** nums = \[1,2,3\], k = 0
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `1 <= nums[i] <= 1000`
* `0 <= k <= 106` | For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function. | Array,Sliding Window | Medium | 152,325,560,1083,2233 |
1,283 | Hello Guys Ball Directly Singh Subscribe Result Subscribe Pimples Ko Subscribe Button Ko Aar Takht In Every Possible Number Now School Subscribe Pimpal Ve subscribe The Video then subscribe to subscribe Video Ko Loot Lo Question Option Android subscribe And subscribe The Amazing Subscribe To that full hd awadhesh loot li jo hair in the right to point se zulutrade subscribe to that weather ko namaskar hai in final ko maximum delhi pin code * ko maximum delhi pin code * ko maximum delhi pin code * a site for inter college maximum bill max player in the mid-day jhaal dhundh ki navmi Find Time For Love May Debit The Receiver Yeh To Time Milk Allahabad Including Many Districts And That Boat Everywhere You English Name Deep Find The Sum Of The Questions On That And Bring To Front Of The Amazing And Favorable Proven Number Sleep Se Hai I Ignore Se war me function loot cea jhal were little boy water tune complexity Thursday subscribe to see sleep se plunder behavior left 2012 hai otherwise intoxication deepanshu dryad appointed vid oo yo honey changes code apk pimple district court decade pimple hai my device where Right Result Test for the Pimple Hai Pimple How to Edit Kar in Obscene Setting Vitamin Complexity Avadhesh Singh Gautam 's Notes Knowledge All During This From Its Function subscribe and subscribe the Video then subscribe to | Find the Smallest Divisor Given a Threshold | reformat-date | Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: `7/3 = 3` and `10/2 = 5`).
The test cases are generated so that there will be an answer.
**Example 1:**
**Input:** nums = \[1,2,5,9\], threshold = 6
**Output:** 5
**Explanation:** We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
**Example 2:**
**Input:** nums = \[44,22,33,11,1\], threshold = 5
**Output:** 44
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 106`
* `nums.length <= threshold <= 106` | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. | String | Easy | null |
5 | hello everyone welcome to code and learn in this video we will continue to look at lead code problem five finding the longest padic sub string in a given string I won't go over the problem statement again as we went over it in detail in the last video in this solution we are going to use moner's algorithm to find the longest pic substring in a given string let's now look at moner's algorithm and how it works moner's algorithm introduced by Glen manaker in 1975 is a powerful solution this algorithm capitalizes on the inherent property of pomes utilizing existing data to efficiently calculate Pome lens centered at the current character let's now visualize it with an example here we have a Pome AB B CB a moner's algorithm works with our number of characters that is our length string the first step we usually perform with moner's algorithm even if the string is already odd is to add special correct C at the odd places in the string in our case we are going to use hash as a special character so let's add that so A String becomes # a # B # C #b # a # next String becomes # a # B # C #b # a # next String becomes # a # B # C #b # a # next moner's algorithm utilizes the property of mirroring in a pad room the center of our current palad room is at C starting with the first character we start to calculate if there's a possible pum centered at this current position as you can see there's no p in here so we can put the length of Pome centered at this position as zero next we go to a and we can expand it both side so as we can formulate a b centered at a we can extend it by one we upate the value of a Pome starting at a to one next we have hash again this time the value of a Pome starting at this hash is zero again next we go to B we repeat the same process and now as you can see the number of character we can extend from the center if the center is at B is one again next moving on to the next hash we can say let zero again now we are at C and this time when we expand we can see the whole string is a Pome it has both side of characters our mirror value around C so we can extend C to 1 2 3 4 5 as such we update the value now this is where mirroring comes into play if you are inside a palome string and there are know other pic substrings you can calculate the length of Pome substring centered at this hash using the already calculated value from the mirror here we can say C is the center and the right boundary of this is at this hash to calculate the mirror we use the formula mirror m is = 2 into Center minus I is mirror m is = 2 into Center minus I is mirror m is = 2 into Center minus I is the index of current character in this case the index of this hash is 0 1 2 3 4 5 6 to calculate the mirror value what we can do is 2 into Center which is at 5 - 6 which gives us 10 - 6 4 so that's - 6 which gives us 10 - 6 4 so that's - 6 which gives us 10 - 6 4 so that's the mirror index which is 0 1 2 3 4 we can use that to say that a palid Drome starting at this hash will be of length zero similarly we can do same thing for B and use the mirror value for B and so on so we can update the values based on the that mirror for B it would be 1 then zero 1 and zero and that is how mirroring is used in manar's algorithm since we are only going over the string once the time complexity of this solution is O of n where n is the number of characters in The String now let's look at the code to find the longest subring palome in a given string using manak's algorithm here as you can see in our main function we are inputting a string b a d and then calling the longest Pome function to get the longest ping substring saving it into the result and printing the result let's now complete the longest Pome function before we do that we need two additional helper function the first one is to process the string for it to be a or length string so we will write fun process string which takes a s string and Returns the process string inside it we initialize result with our special character hash and then we range over s to add our special character at each order index so result plus equals string since it's run we need to convert it to a string and then add a hash at the end as well after which we return the result I'm just going to add a command to sa what this function does so process string takes a string and adds special characters which is Hash add odd indexes now another function that I need to use is a simple Min function what this Min function does is it takes two end values A and B and returns whichever is smaller if a is smaller than b we return a and otherwise we return B now let's fill in the longest Pome function first thing we do is process the thing to make it all length and add our special characters process string is equal to process string and S now we need to initialize an array that we will use to store the length of Pome centered at given characters or given index I can say n which is Len process string and then initialize a array P which is of type end and length n next up I create two variables to track the center and right of current padr and initialize both to zero now we will have our main Loop that it traced over each position in the process ring inside the loop first thing we will do is calculate the mirror position of the current position the formula as we went over earlier is m equal to 2 into Center minus one next we perform a check to see if the current position is within the rightmost boundary of a pad if I is within a Pome then we see the length of Pome centered at the current position to minimum of right minus I and the mirror value we select the Min because if we move towards the end of string if you use the mirror value it's not going to be the right value so we use the main value and the main value should give the correct Pome length if it's with within the current pum else we see the value to be zero now what we are saying here is that the starting seed length of a palome at given I is equal to minimum value between right minus I or P mirror if it's within a Pome El it's zero next we expand beyond the seed value to see if we can find a longer palome for this we need to check for two condition first is that we are within the length of the string so here what we say is since we are using the seed value and then expanding beyond the seed value we are checking that we are within the string length the first is to check the right end that we are within the right extreme of the string and the next one is to check if we are within the left extreme of the string or the end of the string next is the check for the pic string we've already used that in previous example so here we are saying is if the correctors match we keep on expanding or increasing the length of pad Dr I'm just going to turn it to uppercase P so that we are consistent so this for Loop will expand to find longest P Drome at a given Center and it will use information we saved earlier next up we perform another check what this check is doing here is if the right edge of the current palome that we calculated here is greater than the right we stored earlier we need to update the center and right that is we need to move the center and right to match the long longest Pome we have found till now and that's what we do here at the end of this for Loop you would have the data to calculate the longest pic substring we find the maximum value in the p and the center index for that so here I'm doing max length and Center index initializing them to zero and then ranging over P finding the maximum length along with the center index at which the longest pic substring is centered once I have those I can calculate the start and end of that palome using the max length and Center index value the start is calculated by Center index minus max length ided by two please note this calculation is being done with the process string which has the special character in it and end is start plus max length in the end we are using the string provided to us not the process thing to return the longest padic substring let's now go over the solution step by step first up we process the string to add special characters and make it our length next we store the length of the processing and initialize the array of int value with length L next we initialize two variables Center and right to Value zero then we iterate over the string character by corrector this is self-explanatory as we are this is self-explanatory as we are this is self-explanatory as we are calculating the mirror of current value inside the loop at each character first we check if I or the index of current character is within the given padro if that is the case we use the already calculated Val to get the seeding value for I which is minimum of right minus I or P mirror otherwise if this is the index that's out of the current Pome we seed it with value zero then we start a for Loop to expand from the seed value and Beyond to see if we can find a greater paradrome length as such first we have the condition to stay within the length of the string and then the condition to check for pad Drome and if both match we increase the length of the pad Drome centered at a given index if we have found the bigger Bel room we update the value of Center and right and move on to the next Corrector by end of this for Loop we should have the maximum length of pic substance stored in p as such we range over P to find the max length and the center index where the center of the greatest pic substring lies and update the Max and Center length next we calculated the start and end using our values and at the end we return on the longest plyopic substring using the calculated values let's run our program to verify if it works as you can see it's working as expected the longest pic substring is PAB since we have already looked at the code let's try to visualize maner algorithm to find the solution with the given examples so that we can solidify our learnings in the lead code question string that is given is b a d now applying the maner algorithm we can add special characters at odd indexes so this is the string we get after adding hash to odd indexes in the string let's now Mark the indices of these characters now we start from the first character and calculate the values before we start we have Center at zero and R at Z as well which is the center and right boundary of the current palad room first we calculate the palad at this hash it has a length of zero so we can update our AR to say is still stes zero length then we move on to this and expand and as such we can update the value of length of Pome stored at this Center as one since we have a new P we can move Center to B and right to this boundary here then we move over to this to calculate a pad room starting at the center to start off we use the seed value from the mirror which is zero in this case so we update at zero then we try to expand since there are no expansions we leave it at zero then we move on to this corrector this time a is outside the right boundary of the current palum as such we try to expand again this time we can expand and see that there's a palum from here to here the seed value for this was Zero but now since we can expand we can set it to 1 2 3 now again we update the center and R the new center is at A and R is at this hash as such we move on to the next character in the string again since this is within a pad Drome the seed value will be that of the mirror in this case is this one so we update the value to be zero and as such we can't expand it so we leave it at zero next we move to this again we start with a seed value this time the seed value is one so we update it to one then we try to expand it Beyond one if you Center the pad Dr at this P the pad Dr will be starting from this hash up till this hash we update the value again and you can see the length will be three as such we update the seed value to say it has a length of three again we will also update the center and R now our Center lies at this p and rightmost boundary of the current palome is this hash next up we move on to the next character again since this is within a bad Drome we use the CED value which is zero gain so we updated and then try to expand it but since there are no expansions we leave it as such next we move on to a use the mirror value in this case is three if you remember we use minimum value between the mirror M or r - I so the mirror in this case is 3 or r - I so the mirror in this case is 3 or r - I so the mirror in this case is 3 r - I is 8 - 7 1 and this is why we use r - I is 8 - 7 1 and this is why we use r - I is 8 - 7 1 and this is why we use the minimum to prevent us from updating the wrong value as such we use one here next we move on to this since this is still inside the P room we update the value using the mirror to zero next we are at D since it is not inside the current palome we use the seed value zero but then we try to expand and find the value to be one as such again we will move the center and R to the new center and the right boundary so when we get here we again use the mirror value to update the value to be zero and then if we try to expand it there are no expansions so we leave it at here at then this is the p that we will have and then we can iterate over it and find the longest length which is this and this in the end we can either return bab or ABA that's how the monaker algorithm Works use the second example from lead code that is cbbd to visualize the solution for yourself I hope you enjoyed the lesson until next time happy coding | Longest Palindromic Substring | longest-palindromic-substring | Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters. | How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation. | String,Dynamic Programming | Medium | 214,266,336,516,647 |
1,493 | Hi ga namaskar welcome to the channel hum kar 90 days ac prep question number 17 au lead code 75 lead code 493 ok to dekho llenge sub off one after deleting one element a de rakha na aur zero hi hai deleting one element is allowed I have to tell that after deleting one element has to be deleted, it has to be done, it is okay, after deleting one element, what will be the biggest number of all, so I still asked the question lead code 1004, inside which was the question. What was that maximum consecutive once, if you can flip at most k zeros, making one from zeros is allowed, its code was just discussed, the video is of 2025 minutes, it was just discussed So do you know its meaning, what was the meaning of the last year, what was the meaning of a saber which has up to K zero allowed, then the biggest saber of one which has up to K0, tell me, we had also discussed about it in the algorithm re-release. also discussed about it in the algorithm re-release. also discussed about it in the algorithm re-release. So if you look at this question in which it is okay to delete one element then what I would say is that there should be all the ones inside it right and deleting one element is allowed or if one element has to be deleted then I would say this previous question only. So find the largest substring in which one zero is allowed up to zero. Find the largest substring in which one zero is allowed up to zero. Okay, and the length of the largest substring that is zero is equal to that. My is our answer, so if you solve the previous question by putting the value of k as one, then basically you have not done anything. You have solved the previous question by putting the value of k as one. Here k was used for counting greater than 1. It was solved by counting equal to two, it was solved by putting k1 and in the last answer why did it become -1, and in the last answer why did it become -1, and in the last answer why did it become -1, which is the biggest, now see, what will it give to itself, thinking about so much area, what will it give, it will give the biggest subre in which up to two 10 is allowed up to 210 is allowed. I found the biggest window in which one is allowed till zero and then why did I add -1 to the last one. I is allowed till zero and then why did I add -1 to the last one. I made -1 from inside the biggest sub array because one made -1 from inside the biggest sub array because one made -1 from inside the biggest sub array because one element had to be led. Even if all the sabres were of one time, we gave it by -1 all the sabres were of one time, we gave it by -1 all the sabres were of one time, we gave it by -1 because this element had to be deleted. If our biggest sabre, there was a zero in it, then by doing minus and that same zero will go away, so basically this question changes it. Self to find the longest saber with up to one zero allowed. The previous question was up to k0 allowed, so solve the previous question by entering the value of k as one and in the last one, subtract one because you have deleted one element. So the answer that would have come will be T then the answer will be minus plus the answer. I have not explained this question well here. I know you go to the previous question and understand that question. Go to the lead code 1004 and go to the top question in the playlist. That question. Look at that question, it has been explained in great detail, after that you will come to the question, it is a question about children, it is nothing, it is okay, this question was a derivative question, so there is a need to ask the complete question properly, otherwise I hope you would have understood. Let's move on to the next question. Thank you so much. | Longest Subarray of 1's After Deleting One Element | frog-position-after-t-seconds | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's.
**Example 2:**
**Input:** nums = \[0,1,1,1,0,1,1,0,1\]
**Output:** 5
**Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\].
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** 2
**Explanation:** You must delete one element.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. | Tree,Depth-First Search,Breadth-First Search,Graph | Hard | null |
739 | hello welcome back today I will solve leeco 739 Dairy temperatures we're given an integer array containing Dairy temperatures for each item in the array we have to determine how many days we had to wait until we have a higher temperature than the current one if we are not able to find such a temperature then we just assign the value 0. let's take a look at this example we are given the temperature array this is the array that we need to return let's walk through this together and see how we obtain the answers array the first item is 73 and we have to find the day in which the temperature gets warmer so we look through the array from left to right and we find that the next day is 74 so we have to wait one day so one goes into here the next item is 74. again we look through the array on the right hand side of 34 and we find that the next day is 75 we only have to wait for one day to get a warmer temperature next item is 75 we scan the array from left to right starting from 75 and we find that the next higher value is 76 which is four days away so 4 goes in here the next item is 71 two days later we see 72 that is the earliest time point when we see a higher value so 2 goes in here the next value is 69 and we only have to wait one day to get 72 we have one here next value is 72 the immediate right to 72 is 76 we only need to wait one day and finally we have 76 that's the end of the array so the value is zero because we are not able to find a higher value if you have been following the series you will immediately realize this question is asking for the nearest biggest element on the right two videos ago we already discussed abusing a monotonic stat and I discussed in detail about the template to do that if you're not familiar with the monotonic stack I would suggest that you pause this video and watch the first video of the series I left the link in the description below there I discuss in detail how everything works and also I discuss how we derived the template that you're seeing here now I will continue with this one for this question we need a result array where we're going to store the number of days difference between the next warmer temperature and the current one we are populating the stack from right to left and the staff what we're going to store is a tuple which contains the temperature and also the day and the day here is basically is the index of the array because once we find a higher temperature we can always do a simple subtraction and we can calculate the day when we see a higher temperature and the current day and that's how we populate result sub I so the result of I would be the top of the stack and we take the day value minus the current value let's walk through several iterations of this code together we are populating the stack from right to left so the top of the stack will be on the left side first item is day number six we have temperature at 76 and the stack is empty the results of I is zero and then we just push the Tuple 76 and 6 onto the stat the next item is 72 which is on day five 72 is a lower number than the top of the stack which is 76 so we take the top of the stack a day six and we minus the current date which is day five and we get one so we substitute I is 1 and then we push 75 and 5 as a two pole onto the stack the next item is 69 which is also smaller than the top of the stack at 72 so again we do the subtraction taking 5 minus four and we get one so result of I is 1 and we push this two poles 69 4 onto the step because we're looking for the temperature of a higher value we are making a stat where the temperature is decreasing the next value is setting one now that is a higher value than the top of the stack at 69. so in this case we will pop the top of the stack and then beside that 71 is now smaller than 72 the top item on the stack so we are good and then we do the subtraction we take the 5 here and we minus the three here and we get two and then we put two as we solve sub I and we put 71 3 onto the stack the next item is 75 again that's higher than the top item on the stack so we can continue to pop the start until the top item is strictly higher than 75 so we pop those two items now we do the subtraction we take the six here and we minus the two here and we get four as we solve so I and then we put 75 2 onto the stack I think now it's clear how the call works and how we populate the result sub I one can also introduce some optimization here as you can see in the stack you don't really need to store both the temperature and the index because all you need to do is store the index and do a lookup when you're checking whether the temperature is higher or lower I included here just for clarity purposes and now let's talk about the runtime complexity is Big all of n because we're using a monotonic step for this every item is added to the stack exactly once and they will be moved at most once now let's convert the pseudocode into real code this c-sharp call is provided real code this c-sharp call is provided real code this c-sharp call is provided in the GitHub links below everything is very similar as you see in the pseudo call we have the resolved array and we have the stack and we're going in reverse order to populate the stack using temperatures from the end of the temperatures array to the very beginning and the end we will return the results array now let's take a look to see if this works and it looks good so next time we will continue with another example of monotonic stack and we will do an even more challenging problem hope to see you then | Daily Temperatures | daily-temperatures | Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100` | If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next. | Array,Stack,Monotonic Stack | Medium | 496,937 |
250 | hey everybody this is Larry this is me in a really uh poor posture in the bed here in Lisbon uh but I'm gonna try to do the count uh or this week's uh legal premium weekly problem which is too fitty uh count you know value sub trees what does that mean give me the route of binary tree return the number of universe subtrees is all the nodes of the sub tree of the same value what does that even mean still oh no oh okay I see so the leaves by definition does and then you just kind of propagate that up I think right so yeah uh which is so kind of confused I mean I wish they kind of do a little bit explanation somewhere but I guess I get it uh it's a very awkward Farm but yeah uh so maybe we just saw countries there maybe I'll do a global thing um or maybe I guess I don't need to do a global thing because it's just recursive right so maybe we have a count we have a node oops load right so basically the node is none we turn zero I guess uh if node is a leaf then we return one that's our base case that's a leaf uh otherwise if no dot left is not equal to okay so well let's just say children is our future but also it's gonna be a count of no dot left plus kind of note that way that's our children count um and then now we go if note that left is not equal to this is kind of awkward to write but it's fine basically if it's not none and no that value is you go to or if it's not done and this is not the case uh that means that this current node that's not it's not as you know why you're sub tree so then we just return children um we can also do the same for I mean I'm writing this in an awkward way um because usually I think you would write this as one if statement but I think this is slightly clear for on screen so that's why otherwise uh we turn children plus one right um yeah I think that should be good maybe it's very possible to make mistakes that's very possible because I've been making them all day but oh now did I misunderstood this I need a better visualization on this uh what does that even mean oh I see I messed up here on one assumption basically I thought that would it would get propagated up but I did not propagate this up enough right because basically the sub trees um or this thing is just like this example with one on the top triangle and then five on the bottom and the one is propagating up to plus one which is not true right how did I fix that huh what a silly mistake well I don't know if it was a silly mistake it's just a bad mistake honestly um and I should have tested this uh because yeah but okay I mean well this is definitely true this is the one that is technically not right yet right I guess as soon as this is not true for one of them I think I was just trying to be too clever in returning it I think everybody had done it with the other way it went easier to keep track of the states but okay fine whatever we write this a little bit so now instead of count we also return weather the um the node itself is a unit value right so none we can return Force maybe something like this a Tupperware yeah I mean it's not it's fine it is one and this is true that the subtree is the same right and then now we have to do some more no dot left right as you go to account no that way and then total is equal to the left and you would buy user name typo for this but I need to catch my flight so uh I feel like I say that a lot but it's true so we do total here um if left dot if this is not true or uh not right of one we can already we well I guess this should be true then in this case uh then we return total because that means that the sub trees are already whatever so we don't have to do it otherwise we do the same here uh and also we return Force as the second parameter this is why we might have a one statement would be nice otherwise we are actually good and true right uh and then we just return the first thing yep I thought I could get away with router but I don't know why I thought that way yeah well uh sometimes mistakes happen uh when you try to go too fast that's why you know it's okay to go slow to go correct right being fast and incorrect is useless uh I mean you know approximately so uh don't want to generalize everything but uh but yeah what's the time space complexity is just linear time linear space uh maybe all of h space if you will for the height of the tree but otherwise yeah linear in both cases um that's what I have for this one let me know what you think stay good stay healthy take your mental health I'll see y'all later take care bye | Count Univalue Subtrees | count-univalue-subtrees | Given the `root` of a binary tree, return _the number of **uni-value**_ _subtrees_.
A **uni-value subtree** means all nodes of the subtree have the same value.
**Example 1:**
**Input:** root = \[5,1,5,5,5,null,5\]
**Output:** 4
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[5,5,5,5,5,null,5\]
**Output:** 6
**Constraints:**
* The number of the node in the tree will be in the range `[0, 1000]`.
* `-1000 <= Node.val <= 1000` | null | Tree,Depth-First Search,Binary Tree | Medium | 572,687 |
90 | what's up everyone today we're gonna go over elite code number ninety subsets with no duplicates first I'm gonna write out the code and then I'm gonna draw the recursive stack tree diagram so you can see how the subsets are each actually getting populated and which recursive stack is making each one of these subsets the solution comes from the backtracking template by the link code user isaac 3 so follow the code that I post below and then it'll be easy to understand how the recursive stack is being generated so first let's make the data structure that they want as a result it's a new ArrayList and then what we have to do is sort the array because that's how we're gonna be handling duplicates and in the recursive part you'll see that there's one if conditional which checks if a element and the previous element are the same if so we continue but I'll write the recursive stack in a bit DFS res new ArrayList that's a temporary then we pass in the array itself and then we pass in the 0 which is going to be kind of like the position so we start with the 0 position and then each recursive call is gonna be going plus 1 then we return Marez so that's the main method that is gonna run the function now let's get into this recursive DFS function I'll call this rez call this t4 temp integer array numbs and then int POS for position so first thing we're gonna do at the beginning of our recursive stack is always add the temp that was passed in so add new ArrayList TT for attempt so the first one winning pass in it's empty so it's gonna be I'll use a different color marker a null set because when his first passed thing is empty then what we're gonna do is for int I is equal to 0 or rather POS speak but POS is was 0 when it was passed in so this is gonna be POS I was less than numbers dot length I plus yes eyes greater than pls and the element we're presenting is the same as the element that we had previously we're gonna continue so what that means is if we're on this one we're you're gonna skip if the same thing is the same if the number before is the same then we're gonna add the numbers of I then we're going to recursively call this function and what we're gonna change is we're gonna call I plus 1 so the recursive function gets the I that's next so if we're starting out with 0 and it's gonna recursively call 1 next and then remove T dot size minus 1 now that's the general backtracking is you add something to your list you recursively called that and with including it in your function then once that returns you remove the thing that you add it at the very end even for famous problems like a backtracking like an N Queens problem that's the idea of how backtracking works so this is the code now let's get into what the diagram looks like so first DFS Perez that's the in offset gnomes and zero gets passed in raised and alright stuff add new ArrayList this one son this is how we get our first one then we do our for loop for int I than equal to 0 I is less than 3 because numbers of length this gnomes length is always gonna be three deathless plus if that's greater than 0 and blah then we continue we don't need to continue at this point that's why I'm just writing it like that and then T dot add nums of 0 which is gonna be one coming from there then we do DFS res passing the newly added one then gnomes and then I plus one which is gonna be one recursively we get called here DFS res one numbs one so the first thing we do is we add the new ArrayList to our data structure and that's how we get our second answer from that then for int I is equal to 1 as less than 3 I plus close if I is greater than 1 and blah we continue but we don't need that right now then recursively we add first gnomes of I which is 1 and this is pretty much going to be wanted to week we recursively call that's the recursive call res one and two and nums and then 1 plus 1 which is 2 curse when we call here DFS res 1 comma 2 is in the temporary and then we pass in two here right so what we do is first we always add the result new ArrayList 1 and 2 and that's how we get our next one right there for int I is equal to 2 is less than 3 I plus if I is the greater than 2 but we don't need it right now then what we do is T to add nums of 2 then we recursively call this DFS res 1 comma 2 and nums array then we pass in three this gets recursively called here DFS res 1 2 3 and we add new al 1 2 this guy is here and we get our final one here and now because for int I is equal to 3 I is less than 3 this won't happen so this recursive stack isn't done then we come here now we also have to TWP remove the last thing so T dot size minus 1 then what this becomes is 1 to 2 is the temporary array so then we get I is equal to 3 right to start out with 2 I is equal to 3 and it's not less than three so this recursive stack is done as well now we come here now once you duty to remove T dot size minus 1 that pretty much removes this 2 right here then we that was a that here it was I is equal to 1 less than 3 now we're doing I is equal to 2 less than 3 this is the first time we're gonna run into that if condition if I is greater than one the one is coming from here and I use two right now and numbs of to the same as gnomes of 1 2 minus 1 which is 1 then we continue so this one is not gonna happen then we do I is equal to 3 less than 3 that's not going to execute so this recursive stack is done so all we have left is the 2 and the 2 so now we also have to do the same thing TDOT remove T dot size minus 1 so the 1 goes away and we recursively now we do I is equal to 1 which is less than 3 we T dot add we're gonna add 2 pretty much and then recursively call DFS on it so res is it gonna get a little messy but you should be able to understand from the rest of this flow what's gonna happen is two is gonna get added at the top of this recursive stack to nums and then this is gonna be to that's passed in then res dot add new ArrayList so this is where we get our two from and then here for int I is equal to 2 is less than 3 I plus we add T dot add one more time so now it's gonna be two coming to and this gets called recursively DFS and this is res dot add 2 comma 2 so that's where we get our last that one yeah sorry I ran out of room but that's how it would look like if their last recursive stacks were small enough to draw in here anyway we let's counter check so 1 2 3 4 5 6 and we got 1 2 3 4 5 6 so that's how you saw a code number 90 if you like the problem if you liked the video please so it'll motivate me to make some more and let me know how I can improve and thanks for watching | Subsets II | subsets-ii | Given an integer array `nums` that may contain duplicates, 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,2\]
**Output:** \[\[\],\[1\],\[1,2\],\[1,2,2\],\[2\],\[2,2\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10` | null | Array,Backtracking,Bit Manipulation | Medium | 78,2109 |
15 | welcome to Lee codes blind created 75 where I'll be solving the 75 essentially code questions this problem is called threesome and it's mmm very frustrating here's the thing with threesome what I always remembered was you could solve it by using a nested for loop and inside of the nested for simply use a twosome solution so basically normally if this were soft brute-force you could solve it were soft brute-force you could solve it were soft brute-force you could solve it in n to the third power but you could reduce that down to the end to the second power by using a twosome solution in the nested loop so it was something like this first we'll initialize our output and we'll say for I in range of let's see guess just length of nums and then we'll say for J in range of I to the length of nums where you just do a typical to do some solutions so we'll have our look up here we can make that a set and we'll check well let's first calculate what's the value we want and that be the nums of i+ nums of j and we that be the nums of i+ nums of j and we that be the nums of i+ nums of j and we have to subtract here because that's going to be what's required for us to get our solution and if X and look up then we could pen to our output B nums of I and wall typos nums of J and X we'll make that a list okay otherwise add it to the diction a dit to the set so we'll add it to our set add we need to add the not the ex the current number of the world so num nums J and that should have been it so imagine my surprise when I rented found that oh this is even worse I remember - and - why is that there I remember - and - why is that there I remember - and - why is that there mmm - and - I linked up gnomes i ji j mmm - and - I linked up gnomes i ji j mmm - and - I linked up gnomes i ji j know oh okay we've added duplicates okay so that's one either way though I don't get the right answer and I was pulling my hair why is this not correct and I realized oh what my algorithm does is count negative one zero one that's one solution it also counts 0 1 this negative 1 as another so ssin so in my opinion I felt like that should be correct but here they said we want to find all the unique triplets and that made this much more tricky because we could count two negative ones in our solution but if we have a solution that uses a different set but it's the same combination that shouldn't count we've already offered that as a solution okay so how could we solve this well there is one other way accepted way and I didn't want to use that but unfortunately that seems to be the only way to solve this and what you would have to do is if we could sort our list then we can actually solve we don't even need the twosome solution we could have a two-pointer solution we could have a two-pointer solution we could have a two-pointer solution but we'd still need this nested for loop but this allows us to do some tricky things to make sure that we're not going to have duplicate combinations so let me show you what I mean the first thing is alright first we need to calculate our L and our so L will be equal to I plus 1 in this case and R will be equal to again length of nums but subtract 1 okay so while L is less than R what we do well let's first check is nums of I plus nums of L plus nums of j is that equal to zero because if it is then we want to immediately add that to our output so we'll just add all three of these into a list go and once that happens we could add one to our L and subtract one from our are okay otherwise if the value turns out to be greater than zero well then it's greater so we wanted to decrease the amount so subtract L let's subtract one from our otherwise we want to add to our one okay so let's see what happens when I use this up I forgot we need to make sure to not count duplicates right so if let's see if I is great if I is greater than zero and nums I equals nums I plus one then just continue all right so let's try that okay Jay I'm not J fault our are so I thought this might solve it up what now Oh stupid yes because we want to check the previous one okay so that seems to work now let's submit that but again we get a wrong answer and I pull my hair and then I realized Oh God we also need to care about the duplicates here so how do we need do that okay well while and this parts tricky it's while first make sure we're not going to break that and for nums of l equals nums of anything so it's L plus 1 we want to actually increase our L plus 1 as well and do the same thing but on the opposite side but this one for R and R minus 1 ok so let's try that and finally I solved it and this I cannot believe like this is the accepted solution because of that one little caveat we don't want unique output or we want all these combinations to be unique it was very tricky because you don't want to you know have to do some sort of check every single time to sort it and create a set but this seems to work it's the most accepted method honestly like I knew about the two-pointer method but this part was two-pointer method but this part was two-pointer method but this part was really confusing I had to look that up so anyway I hope that helps | 3Sum | 3sum | Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`.
Notice that the solution set must not contain duplicate triplets.
**Example 1:**
**Input:** nums = \[-1,0,1,2,-1,-4\]
**Output:** \[\[-1,-1,2\],\[-1,0,1\]\]
**Explanation:**
nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0.
nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0.
nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0.
The distinct triplets are \[-1,0,1\] and \[-1,-1,2\].
Notice that the order of the output and the order of the triplets does not matter.
**Example 2:**
**Input:** nums = \[0,1,1\]
**Output:** \[\]
**Explanation:** The only possible triplet does not sum up to 0.
**Example 3:**
**Input:** nums = \[0,0,0\]
**Output:** \[\[0,0,0\]\]
**Explanation:** The only possible triplet sums up to 0.
**Constraints:**
* `3 <= nums.length <= 3000`
* `-105 <= nums[i] <= 105` | So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search? | Array,Two Pointers,Sorting | Medium | 1,16,18,259 |
787 | today's lead Cod DCC question is cheapest flights within K stops let's read the question there are n cities connected by some number of flights you are given an array flights where flights I says from to price indicating that there is a flight from City from to City two and the cost of the flight is price I you are also given three integers Source destination key return the cheapest price from source to destination with atmost Cas stops remember it's written at most Cas stops and if there is no such route return minus one so what question is saying that we have given a source a des destination so we have to return the cost to reach from source to destination so to reach from source to destination either we can take a direct flight or we can take we can stop at one place and then take a flight from that place or we can stop at 2 place and then reach the destination so like this we can take at most K stops and then reach the destination so out of all the possibility we have to find out which path is giving us the minimum cost so we have to return that and also there might be a case that there is no way to reach from source to destination in that case we have to return minus one that means there is no connectivity from source to destination let's take one example Suppose there a City aabad Bangalore and Kolkata and there is a flight from ahmdabad to Bangalore and the cost of the flight is 400 that is a flight from aabad to Kolkata and the cost of the flight is 100 and again there is a flight from Kolkata to Bangalore and the cost of the flight is let's suppose 200 now if we have asked what is the price cheapest price to reach from Amad to Bangalore then first we have to see what is the K value indicates how many stops we can take suppose K value is zero that means we can't take any stops we have to reach directly from Amad to Bangalore if K is zero that means we can't take any stops so that in that case we have only one option that is Amad to Bangalore with cost price at 400 so in that case our cost will be 400 now suppose K given is one that means we can take at most one stops it's not necessary that we have to take one stop so in that case we will see we have two option either we can take a direct flight that is k equal to Z or we can take a One-Stop Z or we can take a One-Stop Z or we can take a One-Stop flight that is k equal to 1 so in case of k equal to Z we have only one option that is Amad to Bangalore with cost price of 400 right now for k equal to 1 that means we can take one stop and then reach Bangalore so again we have only one option from Amad to Kolkata and then Kolkata to Bangalore in that case the cost will be 300 so now we have to see which one is giving us the minimum so we can see if we take a on stop flight then cost will be minimum so the answer for this will be 300 that means we can reach from amabat to Bangalore with the minimum cost of 300 and there can be a case like if someone ask what is the cost to reach from Kolkata to Amad and so in that case suppose if K given zero we have to see that means we have to check by taking one flight what is the minimum cost to reach from Kolkata to Amad so from Kolkata to Amad we can see taking one flight we can't reach Amad so taking one flight we can only reach Bangalore if k equal to Z that means we don't have a direct flight that means in that case is we can't reach anath so we have to return minus one now suppose we are given K = to one now suppose we are given K = to one now suppose we are given K = to 1 so we have already seen for k equal to Z we can't reach now we will see by taking at most one stops can be reach to Amad or not so from Kolkata we can see we can only reach Bangalore and from Bangalore we can't take any flights we can't reach anywhere that means even if we take a one stop flight we can't reach Amad so in that case also we are getting minus one so in this we the result will be minus1 now suppose we take one more example we have Kata we have aabad and we have Bombay now suppose from Kolkata to Ahmedabad we have a flight and the cost is 100 from Kolkata to Bombay we have a flight and the cost is 200 and from Bombay to Amad we have a flight and the cost is 300 and from ahmdabad Kolkata we have a flight and the cost is 300 now if someone asked me what is the cost to reach from Bombay to Kolkata and K value given is zero in that case we will see k equal to Z means we can take at most k + 1 most at most k + 1 most at most k + 1 flights so here k equal to Zer that means we can take at most one flight so taking one flight from Bombay we can reach only Amad so we can't reach Kolkata so in that case our answer will be minus now suppose K value is one that means we can take at most k + one that means we can take at most k + one that means we can take at most k + one flight that is two flights to reach Galata so from Bombay we will see where all places we can reach so we can reach only aabad so taking one flight we can reach aabad okay and the cost is 300 now from Amad we will see in where all places we can reach so we can reach only Kolkata so in that case the cost is 300 so since we have allowed to take two flights so by taking two flights we can reach from Bombay to Kolkata so in that case our answer will be 600 so that's what question is saying so we have to return this value now let's take this given example and reach the solution suppose we have this example in this example the N equal to 4 that means we have four cities flights given like from City 0 to City 1 we can reach at Price 100 City 1 to 2 we can reach at Price 100 ct2 to0 we can reach at Price 100 and City 1 to 3 we can reach at Price 600 and City 2 to 3 we can reach at Price 200 and the source given is zero and the destination given is three and the K value is 1 that means if K value is one that means we can take at most k + one flights right so what we will do first we will draw one table so we have four cities so in the column we will keep the cities that means we have four cities and in rows we will keep the number of flights we can take zero flights one flight suppose so this column indicates the city number and row indicates the number of flights taken to reach that City now we will give a numbering so this is City 0 City 1 City 2 City 3 and the flights this indicates zero flights taken one flight taken two flights taken the flights taken so initially we are at source and we have not taken any flights till now so at source zero that means we are at zero City we are at City number zero so the cost to reach at City number Z is zero and other places it is infinity that means we can't reach taking zero flights we can't reach the cities now suppose so since K value is 1 and we are uh that means we are allowed to take at most two flights right if we take one flight and we are at City Z so we will see in which all places we can read from ct0 we can see we can take only one flight and we can reach only at City number one so to reach city number one from City number zero what will be the cost to reach at City number zero and the flight cost which we are taking from City number 0 to one that is 100 so to reach one taking one flight the cost will be 0+ 0+ 0+ 100 that is 100 right so we will see can we reach any else anywhere in other cities from City number zero so from this given flights we can't reach so from zero we can only reach at flight City number one now since we are seeing we have taken a one flight we have already taken one flight so after taking one flight what are the places we can reach if we have taken one flight we can reach only one that means to reach city zero after taking one flight is infinity this is also Infinity this is infinity now we will see after taking one flight in which all cities we can land and from there we will explore we will take one more flight and see in which all cities we can reach so after taking one flight we have only one options that is City 1 now we will see from City one in which all places we can read from City 1 we can see we have two options either we can go to City number two or we can reach city number three so if we go City number two what will be the cost to reach city number two so to D City number two the cost will be cost to the city number one and the cost of the flight from City number one to two that is 100 plus 100 that is 200 and from City number one to three what will be the cost to reach city number one and the flight cost to reach to take from City number one to three that is 100 plus 600 that is 700 so now can we say after taking two flights we can reach only to City number two and three if we have necessarily taken two flights then we can reach only City number two and three if we have started from Destiny Source zero that means we can't reach two we can't reach one now from 2 to three we will see which all places we can reach so from two we will see we can reach two from two we will see we can reach three and zero from two we can reach three and zero so to reach three what will be the cost so to cost to reach two plus the flight cost to take from 2 to three that is 200 plus 200 that is 400 and to reach zero the cost will be 200 plus 100 that is 300 so that was from City number two now from City number three so from City number three we don't have any flight that means we can't go anywhere else that means after taking three flights we can reach only City number zero and City number three that is we can't reach one and two if we have necessarily taken three flights so this row indicates if we have taken zero flights we can reach only at City number zero if we have taken one flight we can reach only City number one if we have taken two flights we can reach only City number two and City number three and if we have taken three flights we can reach city number zero and City number three so this was like what row is indicating now if we see a column wise so what column zero is indicating that from CT number zero that we can reach city number Z this row will indicate what are the prices to reach city number zero if we have this we have taken this many flights now so in the question the K value was one that means we can take at most two flights that means this option is valid since here we are taking two flight but this option is not valid because this row indicates we can reach the cities after taking three flights but we are not allowed to take three flights so we will see only in this first three row so what is the destination is three so we will go to three and we will see whether we can reach the destination three any time after taking either zero flights one flights or two flights so we can see after taking zero flights we can reach but after taking one flight also we can't reach but after taking two flights we can definitely reach three and the cost to reach is 700 so the answer will be 700 now Suppose there would have been any flights which made it possible to reach city number three after taking one flight also and the cause to reach city number three after taking one flight if it was 400 suppose then in that case we have to check and being a destination three we have to see can we reach destination number three by taking after zero flights one flights or two flights so we can see after taking two flights also we can reach rest number three and after taking one flight also we can reach destination number three and after taking two flight also we can and reach destination number two so out of this we will see what will be the minimum to reach so minimum to reach city number three the cost will be 400 now since now suppose if the K value would have been two not one so in that case we would have taken at most three flights so in that case if this in that case this row would have been also valid so we will see to reach city number three what are the possible ways so by taking zero flights we can't reach by taking one flight we can reach at Cost 400 by taking two flights we can reach at Cost 700 and by taking three flights also we can reach at Cost 400 so in that case we will take the minimum of this row and if there has been a case that there is no flight in that case all this row would have been infinity and we would have written Infinity that means we don't have any flights in that case we would have written minus one I hope I have explained the solution let's take one more example so this is a small example let's take this example so since we have three flights and the K value given is one that means we can take at most two flights so since column indicates the city number so we have three cities 01 2 we will write 0 1 2 and since K value given is one that means we can take at most k + one can take at most k + one can take at most k + one flights that is two flights so we can indicate zero flights one flights two flights and Source given is zero and destination given is two so since source is zero so by without taking any flight we can reach at source zero at Cost Z and city1 the cost will be infinity and cd2 also cost will be Infinity now after taking one flight we will see in which all cities we can reach up from City number zero so we can and see we have two options either we can go to City number one or we can go to City number two so if we go to City number one the cost to re City number one will be 0 + + + 100 that is 100 and to reach city number two the cost will be 0+ 0+ 0+ 500 that is 500 so that means if we have mandator taken one flight that we can only reach city number one city number two but we can't reach city number zero so in that case it will be Infinity now suppose from City number one we have taken one more flight so we will see in which all cities we can reach so from City number one if we take a flight we can only to City number two that is to reach city number two from City number one the cost will be 100 plus this 100 plus the cost of this flight 100 that is cost will be 200 and to reach from City number two we will see we can't take any more flights that means after taking two flights necessarily we can only reach to City number two and not City number zero not City number one so it will be Infinity now since we are asked the destination is two so we will see the column number two and see can we reach city number two anytime after taking any of these flights either one flight two flights or zero flights so we can see we can reach city number two after taking one flight also after taking two flights also so what is the minimum to reach here so to minimum to reach city number two so minimum will be minimum of 500 and 200 so minimum is 200 the answer will be 200 that means to reach city number two from City number one the cost will be 200 so that's the answer now suppose I want to take one scenario now Suppose there is a scenario suppose this is City number 0 1 2 and we can read City number two after taking one flight is the cost is 200 and to reach city number two after taking one flight the cost is 300 00 now Suppose there is a flight from City number 2 to one and also a flight from City number 2 to one the cost of this flight is 50 and the cost of this flight is 200 so by what value we will read by what value we will update this cost since after taking two flights we can reach to City number one from two ways either from one from City number zero to City number one or from City number two to City number one so in that case we will take the minimum to reach here that means we have already Tak we are already taking two flights right so after taking two flights we will take the minimum of this cost that means minimum of two 200 + 200 + 200 + 300 comma 300 plus 550 that is we will upgade this position with rupees 350 so if we have multiple options to reach any cities by taking any number of flights we will update with the minimum value right there is no sense of updating with 350 500 because this cell is saying that to reach city number one from a source suppose Source was zero so this salice indicate to reach city number one from a source zero after taking two flights mandator we can reach with a minimum cost of rupees 350 so that's was the point I want to make it clear so what we are doing so let's see the time complexity if we write an algorithm for this so what we are doing suppose so after every flight we are updating what are the places we can reach from the source that means for each position we are updating the next position suppose we can suppose at a certain instance we are reached all the cities we can reach all the cities now if we want to update the next instance like after taking one flight what are the cities we can reach so what all we can we have to check so from City number Z we have to check if there is a flight to City number Z if there is a flight to City number one if there is a flight to City number two that means for each position we have to Check N cities so if there are n cities we have to check n Square cities right so every time we are checking n Square cities for each flight and if there is k + one flight and if there is k + one flight and if there is k + one flights possible then we have to check k + then we have to check k + then we have to check k + 1 into n² so this many operations we have to perform so time complexity for this algorithm will be Big O of K into n² and since we can see the K value given is less than n so if this is maximum n that means we can re reach we have to perform n Cube operation so and we can see the value of n is maximum 100 that means it will take a maximum of 10^ 6 time complexity that means we can perform this algorithm so one more thing I want to make it clear like the information given to us about the flight is in a vector it is not like what we are seeing in a graph so before that we can convert the given information into a graph and then we can perform this operations so let's write the code first we will try we will create a map which will store this information let's and the graph size will be and since there are n cities so we'll create n nodes to it now we will iterate the flights vector and update the T graph of it of zero that is Source from source we can reach destination and destination given as it of one and the cost to reaches it of 2 so we have created the graph now what I have said like how many flights we can take let's write fly so it is k + one fly so we can fly k + 1 one fly so we can fly k + 1 one fly so we can fly k + 1 times so to draw that table we have to create a 2d Vector let's WR ta side route and since we can take at most f l y that is k + 1 flights so y that is k + 1 flights so y that is k + 1 flights so to make fly + make fly + make fly + 2 of fly + 2 of fly + 2 of fly + 1 comma Vector of end and initially since to reach any cities will be Infinity unless we update that cell so we will use int Max and the number of columns is the city number so this is the table we have drawn now we will update this table one by one so initially we can see if the source is given that means to reach a route that is Source at zero flight means without taking any flight we can reach this only source with cost zero so we will upate now for each flight that is from flight one that is from after taking flight one that is from 0 to fly so for each flight we rate like so this will indicate this loope is indicating like suppose we are at position number zero without taking so suppose now we take one flight so we will reach at position number one so we will update this cells so since our fly value will indicate how many flights we can take so we will iterate flight times and for each flights we will update the city's values whether we can reach that City or not and the City count is then now we will see if we have already reached that cities or not so if we have reached that City then this int max value would have been updated that means we can compare it with int max if I that means current city and after taking current flight that is zero I if it is not equal to int Max that means we can we have reached the city now we will explore the flights we can take from City number I so we will iterate ID so from the graph we can iterate the flights we can take from City number I and in what we have decided like we will update only if the existing value is maximum than the current cost that means we will check if current cost that is I + 1 it of Z is greater than route greater than current flight cost i j plus it of 1 in that case we will dated this is the case we will update it else we will not now after updating all the values we will see whether we can reach the destination or not so let's suppose the cost is in Max we will see we will run a for Loop for that column that is the destination column for the whole flight from I = to column for the whole flight from I = to column for the whole flight from I = to 0 till I = till I = till I = to I less than equal to fly I Plus+ to I less than equal to fly I Plus+ to I less than equal to fly I Plus+ and we will see whether we can reach that destination by taking any number of flights or not suppose if the route and the flight is I and the column is destination DST destination if it is not equal to in Max that means we could have reached that destination after taking I number of flights so in that case we will update this cost value with the minimum of cost and the current cost that is route of i n DST now we will see so we have already updated with the cost variable now after updating still the cost value is in X that means we can never reach that destination in that case we will return minus one else we will return cost now let's see what we have done so in this since we can take K flights that means K stops that means we can take k + one can take k + one can take k + one flight if it is k + 1 that means if K flight if it is k + 1 that means if K flight if it is k + 1 that means if K value is two we can take three flights so we have to create a dimension of 0 1 2 3 that means either we can take zero flights one flights two flights and three flights if the K value is two so we have kept this value and fly and we have created a dimension of fly + one so initially we will be at position number zero we will check whether from source to destination we can reach after taking one flight so after taking one flight our value I will increment to one after taking two flights our I will increment to two and after taking three flights our I will increment to three right and then after updating this table we will find the maximum minimum to reach that City so that will be the cost let's try to run this solution since we can see our test case has been accepted now let's try to submit all the test cases so our solution is accepted and we can see the time complexity of this solution will be fly into n into the neighbor of this node and the neighbor can be at most n that is and fly value we can we have seen it is k + fly value we can we have seen it is k + fly value we can we have seen it is k + 1 and K value also we have seen from the constant it is can be at most n that means the time complexity is n into n that is O of NQ I hope I've explained the solution meet you in the next video thank you | Cheapest Flights Within K Stops | sliding-puzzle | There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`.
You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`.
**Example 1:**
**Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1
**Output:** 700
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops.
**Example 2:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1
**Output:** 200
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
**Example 3:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0
**Output:** 500
**Explanation:**
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
**Constraints:**
* `1 <= n <= 100`
* `0 <= flights.length <= (n * (n - 1) / 2)`
* `flights[i].length == 3`
* `0 <= fromi, toi < n`
* `fromi != toi`
* `1 <= pricei <= 104`
* There will not be any multiple flights between two cities.
* `0 <= src, dst, k < n`
* `src != dst` | Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move. | Array,Breadth-First Search,Matrix | Hard | null |
828 | hello and welcome back to the cracking paying YouTube channel today we're going to be solving lead code problem 828 count unique characters of all substrings of a given string let's define a function count unique characters s which Returns the number of unique characters in s for example counting calling count unique characters on S if s equals to leak code then l t c o d are the unique characters since they appear only once in s therefore count unique characters equals five given a string s return the sum of count unique characters T where T is a substring of s and the test cases are generated such that the answer will fit in a 32-bit that the answer will fit in a 32-bit that the answer will fit in a 32-bit integer and you'll notice that some substrings can be repeated so you'll have to count the repeated ones too let's look at a basic example ABC and let's enumerate all of the possible um substrings we can have right we could have a b c we could have B on its own we could have C on its own we could have uh whoops we could have b c right those are all of the possible substrings we can have now what are their lengths right so a has a length of one B has a length of one C has a length of one obviously a B has a length of two uh ABC has a length of three uh and BC has a length of two so if we add all this up one plus one that's three plus five uh plus two five plus three eight plus two ten so we would return ten here the problem is this question is really easy if you look at it and you want to draw all this out and you know the naive solution would be to just generate all the possible substrings and take their lengths uh the problem with that is that when your String's really big that's going to be a really inefficient solution so what we want to do is we want to somehow do this uh in one pass if we can in some sort of like a greedy Manner and that's what we're gonna do though I will warn you the solution is a little bit tricky to wrap your head around um so what we're going to do is we're going to walk through an example and hopefully it will help you kind of wrap your head around it although the intuition behind it may take some kind of thinking to see why it works but what we want to do now I'm going to wipe all of this away and we're going to look at a little bit better of an example and actually walk through how the solution is going to look because it is quite complex and I really doubt that you're going to come up with this on your own so let's now wipe all this away and think about our actual solution we talked about the naive solution but that wasn't good enough what we want to do now is go over the actual solution so we're going to need a few variables here to actually help us um and if I could just get my pen back so the first one obviously we're gonna have to keep track of a result which in the beginning is going to be zero because we haven't counted anything we're also going to want to keep track of the current count um basically the length of our current substring that we can form and that's going to be zero as well what we want to do now is because there can be duplicates in a string this poses a bit of a problem for us because we don't want to be double counting things uh in the case that there's duplicates right like in this string we cannot form the substring ACB a b c b right because then we'll have two B's and that's no longer unique so when we see that second B we have to be careful not to actually double count things uh in our substring that we can form and we have to only uh basically form substrings from the last time we saw a b because only that part will be unique so when we see the second B we can form the substring C and C B uh we can't form a b c b we can't form it you know BCB because those have two B's and obviously that's not unique so every time we see a repeated character we actually need to only consider substrings from the right of whatever that last uh character was and for this reason we're going to have uh two dictionaries or we can just have one actually so we'll have a dictionary and we'll call this D which maps for each character it's going to map to a list and what that list is going to have is the last scene index for that character and then we also want the um you know the last before the last so the second to last right so second to last and we're going to store this and in the beginning all of this will be initialized to -1 and you'll see why we initialized to -1 and you'll see why we initialized to -1 and you'll see why we need to do this in a second uh basically this is just to handle the edge case when you actually see a character for the first time we want to be counting it properly so that is the general um setup that we want to have here so let's just remove all this stuff for our D so we can have an empty dictionary and let's actually go through this um line by line so what we're going to do is we're going to go over our string from left to right and we're going to get the current index and the current character so let's kind of just separate this so the current index is obviously zero and our current character is a so when we have a the obviously the only substring we can form is a right so the length of our current substring is going to follow this formula so we're going to add to whatever the length uh our current length is we're going to do this we're going to say whatever I is so our current index minus the last time that we saw um you know our eye right so we want to basically uh okay so what is it in here so we don't have anything so we would initialize our key for a here to basically be minus one because that's the default value so we're going to say our length is I which is zero actually let's replace that uh no I'm going to lose all this whatever it's fine uh we're gonna say zero and then we're gonna put a in here so a and this is minus one and you'll see why we do this second so we do zero minus one um because that's the last time we saw it uh is that the minus one index and this is actually that edge case we're talking about when you actually just have one character and now we need to subtract um basically the amount of substrings between the last time we saw it and the previous time we saw it because we again don't want to be double counting things uh because that won't be allowed so we would essentially say minus one uh so we take whatever the previous index was that we saw it at and we're going to subtract from this the second to last time we saw it so obviously this is -1 the double obviously this is -1 the double obviously this is -1 the double negatives will cancel out here so this is minus one plus one so this is actually just zero and then this is just the double negatives will cancel out so we're going to essentially add to our current one right so current now becomes one which makes sense right the length of our substring is one okay we can kind of Sanity check that now what we want to do is we want to update our values in um you know our dictionary here so the second to last value now becomes whatever the last value was because we've now seen the character so we can actually rewrite this and we can also update the last scene so the last time we saw a was at zero and obviously the last time we saw it before that was at -1 because we haven't actually seen it -1 because we haven't actually seen it -1 because we haven't actually seen it before now what we need to do is we need to just simply add to our results whatever the length of the substring is which is one so our result now becomes one and then we move on to the next character so now we're going to be at index one and this is going to be B right so now we're going to do the same thing we're going to say we're going to add to our current substring length so obviously with B the substrings we can form are a B or just B so in total we want to add one character plus two characters plus one so let's kind of Sandy check that we'll get that at the end here so in total we should get four uh after this step so what do we want to do so we want to take our current index which is one we want to subtract the last time we saw a b we haven't seen a b so it's just going to be at -1 and then we also want to be at -1 and then we also want to be at -1 and then we also want to account for the fact that they could be um you know the previous B so we're going to take the last time we saw B uh minus the time before that but since it's just negative one uh whoops this should still be zero and then here we will have one minus one so this is going to be two so we want to add to our current um and make it two so remember current was one before so we want to basically um you know account for these two substrings now um the length right here so once we add two to it this will become three so three and then remember we're going to update our dictionary so B when was the last time we saw B we saw it at index one and the one time before that we haven't actually seen it so it's still going to be minus one and remember when I add to our result the um three that current equals now right that's the length of our current substring so we're going to add 3 to our result and now it's four right and we can sanity check this because this is what we established in the beginning so we're on the right track now what we want to do is we get to uh index two and C again we're going to do the same thing so the current value plus equals and we're going to do the current index which is 2 when was the last time we saw a c we haven't seen a c so we do minus one and we want to subtract from this the last time we saw C and then the time before that so again we haven't seen a c yet so this will cancel out and this equals three and then let's just sanity check again so at C what are the substrings we can form right we can form a we can Form B C we can do BC or we can do a b c right and the total length here is going to be three two one right uh hopefully we haven't missed anything there but I think that is all of them right um let's see actually did we miss anything let me try to think no I think we're okay ABC BC ABC so this is five plus eight right so we should have eight at the end of this step actually hold up I think we may have missed one let me double check uh oh I forgot a b whoops yeah a b so yeah it should be ten my bad yeah I was thinking back to the example yeah so we should have 10 at the end of this step so obviously this is going to evaluate to three so we're going to add to our current uh three so now the current length will be six and then remember we need to update our dictionary so we haven't seen C yet so we first seen it at two and the last time we saw it was at -1 because we time we saw it was at -1 because we time we saw it was at -1 because we haven't saw it now remember we want to add to our result uh whatever current is so that's six so we're going to add to our result six and it now becomes ten so we're on the right track because our results are matching so we can kind of Sanity check that this algorithm is actually working now what we're going to do is we're going to get to an interesting part which is when we see our second B because this throws a spanner in the works right so we get to 3B now let's think about this right we can't form a string like a b c b because there's two B's here which means that doesn't work right so what are the possible substrings that we can do well we could do CB is one or we could just do B on its own so that is a total of three right and if we were to add it to our you know previous one we should um you know basically end up with 13 right so what we need to do now is we need to count this without accidentally double counting all the substrings that we've already formed because we cannot actually access any of these because they're locked behind the fact that we've already seen a b right we can only access things to the right of this previous B and build substrings from there we can't actually do anything there so we need to make sure that we don't double count things that we've already seen and that's the reason why we're keeping track of these values in terms of like when was the last time we saw a value in the previous time so let's look at how this works so now we have B right so we'll go through the formula again occur and then we're going to add to current so what is our current index three now when was the last time we saw a b last time we saw B was at one right so what we're going to do here is we're going to subtract one from our three here and now what we need to do is we need to say okay when was the last time that we um you know uh essentially saw a one here right so we saw one at one and then we want to subtract a minus 1 from this so what we want to do here okay sorry my recorder cut out there um essentially where we were at we were doing this formula so this is going to be 2 and then minus so 1 minus 1 this is two and this actually gives us zero now why is this significant well let's think about all of the you know the substrings that we could build here right we could build uh a b c b uh we could build b c b oops uh BCB we could build CB and we could build B now we can't count the entirety of this substring or this substring right because we only want the unique characters which means that we can only count a b uh as two and we can only count this one as one because it only has that c that we can count uh this CB we can count as two um so c b that's two and then this B which is just one right so if we were due to this it's actually six which is what our current is currently at so we don't actually want to count anything new here so we simply append to our result which is currently 10. it now becomes 16. so let's again sanity check this to make sure that we are correct here so uh let's kind of okay we'll just wipe away some stuff so let's build all the substrings we can do so remember we are so far at a b c b right so we have a b c b and then we have B we have BC we have c um we have um CB we have b c b and do we have anything else here let's see uh then we have a B on its own again and then I think that is it yeah that should be it okay so let's add all of these so obviously a has one unique character a B has two unique characters ABC has three a b c b has a and C we cannot count the B's so this is two B has one this has two this has one unique character the C and one here so one plus two three plus three uh three six plus two eight plus one nine plus two eleven plus one um twelve plus two Fourteen and then plus one equals sixteen so we are still okay because our result is as we saw we added Uh current uh our six to ten so we are still on track because our result is right so now what we want to do is let's now kind of clear things away because we want to make some room here and okay so we know that current is still six and our result is now 16. so the last thing we need to do is remember we need to do 4B which is that last character so again we're going to say current plus equals two so the current index is four when was the last time that we saw a b so actually we need to update this from the last time so the last time we saw a b was actually at three and the time before that was at A1 so we want to say four uh minus when was the last time we saw it at three and we want to subtract from this so we want to take the last time we saw a b 3 minus when was the last time we saw the time before that a one right so this is going to be 2 and this is going to be um let's see this is going to be one so two a one minus 2 is obviously negative 1. so we want to update our dictionary as well even though this is the last key we don't technically have to do this but for good measure it's now 4 3 and then we want to add to our result uh minus one right so current uh we're going to subtract one from current so current now becomes five and we're going to add to our result of five so we would get twenty one here which is actually going to be our final result now let's do one final sanity check because this is a little bit complicated and you may not believe me that this works so our substring is a or sorry our string is a b c BB so what are all the possible substrings here hopefully I actually managed to enumerate all of them but we have a b c b we then have B on its own we have BC we have b c b and then we have C on its own we have CB we have c b then we have B on its own again or we can have BB and then we have B on its own okay so let's count all these so obviously a only has one unique character a B has two unique characters ABC has three unique characters a b c b only has a and C as unique characters that's two a b c b we only have again A and C so we can only count those two uh B is one BC is two BCB is just the one from the C bcbb is just the one from the C then we have the C on its own which is one CB which is two CBB which is one again one here this is zero and this is one so one plus two three plus three six plus two uh eight plus two ten plus one eleven thirteen uh fourteen fifteen sixteen seventeen eighteen nineteen 20 and okay did I forget one somewhere let's see I probably did um let's see did I forget one somewhere okay I definitely I'm off by one somewhere um but where exactly is that I don't know let's see uh A1 so this is two so it's three six uh two this is two uh so it's 10 11 13. 14 uh 15 16 18. 19 20 21 okay yeah I miscounted okay yeah so we're still at 21 and that's our final answer so quite complicated um but you can see that it works essentially we just want to make sure that we're not uh double counting things so we're just keeping track of kind of what the current length is and using that to help us so hopefully that kind of makes it clear walking you through um the kind of line by line um now let's actually go to the code editor and type this up it's really easier to code than it is to explain which is unfortunate so we're back in the code editor let's write the code remember that we need a current variable and our results which are both going to be 0 and we also need our position dictionary which is going to be a map for each character the last index we've seen it and the index before that um so we're going to say collections Dot defaultdict and we want to initialize this with a minus one if we haven't seen the key before so we're going to say for I Char in enumerate s uh what we want to do here is remember we do current plus equals to I minus what we're going to say position dictionary of our character right Char and remember that we want to access the uh last time we've seen it so this should be what this should be the zeroth index and then we want to subtract from the time the last time we saw it so we're going to say a map sorry position dictionary of our character uh the last time we saw it minus the position dictionary of the character for the time before that and then we want to update our positions so we are essentially going to say position dictionary of char of 1 is going to equal to whatever the current uh last time we saw it was so position dict Char uh zero and then we're also going to say that position dictionary of char for the zeroth is whatever our current index is and then we want to say res plus equals to whatever Cur is and then we simply return res at the end so what I want to do now is I'm going to submit this make sure that it actually works um so accepted cool uh I want to talk about the time and space complexity and then we will kind of do a little bit of an explanation for this formula here because it can be confusing we know that it works because we draw obviously it's accepted and we went through a dry run so we know how it works and that we get the right answer with it but how we actually derived it is a bit unclear so let's first do the time and space complexity obviously all we're doing is going over our characters from you know left to right in the string and we do a few lookups in a dictionary which is basically a constant time so it's just going to be a big O of n uh in the time for the space um we have this position dictionary so that's going to be dependent on basically the number of unique characters uh in s so it's just going to be Big O of n uh actually here let's see um let me just double check this let's see what is our okay so since s actually consists of only uppercase English characters the maximum amount we're gonna store in our position dictionary is actually just going to be 26 uh which means that we just have Big O of one here uh for this base complexity because the maximum we can store is actually 26 keys and because we know that up front it's actually Big O of one uh even though it may not seem like it because it's only 26 keys and we know that up front yeah it's big o f one so now that we have that out of the way I think that what I want to just talk about is why we use this kind of formula so what we are essentially doing here is let's think about what happens when we add a new character right we get like a b c b we want the how many new characters is this going to contribute right how many unique characters it's not going to be this entire array or this entire substring because we've already seen a b which means that we cannot count uh B before right we cannot count it so we need to account for basically all of the B's that we've already seen because we don't want to count them again um so it's essentially going to contribute how many unique characters well it's going to contribute how many are between C and B right so the index where we see B now is going to be what at the third index so index three when was the last time we saw a b we saw it at index one so that means that this is going to contribute two unique characters and how is that so well we could have C or we could have CB or we could have um sorry uh or we could have B right so my recorder cut out again um but essentially let's now think about how this uh works so remember the string a b c b right when we see this second B what happens right that means that when we have a substring because before we can have a substring like ABC if we're to add to the B to it unfortunately this now gets rid of um the B that we could actually count in that substring because now we've reduced our character by basically the number of you know B's we have between them right which is two and now we'd only get a and C whereas before we had ABC which was three so what we're doing here is remember we see the B at index three so everything after the last B is now unique right so we could have c b c and b right those are our new unique uh characters that we can get so we want to take count of that right so we want to say that three and when was the last time we saw B well we saw it at index one so the new unique counts we can get is going to be you know the CB which is two right so this is two but we also have to account for the fact that now that we added a b we're also going to lose unique Counts from previous substrings so we need to account for that and this is what this part is right so when did we see uh previously that you know B so we saw it at one and when was the previous time well there's not a previous time before this one so it's still going to be negative one so -1 still going to be negative one so -1 still going to be negative one so -1 here so this obviously the negatives cancel out and this becomes a 2. and this is also a two uh so adding this B is actually not really adding any uh characters at its current iteration so remember we still have um some new characters like we still have substrings that can be formed right we still now that we added the second B we can still make BCB we can still make a b c b we can still make CB but with BCB right we only get one character here we only get now two characters here and now we only get um you know CB from this one so essentially we're trying to discount from previous counts that we've done um characters now that we've added a second one because obviously we can only count whatever the unique ones are so it's just the AC um so this basically attempts to do that and yeah it's still confusing even I get it um it's very difficult to wrap your head around I would say this is definitely a hard question even though the code doesn't look that complicated um actually explaining it is quite hard uh I think I've done the best that I can I mean I walked you through it makes sense on paper but uh explaining it I think if I don't know hopefully you watch this video and have some sort of epiphany um but this is you know the solution you want to go with anyway yeah uh kind of ending on a cliffhanger there this is definitely uh one of the harder Hearts um just because of how ridiculous it is to wrap your head around its algorithm people who come up with this I have no idea um so yeah there you go that's account unique characters of all substrings of a given string geez that's a mouthful but um hopefully you enjoyed the video hopefully it helps um I think definitely one to kind of just steer you on the right path and then maybe you can kind of connect the dots on how to actually explain it very well I think if anything this is the part that um kind of trips me up a bit um I understand it but it's kind of the part where you're running with the current um and how it carries over to the next iteration uh is still a little bit unclear for me so yeah anyway if you enjoyed the video like and comment uh if you want to see more content like this I promise my other explanations are much better this is a very hard problem I did my best on this one not gonna lie and um yeah uh thanks for watching and I'll see you in the next one | Count Unique Characters of All Substrings of a Given String | chalkboard-xor-game | Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`.
* For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`.
Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
**Example 1:**
**Input:** s = "ABC "
**Output:** 10
**Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
**Example 2:**
**Input:** s = "ABA "
**Output:** 8
**Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1.
**Example 3:**
**Input:** s = "LEETCODE "
**Output:** 92
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of uppercase English letters only. | null | Array,Math,Bit Manipulation,Brainteaser,Game Theory | Hard | null |
104 | hi guys welcome to algorithms made easy today we will go through the question maximum depth of a binary tree so given a root of a binary tree we need to return its maximum depth what is the maximum depth of a binary tree is the number of nodes along the longest path from root down to the farthest leaf node okay so if i say what is the depth of node 20 we can see that there are two nodes from path root to node 20 which is 3 and 20 itself so its depth here becomes 2. similarly if you want to find the depth for 15 or 7 it would be 3 as there are 3 nodes 3 20 and 15 or 3 20 and 7 and the depth for 9 will be 2 as it has 3 and 9 so if we see the maximum depth we can obtain here is at the node 15 or at the node 7 which is 3 and so we return 3 so now how do we code this for this we would need to traverse down the path and we need to add 1 while we get a root dot left or root.right which is left or root.right which is left or root.right which is not null so firstly let's write the null condition okay then for simplicity i will take a variable in which i'll store the depth so it would be recursive call to root dot left and r will be recursive call to root dot right at the end we will return 1 plus maximum of l and r you can actually omit these two lines and do substitute this over here and arcs value over here so it just becomes a two-liner code fine so it just becomes a two-liner code fine so it just becomes a two-liner code fine so let's try to run this one and try to submit it that's it got submitted so that's it for today guys thanks for watching the video i'll see you in the next one | Maximum Depth of Binary Tree | maximum-depth-of-binary-tree | Given the `root` of a binary tree, return _its maximum depth_.
A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 3
**Example 2:**
**Input:** root = \[1,null,2\]
**Output:** 2
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-100 <= Node.val <= 100` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | 110,111,774,1492 |
331 | okay so here we are back again another question let's just make sure things are working i think they are hello so if we look at another medium leak code question there we go take just a moment i yeah we'll keep going here we'll keep going so this question is verify pre-order serialization is verify pre-order serialization is verify pre-order serialization of a binary tree take a look one way to see your lines of binary tree is to use pre-order traversal is to use pre-order traversal is to use pre-order traversal i don't know what they mean by serialized so i guess we'll find out we encounter a non-null node and we record encounter a non-null node and we record encounter a non-null node and we record the node's value if it is a null node we record using a sentinel value such as pound okay for example the above binary tree can be serialized to the string 934 pound one pound two pound six pound four pound represents a null node given a string of comma separated values verify whether it is a correct pre-order verify whether it is a correct pre-order verify whether it is a correct pre-order traversal serialization of a binary tree find an algorithm without reconstructing the tree each comma separated value in the stream must be either an integer or a character pound representing null pointer may assume that the input format is always valid for example it could never contain two consecutive commas such as one comma three you may assume that okay so we want to parse it first obviously into us into an array the string the thing that's tricky about this question so we've seen a question like this already actually and it's let's do the parsing first so we're going to say let's do character by character hint i equals zero i is less than pre-order pre-order pre-order size plus i could actually do something like this auto character and pre-order i think this works too we want pre-order i think this works too we want pre-order i think this works too we want to say if c equals this character and we're going to do things if c equals this character and then we want to do things so this character we skip actually this is a null node so this is we want that's kind of interesting actually we don't necessarily need these pound symbols or do we what would we put an integer i want to put this into an integer array and then process the integer array however i actually don't know i said that's actually very interesting huh um that's awkward um i just wanted to dump everything into an array and then this becomes the you know is this a valid pre-order you know is this a valid pre-order you know is this a valid pre-order traversal question but actually with these pound symbols it becomes quite a bit more involved because these basically need to be not positioned incorrectly i guess and yeah pre-order traversal i guess and yeah pre-order traversal i guess and yeah pre-order traversal we've seen this a few times but basically the prior traversal says first new on the left is the head and some number of nodes are going to be the left subtree and then some then the rest of the nodes are going to be the right subtree and recursive algorithm i think is not too bad the tricky thing about it though is you don't necessarily know if the node the next node on the like you don't necessarily know when the right subtree begins so you kind of need to i guess um i'm actually not sure i don't even remember the algorithm for the pre-order check even after you pre-order check even after you pre-order check even after you parse so we are going to sit and think for a bit because this is actually a question that like i probably should know the answer to pretty quickly because i've actually seen it before but i tend to forget how exactly one verifies a pre-order traversal with verifies a pre-order traversal with verifies a pre-order traversal with binary tree is it a binary search tree or just a binary tree because i think if it's just a binary tree then you can kind of always call it i'm not sure if it's a binder i need to be a binary search tree nine pound one is false one pound is false i mean are we just counting the number of pound symbols that we need is that you know so one you need two pound symbols they have explanations they don't really and nine pound one doesn't work because i guess the pound ends the subtree maybe is that why 934 will give you one the first pound would be this is the head node this is the left subtree head of head node left subtree head node left sub tree and then the pound means that's sort of the end of that left sub you know that's the end of it and then the right the next pound would be the that right subtree i guess you can do a recursion on left and right recursions and you can use the characters as sort of inputs i guess we could do something like that way we don't need to actually store the characters in any kind of data structure will just be kind of on the stack because it's a little awkward having like a sentinel value in your integer array yeah it's very awkward to do that actually and the tricky thing is we need to not you don't necessarily want to go character by character because the tree the tricky thing about going by character is these integers you want to parse the integer but you also want to handle that sentinel value nicely it's a very awkward situation here well actually no never mind i don't want to do this i mean you can give a you can give like an index that you're currently in a point which character which yeah which character you're currently looking at and you can kind of do the parsing as you go something like that so we could try that i just used something like recurse keep it simple this is not going to take me a few minutes this might take a while this could be a while i have an index we'll call this with and we'll even probably return an index as well yeah return and index and we're going to i'm going to say for int i equals index i is less than preorder dot size increment i let's say character c equals pre-order of character c equals pre-order of character c equals pre-order of i if c is this symbol we're going to otherwise else if c is this symbol we're going to do other things and then we could say else if i really want to know that it's a digit c is c minus this character is greater than equal to zero and c minus this character is less than or equal to nine right so it's a digit so we'll have int value equals zero so we're going to have parse pars the value next value say then we'll say value is equal to 10 times what's already there plus c minus this and otherwise exit or break really and we're going to say that the value should already be computed at this point and here we also break and we set probably a boolean maybe boolean is sentinel we'll call it something like this i don't really know exactly what we should do set this to false initially sentinel right so we can exit our loop and we'll collect so we'll basically parse the we'll also update the index appropriately so index is then going to be updated i plus one or rather you can even just do something like this i equals index and then index equals i and we start off with that so it's going to be i plus 1 right so we're going to consume yeah we break at these points we don't update and we're going to consume these characters and i'm going to say base cases base case it's less than zero just to sanity check this is not a trick and say or this basically means you know don't recurse and just return this so we have our sanity check and now we want to say oh we actually want two things to be set here so let's just say is valid start off with true and then if we set it to false then pretty much call recurse we should also have auto f of the recurse with index zero initially of the string yeah okay so parse the next value check with the value valid expected actually we don't even care about the integer itself really we don't even need this vowel really let's just say continue we could just leave that out altogether right we don't care about that at all really and then value is valid slash expected so we're going to say left or right so we would say well a recursion is going to be recur what we're going to recurse on the left side and then recurse on the right side we're going to check our value here and we're going to say not sure actually what checks we're going to do how we're going to check this index it's going to be index and then we're going to say int temp equals f of index f and then we're going to say f of temp f and then return temp right because we add i we parse this value we do some calculating and the index is set to the next spot already and then it should be we assume we set the next spot again and then we return this value actually for the index and we want to say so these are the next index next to the next left index right index and so this will basically recurse through the sort of recurs through the tree the problem with this though is what are we calculating though when we go through our tree like what do we why do we care about this at all what are we looking for well the head node we're looking for either a we could end so we would say if is sentinel then we don't recurse on the left to the right now the problem is oh i think i know what the problem is don't even know if we don't think we even need to do this i think we just need i think you could just see that you just have to get all the way through and then that's it i think you just need to get all the way through so if it's a if it is a sentinel then we're going to return this index right check the value is valid so i should support slash expected so the left index that we get and there's the right index and return the right index rather than the left index i think this is all we need to do is just get all the way through yeah i think it's actually a lot simpler than i'm oh okay we always get true all right no we hm what's the problem exactly if it's a sentinel return check that the value is valid expected so for these two we would say all right let's say is valid right let's do that let's do boolean is valid equals false or it's true yeah and we say left is the sentinel the right is the sentinel and then i'm not really sure what this to do actually let's look at the left this look to the right both of these sentinel values will return like i'm thinking here right this left and right returns and then and the indexes what is oh wait a second where is the index i actually don't know what to do here i gotta think about it some more i gotta think some more 25 3 and 7. whoa zero one two three four five three zero one two three four five six seven so we oh wait why does this parse everything and same thing over here how come what i have a left and a right on hmm oh yeah no what hold on let me just look at let's just look at this one because i'm actually getting something unexpected here oh wait i don't know did that wrong actually we don't need to cut it we could just copy it all right we get seven zero one two three four five six seven and call this once and we say all right call these two call that left side that does that should be a sentinel and then oh that's why i see that doesn't matter that's why this is supposed to only break here that's my mistake look at this like how did we still get seven why though what we shouldn't do this anymore i think then because this we break here uh why do we still get seven though wait a minute what okay oh okey dokey oh what did we do that probably has something to do with it that's really confusing actually i don't know what we get now i don't know what was going on there six okay there you go zero one two three four five six it stops at six okay that's what i was looking for before saying that if we don't get all the way through it then it's false however there's also cases where that's what i was thinking i programmed it incorrectly which is always good so that okay that gives us the right answer there but i don't think that's the correct answer all the way through yeah because we should get false in this middle one and this middle one causes a problem so the reason the middle one causes the problem is because just copy this because it does get all the way through however we're supposed to have two of these if the left index if we're already at the end and this should return false sure that a right subtree exists if left index is greater than three preorder.size then is valid equals false how about that ah there you go so there has to be something that follows the left subtree and i think that's all you really need and you need to also make sure you don't stop too early and then if those are those conditions are met then it should be a valid serialization because it's not a balanced binary search tree or anything like that like there's no real conditions that we have it's just i actually might be totally wrong in that there's maybe needs to be maybe i'm crazy actually i don't know oh it's correct on all these really why would this one be correct the left subtree and this is on the right subtree and we get a left and the right and it's four right ones middle left right left that could be another left and then the left is done there yeah right about the one over here right um all at the bottom can we make this one true how do i make that one true so initial left the left one finishes this is the right then there's the left a left and then there's no right subtree it's got to be there oh wait what left done this has got to be the right one then this is then the left subtree are there not enough pound symbols for this like it's hard to do correctly right what tree would this be this would be like i don't know man i get this feeling like that my algorithm can't be right like it's too complicated for it to be right nine three two and there's a pound symbol and there's a thirty eight two three five and a left pounceable a right pouncable but there needs to be a pound symbol here after the three after the five and a two as you'll be one two three four five pound symbols leave five more pound symbols is that right one two three four five is that what we need is our text for your left [Laughter] apparently so dude i don't know how we do this iteratively this would be really challenging to do iteratively let's see if it works let's go for it oh we got it hey not bad sweet do i have any printout messages that are still in there i don't think so all right nice not too bad eighty percent four milliseconds not as fast as it could be oh hey 100 got him and not very much memory usage either whoa what did i do okay sweet i like that there we go and 30 minutes all right not great but okay i'll take it not the most it probably could be more efficient because you could probably do this iteratively however i think it'd be kind of hard to do this iteratively in my opinion that would be challenging you would need like i don't know it's just easier on a stack in my opinion it's just kind of easier so you could also return early here but it doesn't seem to matter very much on the test cases 100 there you go beat out everybody's solutions not too shabby all right let me go ahead and end this stream here and say thank you for watching i will talk to you soon that was my solution for yeah that is valid serialization hopefully that was interesting and i will talk to you soon take care | Verify Preorder Serialization of a Binary Tree | verify-preorder-serialization-of-a-binary-tree | One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`.
For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,# "`, where `'#'` represents a null node.
Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree.
It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer.
You may assume that the input format is always valid.
* For example, it could never contain two consecutive commas, such as `"1,,3 "`.
**Note:** You are not allowed to reconstruct the tree.
**Example 1:**
**Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
**Output:** true
**Example 2:**
**Input:** preorder = "1,#"
**Output:** false
**Example 3:**
**Input:** preorder = "9,#,#,1"
**Output:** false
**Constraints:**
* `1 <= preorder.length <= 104`
* `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`. | null | String,Stack,Tree,Binary Tree | Medium | null |
679 | hey what's up guys chung here again so today i want to talk about this lead called problem number 679 24 game it's a hard problem yeah i think it is a hard problem so basically you're giving only four cards and each cards contain a number from one to nine okay and you need to judge whether they could operate it basically if those you can combine make a formula right for those four cards that the result equals to 24. and you can either use multiply divide plus subtract or the parenthesis right basically you can just concatenate any of the two uh two string two numbers here right and uh okay so how should we approach this problem right i mean notice that here we have like this left and right parenthesis so what does that mean that means we can just use any sequence right so basically we can calculate any numbers any two numbers first and we don't have to worry about the sequence here because we have this left and right parentheses basically we can group any two numbers here right and we can do any of the any of these four operations here so then this problem will be converted to like a dfs search or backtracking right basically every time right every time we uh for this for each of the for each of this current cards here right we pick any of the two numbers basically we try all the combinations of the current cards right and then for each combinations we uh basically let's say for example if we have this let me increase this size a little bit so for example this four one and eight and seven right basically we first we try each of the combinations okay and for each of the combinations when i say combination i mean the uh i pick any of the two cards for this current list here and for each of the two cards i will also cop calculate all the com all the possible results between those two cards that will be a multiply divide plus and minors right and then among all those for each of the possible results right i'll get that result and then i will just append the remaining cards to that result and i will pass it to the next level of traverse of the uh to the next level of the calculation and i do it until uh recursively until uh there's only one card left in the current list and then the uh i compare when there's only one card left that's our final result right and then i just compare that final card result is just 24. if it's 24 then okay we see we find our find a solution otherwise false right so for example here so we have a basically we're going to have like a dfs method here right dfs and this is going to be our current cards right so let's say for example if we pick the four and one that'll be at the first time right then we're gonna have like try to get all the possible values between four and one so for four and one it's gonna be a four plus one that's one right and then four minus one right so for the plus there's only one value because one plus four and four plus one they have to have the same value but for the miners we're gonna have two four minus one and one minus four right four times one is the same right and for the divi division we also have two values right four divided by one and one divided by four right basically that's the at most we will have six at most we'll have six uh six possible values between those two values right between those two numbers and then for each of these numbers there we will basically this is going to be a five right three with uh negative three four zero point five for each of these values we're gonna append the rest of eight seven here right eight seven and so on so forth for each of those we'll make this one as a new card and then pass into the same dfs okay right with this one with this card the updated card we continue doing everything until we reach the there's only one card left right then we compare if the card left it's a is the 24. but remember here since we'll be having like this uh division here right so for example this one see 2 divided by 3 will have like 0.66667 3 will have like 0.66667 3 will have like 0.66667 indefinitely right and then in the end our final cards the answer may not be exactly equal to 24.000 right so 24.000 right so 24.000 right so since we have this division here we uh when we compare with 24 we're going to have like a above buffer basically we compare if the difference between 24 is within the range of 0.0001 is within the range of 0.0001 is within the range of 0.0001 right if that's the case then we are simply assuming okay it's almost 24 i know we are we treat it as the as a 24. yeah i think basically that's the basic idea here so let's go to the codings now so and like i said i'm going to have a dfs here actually you know for the things we're using the same numbers here we can just use the uh keep calling the function itself we don't have to define a new dfs method here right so let's just do a i'll just call this function uh by itself so uh like i said so for the we're going to have the numbers here right in the and then we track if the number is one right and then we see if the uh the nums zero right since there's only one left here my 24 okay so it could be bigger or smaller so that's why we have to need to do a absolute value so less than 0.001 0.001 0.001 right then we said okay this is true right else return false right okay so now if it's not one then we have to do the similar thing right we have to uh do a we have to pick up we have basically we need to find all the combinations right of the two numbers so we do a i in range n right to get all the combinations we do a nice for loop j in range i plus 1 to n okay now we have a card one and card two card one equals to the nums i right and car 2 equals to nums j so then what's going to be the possible results for this right like i said possible result equals to the uh c1 plus c2 okay c1 minus c2 minus c1 and then c1 multiplied by c2 right so the reason i don't do a division here is because either c1 or c2 could be zero and if that's the case we'll have like a divided by 0 exception that's why i simply do a simple check here if c1 is not empty right and then it's possible to a possible result then add the division result here and c2 divided by c1 okay and same thing if c2 is not empty do a possible result and c1 dot divided by c2 okay so now we have all the possible results we have in this of this current two cards right and then for each of the possible results here right we will pass that and a pa and we'll pass this result plus the remaining cards uh other than the uh other than these two cards to the next level of the dfs traverse okay so and i'm gonna do this okay so here you know i'm using uh i'm using like a new array here basically and let's see and or we can uh no or we can use our back tracking methods here right or i we can create a new array here let's try to use a backtracking here so basically what do we uh we remove it we remove those two eyes from the uh basically first we'll be removing those two now those two numbers from this num from these numbers right we do a nums uh dot remove right remove uh c1 and nums remove c2 okay and then we do a num start append right or pan we append the current value right and then um and then we pass this num the updated number to a dfs so basically if the dfs and the update numbers right if the updated number of dfs is true then we return true right if it's false we continue all right but since we are using like this is the uh we're going to try each of the possible possibilities here for each of the uh okay so i think here we can uh we can move this thing out right because this is for because for each of the for all the num the possible numbers here we're going to remove the c1 c2 anyway so that we can do this at the beginning of each for loop and here we just need to uh remove this numbers in the end basically pop okay because for each of the possible v numbers here uh once we process this number here uh we finished doing this for the next for loop we need to pop the previously result right because we want to try all the other possible numbers and since we're using the same numbers here that's why we need to pop it right and then okay so and then okay once this is done we're gonna need to add append c two and c one the sequence doesn't really matter c one c two okay because the next combinations we're going to have like different c1 c2 and we want for each of the loop here we want to make sure our the nums is a fresh start for each of the loop here right and then in the end we see if there's nothing there we should simply return false if none of those is true and if this is not true we simply return false in the end and okay i think that's let's try to run it yeah what i mean soft dots okay right let's see i think here yeah don't have a pop here missing a parenthesis here okay so this one accept it let's try to submit it false i see uh yeah i think i finally figured out what did i do wrong here because you guys see i do i remove these two numbers here right and then i append them into the end although the number are the same but since we're doing the looping here right we're looping it based on the index here once i remove them from the list right then when i try to add them back the sequence will be different right so i believe in this case a better way will be uh every time instead of like doing the uh remove it from the numbers and then try to add them back while keeping the same sequence we should create a new integer sorry we should create a new array to store those values here so basically every time right when we have a new values here we create the next card right next cards will be uh the first one will be always the v right and then here will be we'll be simply doing the uh if and then we will be will need to append the rest of the yeah basically here we need to append the rest of the numbers into this next card right so we simply do another uh if check we do another like a loop here chi in range k in range n here right if k is not it's not in inj right because uh we will i need to exclude those two numbers right and then for next card dot to uh to nums k all right and then here so and i can simply remove everything here i can remove the all those backtracking issues here so i simply every time i simply create a new element right and then first we append this thing and next we append the rest which is not just two numbers right and then we pass this next cards next around the cards into the function itself right and then let's try to run it oops okay not in all right let's try to submit it yeah so this time it works the past basically uh the main idea here is like do a real recap here a quick recap here and the main con idea here is since we have this left and right parenthesis we can basically simply pick any two numbers as our current operator and then we get the for those two numbers we get all the possible results from those two numbers and then for each of the possible numbers we'll also we'll be trying that possible numbers with the remaining numbers and we pass it into the this dfs method itself until when we reach the end we will compare the final result right so this is like the uh the graph sortings right backtracking or dfs whatever you want to call it and in the end basically we try all the uh the possible combinations for the two cards first and then for each two cards combination we try all the possible values and we keep doing it until we reach the end uh cool guys i think that's pretty much it is i want to talk about for this problem and i hope you guys enjoyed the video thank you so much for watching the video and see you guys soon bye | 24 Game | 24-game | You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted with the following rules:
* The division operator `'/'` represents real division, not integer division.
* For example, `4 / (1 - 2 / 3) = 4 / (1 / 3) = 12`.
* Every operation done is between two numbers. In particular, we cannot use `'-'` as a unary operator.
* For example, if `cards = [1, 1, 1, 1]`, the expression `"-1 - 1 - 1 - 1 "` is **not allowed**.
* You cannot concatenate numbers together
* For example, if `cards = [1, 2, 1, 2]`, the expression `"12 + 12 "` is not valid.
Return `true` if you can get such expression that evaluates to `24`, and `false` otherwise.
**Example 1:**
**Input:** cards = \[4,1,8,7\]
**Output:** true
**Explanation:** (8-4) \* (7-1) = 24
**Example 2:**
**Input:** cards = \[1,2,1,2\]
**Output:** false
**Constraints:**
* `cards.length == 4`
* `1 <= cards[i] <= 9` | null | Array,Math,Backtracking | Hard | null |
209 | Ajay to Pimpri channel highest and we do yaar medium size ok with me any question you are improve a curtain if understood then according to me you will not speak I consider safe nothing to do final minimum balance and one more and all his Let's subscribe all of them and do it in a good way by subscribing to us that whatever increase this information jewelery will get is good ok if minimum rating will be looted forces will be five inch target we have 512 will be proved then please subscribe and in this I will be your target Pipe, we have to do partnership, by taking everything, it is basically a religion, let me see it in the morning, with the help of which we live in private partnership, which one will be, then it is only with the help of 141 note 4, I am the palm super power, at this time, with the help of 140, the mosque is removed. 5751 morning, how do they live at this time, those who have more money, only who doesn't know, Congress, like Jasmine with more target in it, tell them this, I want to tell, Ooh, I will go this much, till Monday, just eight, this one will be fine. Even in the morning, the sum of the oath and decision is looted, I swear in the Kayan Tower, now I am one, all the waves of all of them are complete, today we are complete in Ghaghare Guftagu Me Sami Remix, then she will come after getting late to the office, 145 ki Chittor time 100 I and vegetables help solve some example issues less than 15 can I sama side so physical for you keep doing this all very rich depot a savage mother passed to pimplepoint is this manuscript minute system part or equal your pimples and uk The target is equal to the survey, there is no need to meet early in the morning, from that time, this type of phone number is to be taken early in the morning, 2 minutes, then I can achieve my target by inviting elements and I am the court to appear and time is goddess. So I give the answer, get meaning of father can become a laugh, so basically this is the question, you are not in the list, you have got the target, sources claim that Minimum Balance Observance, Oath, Equal have written in front of that now how will you answer this question if your Mind on Cassio should first take out all the time of all which wait and tell them the time of balance is equal to how deed then don't mute from them then I will ask him that if you directly only get the marriage done means only this simplex Method time, you follow simple steps that I took out this time, then we all time gas song in China, sign in the morning, its evening - Dainik Paltu, the in China, sign in the morning, its evening - Dainik Paltu, the in China, sign in the morning, its evening - Dainik Paltu, the target is that fort, 2100 Kumar, it would be good if you think in this way, then I will go to the office with my Khan Saheb. Like, if I talk only about the value extracting part, there are 24 elements from the flat, which exam is it in a little regiment, at this time, to extract its service, you will have to operate on inches to extract the maximum juice. On the districts, if I want to take out the entire time since it started, then it has all the rights from A to B A to Z. Secondly, a survey was done again, I have seen the latest from it, from A B C to D A B C D. This is bring that America now you can do this only 24 Americans who will be with behind like laghe rahe time re to bhi ek time behind 60-year old finished a survey and behind 60-year old finished a survey and behind 60-year old finished a survey and people start with different finished one morning In this video, if you see things in the morning, then you will see them, my friend, at the time of CID and discharge, it will be like this, the third speed, if you see the total, then you will have to install operations only to remove it in the morning, then your complexity will either The answer will be thank you depending on the instrumentation and if you are okay with the doctor at November and this much time life is the titans operation can't understand everything can be started at one point important it is okay to soak the question the complexity of your in it Neither does she go to the office, she clears the sugar till the end, looks at Sapoch for once on the occasion of Congress, okay, this is a simple process of recruitment system wise, if you know how to leave in the morning, then there is a little struggle, you can easily do the prank. You can be very pleased, he is the richest person in time. Okay, the operation that we should focus on is that due to time complexity, it is a little bit, let me stop for a while, keep making you a little who is there, whether it is chicken or a little bit, now to solve this a little bit. Si question you * Concerts like I Si question you * Concerts like I Si question you * Concerts like I came with lenses Makeup artist time will be in the first chu hai indexing forgive sequence first and its contents for its processes that in points I speak the quantum setting open that chancellor fruit doing starting Point and landing point will come and differentiate the part of the morning. Okay and you make available to take out the dead body of that part. If someone shares the situation then be careful because of the flour, Bill is going to fight, this is from your starting point to the last point. I can keep all the elements as they are, okay, you have the target, I have sent the file, looted 1/2 inch point, all your element looted 1/2 inch point, all your element looted 1/2 inch point, all your element parts which you are going to flatten will depend on the rain, the time of that rain and the relation of increase in which child service. Only in the cigarette and all the morning its all the morning this special minimum balance and in the morning so to do I make them that the chicken boiled and made what we have right now a place in 3D tiles will clean up okay now going to clean up Now it is not difficult to focus on that, so first of all we will add more of your end points where we will be from the point, we will add its value inside everything, then it will go to the maximum antique coin inside the districts and okay, now I will check. I will take it, now let's go, now the union is asking which lens's software saree pimples apun ka samyak ghan one, what is this part and the evening is the evening, it is done with the target, it does not go towards the same, which is the restaurant at that time. It makes a difference that even if the oath is taken, it is more than the target. Now if we do it with the society, then we do not do it. We simply make our pending point so and so. Now we have become like that rotting hormone. Till now we have been trying to conceive this canteen point. I will do it, I mean, I will get this person added, I will take care of it, but it would be 100, how much fun, now if you do 10 photos, then I have the dead bodies of these two elements lying in my room, or these two elements, I swear, Indore Element would come out. Which is five which is equal to my tablet, this means that neither is this my part of the year, from which I select two elements, it is Amazon that is differentiating it at that time, whose company is equal to the target. If the target goes then it can contact in my lineage then this first article will be able to minimum balance result will be in the morning or will it happen then taking your side we will find it out like if you talk I have many elements here and the starting point is mine Here it is and there is no end in points. I am typing how many elements are there at a quarter inch. If it is taken out then only number elements will be taken out. Internet Settings for Identification. 0.2 Please vote 517. Most of the 0.2 Please vote 517. Most of the 0.2 Please vote 517. Most of the starting point is in points - turning point is 8 - Will support - turning point is 8 - Will support - turning point is 8 - Will support comes and on Activa four are admitted in one 5 so end in point - 5 so end in point - 5 so end in point - Starting point Plus but my sub LED light comes out from it if reverse was the ending point and scientific and I want to extract elements from it that how many Sanskrit So I use this formula to calculate the element, so for example, I come to know that the value of the committee is that it is as big as the middle of the Taliban, then I calculated its length, then how will its length be calculated? Sanjay Bansal, put 10.1 10.02 plus be calculated? Sanjay Bansal, put 10.1 10.02 plus be calculated? Sanjay Bansal, put 10.1 10.02 plus one part - 02 14 This question which is loot till now, one part - 02 14 This question which is loot till now, one part - 02 14 This question which is loot till now, comeback response from family with hands, we will start within the minimum, which is all your violence against all, its minimum balance, Tata balance of all arguments, how many minutes of soil rough that when this thing of mine happens, na babi How do I get the time? Early in the morning means a lip subscribe. We fold it in our hands. To do so many degrees means we have to use it on time. And today we have to use it early in the morning. So we got it. Now do this. My all is that it is less than the target, which means that whatever side is 0.5 meters from the important point, it 0.5 meters from the important point, it 0.5 meters from the important point, it cannot be my answer. We will pizza through them slowly. Now let's push forward and move the adding point forward. If it is increased then I will add plus two here and there and the plant becomes 6. Let us update that the limit of this entire tank regiment within Assam has been reached. Now all this is done by Congressmen so that if it is more then its length is also its limit. If the time is not less than you, then do not be angry that after that, if you will mix the points in the sign in, it is a starting point of the interview, when the opposition gets the balance time, that now I have time, I will give it at the right time, but the phone I state minor school that at that time cricket in this country is less than the target then nothing will happen. Now let's push the ending point further and spend that on tempered glass. So I will update us. Follow me on this phone. So you It is available in the handle, the rally that will happen is automatically updated because according to which it is right, the time is still less than the target, it means whoever represents me on this, not the starting point in these points. Also like and invite to celebrate the answer. Let's take forward these points. When the opposition is this urgent, it is my half. As in and plus Ankita has become instead of ' As in and plus Ankita has become instead of ' As in and plus Ankita has become instead of ' sab mera lehar' target also in the file, sab mera lehar' target also in the file, sab mera lehar' target also in the file, it means when all If the elements of the target of the previous evening become equal to the elements of the target, then it may be his lunch. What should I do with the video? We will find out the length of this survey. If I do LED at this time, then these points are intact. Font size is the default font and expressed in these. Present for placement or that the opposition of the length of this survey is that till now the minimum was the highest, if I will not update it within myself, then now I feel sad when I give this thing that whenever I get time. If I take the element from behind as the turning point then force it forward and see in this book that it is possible for me that this size comes let me the Tiger Shroff and if we present a reminder of what time it is, then what will happen to our subjects. - Will be then what will happen to our subjects. - Will be then what will happen to our subjects. - Will be done 5 - Toe gift done 5 - Toe gift done 5 - Toe gift is the work in coordination until this papad time is not the same. While speaking help in the answer, college morning I am killing him one morning whose element's time which is the alarm's oath, what is the target, it is simple, it is equal to Of this survey is note do this does not happen early in the morning and subscribe to your point that the picture element of this survey is their contract is with nurses target which means it could be that which all this is my front part plus one drops in the morning -Will do it in the morning, plus one drops in the morning -Will do it in the morning, plus one drops in the morning -Will do it in the morning, even drinking water becomes difficult and will fight on time, now there is time, it is equal to my target and then this velvet city including the pilot that we take out lunch also is the end points and - Volume 12345 will not be subscribed. If and - Volume 12345 will not be subscribed. If and - Volume 12345 will not be subscribed. If you use the points then please subscribe. 15 - It is near the pump. If it is 15 - It is near the pump. If it is 15 - It is near the pump. If it is less than the target then this survey will be subscribing and sharing these points. There will be minimum balance till then. Everything is there first thing channel friends set pointer and that politician end in points grows on trees starting point is on witch will and yet time is there learn something and minimum do 500 minimum balance on jhal were integrated You set the spring meaning of the image, okay, after setting the waste, now remove it as pending point, always do this, kind of or NSS member, come, how many makers number is it, confirm chord and play the landing point, engaged in some serpent equal. Let's use it, first its value came in its time, when the changing season and sequence of phone numbers of intention, then now it breathes when I updated it physically, I took out some of the range of that day, the railway station, now from my heart, I will say if Which is my evening, I have increased it from the target, it is equal, so what we do is that we find out the length, so there is a way to remove the crease of their hands or not. Jhala | Minimum Size Subarray Sum | minimum-size-subarray-sum | Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`. | null | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 76,325,718,1776,2211,2329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.