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 |
---|---|---|---|---|---|---|---|---|
25 | So hi gas welcome tu code of our next question is reverse notes group of these so in the question I understand gas so the question is something like that we iron has a link list given HDK is given with integer value. Look here, a wait value is given. What do we have to do? Basically, we have to reverse the notes of this linked list in groups of 1, 2, 3, 4. If there is 5 then what do we do in the group of K like K Kya Hai Tu Hai then in the group of two if we reverse the notes of the linked list then like Van Tu Tha then these two will be reversed then 21 will become like this 34 If that is reversed then it will become 43 and five that is forward it will become gas because 5 of ours is not making any connections with anyone so what is five it will remain today it is okay let's see the next question. Look in the next example 1 2 3 4 5 tha and ke jo tha wo tha three hai dat mains ki what do we have to do in the group of three, we have to reverse the notes of the link list so like van tu three four five hai So three tu van is done but 45 look gas, they are not doing the reverse, we people, if it is not a multiple of three, the remaining notes are the notes of the link list, if it is not a multiple of three, then what are we given? Question. Look here if the number of notes is not a multiple of k let's leave out d notes in d and should remain in it then we have to leave it out then four five we have to leave it out We don't have to make it 54. We don't have to reverse these two notes. We have to leave it as it is. Well, I hope the question is clear to you. So let's see it. How will we solve it? Look, we have this link list. If I write its output, then we take lets of three, we take three, then what will be its output. We are in groups of three. Basically, what has to be done is to reverse the notes of the link list, then it will become 321, then what will happen here, it will become 654 and give these last two notes, they will remain as it is, which I told that if they are multiple. If it is not off, then what we have to do is to leave those notes as they are, so 78 will remain as it is, okay, let's discuss the solution. Okay, we had solved one question, gas, if you remember. So we had solved the question with swipe notes. We had solved this question and I think the hashtag Aate Video was ours. So, what should we do in this question, which I give a little bit of this question to many people. If we do, then in this question we were given a link list. What would we do in pairs? If we swipe the notes, it would become like Van Tu, what would it become? It would become 21. Like if it is 34, then what would that be? It used to be 43 and what would be 56, what would be five six, it would be 65, so we would have been reducing something like this in this question, so I would request you guys to gas this. Do watch the video because from this video it will be very easy for you to understand this question because what will we do? We will ask the same question here also, why will we do it because see if we do two pairs. So if we can swipe two notes, if we know two notes are 12, then I think we know how to make 123 into 321, so these symbols flow like that, so if you know 1, 2, When people see the solution, I understand that it will be more difficult for you that if you have to swipe three notes or if you have to reverse four notes, then it will not be too difficult for you, so this is my request that You guys watch it and give it an end to the video. If you continue this video, then okay gas. So see what we are doing in this. In the previous question, we will also do the reconstruction. Basically, we will write two notes here. I also understand that question to you guys, what would we do to the two notes, what would we do, we would swipe the end, and in the rest of the link list, we would make a recension call. What would we have done if we would have called the function from the register and what would have been the faith of our calculation? Our reduction would have been that if we could reduce these two, if we would swipe these two notes, then our calculation would be It used to be that all the remaining notes which were children of the link list, he would vice versa and return the head note to us. This was a government expectation that it was okay with a rickshaw, what should we do? We reverse these three notes, what will happen to the children in the notes, what will he do to the cake group, he will reverse our Lincoln and he to us It will return the head number of the link list, so our expectation from this question is that it is fine, our requests and expectations are this, so from here, the head number of the six note will be returned and what should we do? If we give 321, then we will basically find it in the next part of van, then which point of van is our head, then what will we do, head dot next equals to head dot next equation, here we will let's research function. This is our solution and from here, we will sign whatever return will be in head dot next, so this is the basic we will reduce, so let's see how we will do, so what we have to do on 1 2 3 is to reverse. The gas has to be reversed, I understand if it is not a big task for you because we are doing reverse through many videos, notes, link list, hashtag three, our video in which I told how we can reverse, this was four. There was our fourth video in which I had told that if you want to reverse then watch that video. If you people do not know how to reverse then see the first three notes. What will we do with the first notes here, I would rather give them using three, I would say. I mean, if we reverse the first notes, then we reverse the first notes and if we put recursive calls on the remaining notes, then how do we do the reverse? We take three pointers, the previous current and Next previous current and next previous will be null. Current will also be initially one and next will also be initially null. Okay then what would we have done, what was our flu, we would have first stored the next, the current dot next, this I would reverse. I am telling you how he used to do it. If you people are not able to understand this then you people need to watch the reverse video, then you people go and watch it from there, then we will do the equals tu previous end. If equals tu previous end. If equals tu previous end. If we had changed the previous and current, then the previous question would have become current and our current would have become next, then this gas would have been decreasing, our reversal link list is fine, so let's see, first of all what is the current? So what are we doing that we are storing it in next, current dot next, what will come in next, tu and our previous is null, then what will we do in current dot next question. Previous, this link from here will be broken, the next one of gas and van will now be pointing to the tap and then what will we do, we will change the previous and if we change the current then it will be previous. Now one will become one and current, now you have become previous, one has become current, what will you become in the next, which will be called , then three A will go in the next, , then three A will go in the next, , then three A will go in the next, then what will we do, = then what will we do, = then what will we do, = previous, then this note will break. If the one that is next to you is pointing to van, then we will do the same thing, if the free one is on the note, then our next will be four, the current one will be three, the previous one will be tu and this note will start pointing to it as three. Which is next and we will have a link list like this. Okay, so we will reduce this much, so see how many times we reduced it, what did we do at the time, we reversed the notes in the link list, so What are we doing? We are reducing the times. So in the previous question, when we are running the loop, when we are reversing our latest, we are running the loop until the count. What am I talking about? I am talking about the #8 video I am talking about the #8 video I am talking about the #8 video in which we are doing what the dream notes are doing in pairs because there was a foot and there was a foot in it. There are two notes, so we reduce the count till 2. What are we doing? We reduce the reverse one. But in this video, we will reduce the count till 2. Why would we because we have to reduce the count by three notes? If we have to reverse the three notes or if I should say the notes, then we will take a counter here, sign the count as zero and run the loop till our count is given, what will we do till then? We will reduce our reverse one, so the first three notes, we have reversed them and our next one, our next point is pointing to whom, it is pointing to four, so we will call our function solve. And here we will pass next. Here we will pass next and our expectation is that if he returns so many notes by swiping his foot vice then it will be less basic gauge. I hope it is clear to you. Okay. One more thing, what do we have to keep in mind here, like we have reduced so much and these three notes have been reversed and on this we have called Rockers and What will happen in the expectations that we have, who will we sign next in the van 654 and give 78 Well, in this, what will we have to take care of one thing, gas, one thing will have to be taken care of like this, look like 456 So this will reverse four five six. What do we have to do? Why not reverse 78? Why not because it is not a multiple of, so we have to keep in mind that these two notes are If it does not reverse, how will we take care of it? We will take care of it in such a way that if we find the size of this completely English, then what will be the size? And what do we do in every iteration? In every iteration, we will minize K from the size, so for example, if we reverse the initial three notes, we mined K from the size and then give these J notes. These three notes are what they are. If there is a reverse, then we will mine from here so that 8 - we will mine from here so that 8 - we will mine from here so that 8 - 6, whatever is there, you will be left, then what will become of our size, you, we will check that our size is ours, brother, if it is our size, then if you give us the lace. It has been done, so what do we do? We are simply returning from here, so it will be a simple flow because look, if the size is this less, then I have only these two notes left. Now we will return these two notes. If people do not want to reverse then we will not revise these two notes, from here we will simply return, then this will be less basic gauge, so for this, let me show you the code, I will try to understand you people from the code. So this is our code editor, gas, so look in it, we had a function of reverse group, in this we had head not given and we have an interior value, okay then what did we do in this, we took out the size, why the size? I took it out because I told that we have to take care of the last notes also that if those two notes are not reversed then we will have to find out its size, so look here, I created a function for the length of the link list and to find out the size. I understand you all know gas, take this pointer, we will keep on adding plus to the current and count and we will move forward one quarter each, what is the current, what will we get from this, we will get account A from this, okay so first of all we will What did people do? We found out the size of this linklist, then we called the function solve in which we passed head not end and give. What is the size of our size in English? So see this. Solved function is gas, so here the most initial check which I just told is that if the size we have at any point in time has become smaller then how has it become smaller then do n't do anything from here brother simply. Please return whatever has come, so we will return it from here. Okay, we have taken one count, then we will give the account like this, till now we have to reverse the notes, so we have this one here. We are reducing the count by giving less and this is reverse function gas and if you guys know this then I think you guys need to understand this is basically reverse reduction and in this we do what every time We are making the count plus because we have to reverse the initial notes, then here we are checking what is next, why do we do this because it can be We have 123 only three notes and when we reduce these, then our notes will look something like this: our notes will look something like this: our notes will look something like this: three, you van and our next point will be pointing to the tap, gas is our next point. If he is pointing to the tap, then we will have to check that our next point is somewhere. If he is pointing to the tap, then what is lacking for us has already happened. Now we do not want to do anything, so here Simply return the previous one, Aadar Vice, what to do, Aadar Vice, we will make recursive call, you are blind, the gas regulator is only in the call, we are passing next, why next, because the next point must be pointing to four, so from here We will do the next pass and see the gas here, we mine K from the size because look, once we have reversed what is there, I had told that what we will do in every iteration, we will take the K from the size. If we mined K then here we will do the size - key and we will receive it do the size - key and we will receive it do the size - key and we will receive it in which head dot next because look here it would have become 321 so it has become 321 in the van next we will sign it. If you want to do it then where is the van pointing then the head is finding the van so if head dot next man lo will receive it then whatever is less of ours will be done in the last we are returning the previous Question, this was the code of Gage and I hope it has been cleared, so look at Gage, there is something new in it, we are not doing much, we have done very little in it. Gas Swapna Notes is just here in these. The count is given below, there the account is given below, basically, we have not done this less, here we are just doing one extra thing, what are we doing, the length of the list is coming to an end from here. We are also passing such parameters like size and we are keeping in mind that the last notes are to be left as they are and we are not to reverse those two notes. So, here we just have to take care of it, the rest is a simple question, the question was there, the complete discussion of swipe notes, I hope it is clear to you guys, so let's submit it and let's talk about its time complexity. Regarding time, if we talk about a city, gas, then look at the time complexity, what will happen. Here, first of all, we are finding the length, so the time complexity in finding the length will be bigaf N, then bigf L. Will it help us in finding the length? We are calling the solve function from here, so the solve function will be called from here. Okay, how many times will this solve function be called? Gas, this solve function is the time of length bike. That call must be happening because from here we will only make calls by making the same number of notes as many groups as we have, we will have the same number of recognized calls from as many groups as we have. Here, only calls are being made due to the size of the bike, so if I If I write the time complexity here, then what will be the time less city? Big of N will be required to find the length. If we will make and Big of N/k recursive calls, then it will be we will make and Big of N/k recursive calls, then it will be we will make and Big of N/k recursive calls, then it will be this. People can simply say request n and space. If we talk about electricity then the space complexity will also be big of n/k then the space complexity will also be big of n/k then the space complexity will also be big of n/k because from here the space of reconnection strike will be coming to it because we are calling with rekus so big of n/. calling with rekus so big of n/. calling with rekus so big of n/. What is its space complexity and this is its time, so I hope the complete discussion must have been clear to you guys and if you guys have understood the question then string case, if you liked the video and if this question is clear to you guys. It has been cleared, please like this video and subscribe to the channel so that you do not miss any latest notification. I will meet you guys in the next video. In the next video, we will have to see one more question. On top of the link list. So I'll see you guys in the next video Thank You | 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 |
329 | Hey guys welcome back to my channel in this video we are going to solve longest increasing path in a matrix so what is given in this problem your admin has given a matrix of two end sizes and you have to find here longest increasing path so long What is this increasing path that if you go from one end to the other then the value of the second year should be gate from the first head, if so then what has increased to you then how long and how many likes can you get by doing this. It is the longest for the longest, what do you have to do, finalize and see whether it is okay to give and here it is given that you can face in four directions, right side, left side and donation side is okay, you can do it now. What will we do? We will understand through the example. Write here that you can remove any of the offerings. Right, there are only two possible ways for this oil. We can go, then in which section will we investigate? Okay, that too, we will see, it is not necessary that now it is increasing, no, we have to go and see, we will not do this, we will do it here, will we see from here, we will see the excel, we will see like, we will see this process, now you will go here, you will see that it is equal, I have not increased. If it is happening, then look ahead, what is the benefit of meeting someone in this year, if you go here and look, you will see here too, if it is laced, then you will turn off the laghvi from it, if you get relief from meeting like this, then how much will you pay for using it. Possible a boy like this is possible ok then you will look for it you will point for it you will look for this fort you will point for it you will look for it you will call the office for it you will look for it you will point for it then you will file for it you will fine for it People have signed up for this, will you side with me, if you finalize for sir, then you will see that for Vansh, you are getting the longest one, which is going to be the phone, then it is going to be a little longer, now we will see that we have to go here for the one. But how to get it, how can we finalize, here we are going to use data and we are going to use DP, okay why will we do day vs because you are looking at all the paths for one, you are going in the direction, whether it is Uday. Singh, you are seeing that if you go that way, how long can you get for that Ali, right now you are doing this, you are looking at a fort, for this we will use difficulty, we will go as far as possible. We can go and call his office, we will see the approach, although the film will understand how depression is using us, we will use DP, now why would Deepika do, while I am explaining, let me tell you at the same time why we are using it here again. There will be such a point, come, I will tell you why we should use it, okay, here we will put the same size as our matrix given, okay, now we will start from here, now what will we do for this, first this year we will make it difficult. Dad will follow no, it is just for this year, this is our 0021, we will click ok, whether he will do it in the next year or not depends on the fact that our cry will definitely happen, is it possible that he will see that we will see this Is his kind from whom he has come from whom has he checked ? Not much, why ? Not much, why ? Not much, why not you, we will see, neither will you go here, this value is possible, but this we will see, maybe this is a possible way upwards, but due to being less than six. It is less, so what will we do after seeing that for nine we will know that length was going to be its maximum, what will we do, how much net slow gas can we get from these sales, till now I have got only one, what will you two do, we will do something here. We will do it, we will put it here, see, you have got only this much language from this oil, if it sounds like Amitabh's, then we will not get it, then we will see, at this time, for Mittal, we will see where we can go here and we can go here. can go, we can go here and we can go here. Okay, so now everyone has gone towards the flower, it is less than this, it is not possible because it is less, not possible, it is not possible because it is less, its value is less, so it will come in increasing, it cannot go, hence it is not possible, it will go in it. No, now we will find out the diet left, see if this is less then this is also not possible, then for this we will give colloidal also, if this is not possible then the story of speaking is its own till the lines maximum, this one word is found, then we will fold it. We will go for four, we can go here, okay, we can't wait any longer, not possible, so now where will you go, towards nine, is this more than this, force 9 inches, this is more than this, right, I have you then. Now what should I do, there is a video for which you will call the force, you will go here for this, instead of going somewhere else, you will look for the ninth, for no, we have already seen it, by making it difficult, we had seen nine qualities, how long is it possible, there is one for this, etc. Karmas now. That's not enough, the world has got 911 and we are going to make it again, so how much is the longest maximum here on this path, then there is the flower here too, it will go here and there from the court, then the end creative skill will be done when the skill Develop and do this, how long can it be for this to stick, when this is seen, that is why it is less, this is also less here, this is also seen, this is waiting for the direction, not possible here, this is possible, our possible. It will not be possible here also because the value is in the first path, it is possible but its value is not greater than it, then it is possible, it is also possible below, it is possible for the back, so it will come out and what about us for the Come out, the shampoo will come out, after taking out maximum two, they will be the only ones, then what will we do, we have seen all the chuckles here, now we will give for this, now we will see the last six, it will be seen in this event of ours, this will remain from this side, we will write the fruits, now that is seen in the reaction now. The director will go towards making a note and if he calls for a refund, we have already done this for the line, we will check it in all the TVs, is it already for this year, will we take it from here for this longest and may not be the length, so is it okay? That is six went from Sunday, this one went from here to here, there will be two for that, otherwise for this, you will leave, the rat will go here, the request will go, if it is less then till now, therefore, you are maximum, so we will write here, now see, now you It is understood that if we use the diff, you should make the first call for it. Now what to do. There are Muslims all around him, he will call for that. Okay, he will also do so in this condition, when there is a liquidator, then in this direction, Shravan, this direction. In - This type of time, so it will Shravan, this direction. In - This type of time, so it will Shravan, this direction. In - This type of time, so it will take time, but it has been seen that there is no need to call in already because we have kept it upside down, that is why we had started in, so that we do not have to do it outside, for this we Okay, so we have got the quality award here, for this now we must have understood why we are using it here, then now let's come to how much we can decide for it, we can give the pillar from here when it Ca n't go because there is no equal increasing pass, now it can be said, can be put, but it is already done for both of us like we have done school, Naval here also you are his possible, here Bittu himself neither will be one nor will go here or here. Okay, now this is what you will do, you will see according to this opinion in action here till the style time, this will go for this, now this will go for this, so it will go, its already opened, okay here two And here itself it will become three-three, here two And here itself it will become three-three, here two And here itself it will become three-three, here there is life, it will go here for a bit, it cannot go here because it is absolutely, if it can go for a long time, it will go here, then the maximum here, this two will come out to be 213, but that's why There are three, it will be 314, then which of the two is more clever, here we will take four possible fabrics, that one is the one that can go, has the charm by playing, that's why there is one, but if there is one for this, then the person who wants to be mixed with 181 weeks is all those. In Devgan Maximum Meghnad, what will be the answer, then you have understood, use Sandeep, you do not have to call Banswara media, for this news is a pain and use this truth because we have to see for one sale and then for the next year. If it is possible, then we have to look for the tight one from the next one. Now we have passed the dough, what have we used, we have to use it and use the deputy, Deepika size is the same as the bean, what will we do here in medical science, let's come to this function. Now we will point the row and column of this, now main and we also get into the case of longest zero till then the alarms are there and DP, we have taken the matrix size of the same size here, now we will see for a cell, possible plunge steel is there in them. If Amazon will pass the maximum from then do the same for me. People who are looking for me in this path, after knowing the final of the maximum, now how much can be the longest pass from this point, it is giving us the dates. Okay, you can see by calling here. Will keep doing it for the year Come MLA Roka for that particular cell Total Road is a total problem and the organizer is a particular cell For that particular frill, this camera lens is fine to the maximum and now the maximum loyalty would have come out of them. Both BSP and BSP have taken the clothes out of which the maximum and ours will be in the blogspot, then finally you will tweet the alarms that I have raised. Now let's come to the main function of the address, the wart is drying up, so how long has it been, what will we do now with this lead. We will take the ore, okay, now in the country, what layers did we have yesterday and the comments in it, the total road, total column, row and column ID of Patil and show the vectors matrix, we have created Deputy General here and will give you Less is DP that now let us assume that in that particular cell also the maximum like is there, then whatever is there, we will check whether that JIJKLM fine has already been done, then its maximum light will be there, Warden. We will do it okay, otherwise what will we do in this, tell us whatever direction will come out of that particular, we will look for the direction, then we will look for all the directions, in which direction we will go, this will save you from your star of this which is organized now. What will you do with it, you will add it, okay, you will art that you can go in this path, here the direction has given us this, its next - I0 - Mall 101 i.e. it is towards the light, don't go towards the - I0 - Mall 101 i.e. it is towards the light, don't go towards the - I0 - Mall 101 i.e. it is towards the light, don't go towards the west, that is why it is kept okay. We will go to add it here and give it for an injection. Now we will call the next edifice. For whom will we mark this A? It depends on whether it is a possible path or not. If it is there, then its value is greater. It is not such that the next value will be less in that film. To call the day, we have to do it for the one whose gate is next, so here we will keep the condition that it is okay that we only want him here because ours, this is what should happen, period should be love because it feels like it should happen and on the table. Why value matrix will come, only then what will we do for the next year first, will we call gas, will we resign, why the alarms, that roll made for sesame will be long and we will take it here, I will call him, okay Now this is the maximum pass that we would have got, we will leave it in it, okay, now it has been seen that DPI is given, what are we going to do, whatever is the maximum pass, we will take it out and after doing plus one, I will add it, okay and the final Kumar Maximum. Part plus one, this hole will come out, we will make it medium, okay, do it there, that is our code, now what we do is turn it, let's submit for them, okay, the code has been submitted, thank you. | Longest Increasing Path in a Matrix | longest-increasing-path-in-a-matrix | Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1` | null | Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization | Hard | null |
1,286 | hey everybody this is larry this is me going over day 14 of the november league daily challenge hit the like button to subscribe and join me in discord let me know what you how you know how you've been doing in november so far two weeks in almost halfway there and let's get started today's problem is iterated for combination okay so iterators um what are we doing okay so we have sorted distinct lowercase letters okay um the next combination okay so there are a couple of things you can do here i think if you want to cheat and i think i've done this in the past you just generate all combinations prior and then just you know and then just go and of course this in python specifically there's a library function for this um combination which one is combination again uh combination length okay so um how do we want to think about this right the idea is that we have a length and then we just basically keep track of counters and then we keep going as much as we can i think that should be okay um yeah i mean i think that's the idea right and then has next and next we just go to the next one um and we can kind of break it down one by one uh what are the constraints are 15 so we should be okay and only 10 to the fourth at most um but yeah but basically you would do something like you know the way that you would think about it if you had to do it manually or not manually but just like in general is you have the idea of okay you have maybe indexes oops is you go to something of length combination length and then you start at you know 0 1 2 and then you increment the 2 to 3 and so forth and then up all the way up to the last one and then you increment the next one it's a combination so all the numbers are the same but yeah but then in here we will go yeah so let's just say self.jars as you yeah so let's just say self.jars as you yeah so let's just say self.jars as you go to characters and as you go to the length of that charge so then here we start with and this is already sorted so we only won um x for x in range of combination length and a list of this right so what this is saying is that it's going to have for example it's going to start 0 1 2 and then it goes to and ideally we do something like this where we go to 0 1 3 we go to 0 1 4 dot all the way right um yeah and there are just a lot of bookkeeping i mean so the way that i would normally generate oil combination honestly is by recursively but here maybe it's a fun exercise for me to kind of figure out um how to do it not recursively relatively which i haven't done in a while i mean it's not shouldn't be that bad but yeah keeping in mind that in this case for combinations um for every i j k i is less than j less than k right so i think that will make it okay so then we basically increment the last number that we can and then once that goes over we increment the number before that um and then yeah and then we start that one with i minus one something like that um let's play around with that i think it's a big potential to get off by one but that's basically the way that would do it um and then this goes to at some point two three um after this is o of zero one um n maybe or n minus one maybe um and then this goes to zero to four and then increment all the way through um we just have to make sure that we have enough numbers and i guess that's it okay let's play around with that and let's get started um let's see has next we always have has next unless um the first index is already like you know basically you have essentially uh the last number is gonna be n minus one the second last number is going to be n minus 2 dot all the way to n minus i for some i that is uh the length of the thing right um so basically we turn off the indices the first element if that is equal to um if that is equal to n minus one uh n sub dot n minus length of self.index c n sub dot n minus length of self.index c n sub dot n minus length of self.index c something like this i may be off by one here let me think about it for a second um but basically if that's not the case we can always increment somewhere right uh yeah okay i think we're okay here maybe we'll see if that's true uh at least for now let's see if indexes have zero element then this should start zero minus one so i think we're off by one okay that's an easy check um to see if indices has one element what happens right when the c has one element then this element should be n by minus one actually no i think that was right oops okay so then now we do the next one which means that we look at the last element and then we increment right so index is equal to uh the last element right let's just say indexes you go this is more pythonic i don't really know that i'm a fan of this but uh so yeah self.indexes self.indexes self.indexes of index we increment by one if and we make we're going to change this to while loops in a second but i'm just working this through if this is equal to sub dot n and the last one is going to be -1 going to be -1 going to be -1 so this is plus index which is actually really awkward to say but um if this is the truth then we inc um in this case we actually go more to the left so we subtract one um and we also in this case we set my neighbors are singing very loudly but um okay how do we think about this way then we think okay let's increment the number to the left um and then get this number later what is this number what is the current number right well we can maybe just do a helper function instead let's actually do it that way maybe i will do a recursive i mean it's recursive but it's more stack based you can think about it as a stack versus uh the iterative version but yeah um so let's just say increment um the last element so let's actually yeah so increment negative one for the last element uh do we want to do it this way let's see and let's just do n by one uh oops sub dot n minus one um and of course we will define increment here so now we have this thing but of course this map is a little bit different now we have if this is the worst then we have to get the last um if this is the end or if this is not the end we let's see uh what is the n mean um if the index is equal itself okay so uh is the code two sub.n minus length of is the code two sub.n minus length of is the code two sub.n minus length of something like this well maybe i'll buy one again but yeah if this is the biggest number oh sorry this is this minus index right because if index is no because this is um this going backwards thing is kind of mixing me up a little bit to be honest uh maybe i need more sleep but that's besides the point okay so we don't fix this index so then this is going to give us one okay so i think this is the case actually right because under if no this is only the case so i think one thing i'm mixing a little bit is this the length of this and n i think that's why so we want it to be the same okay so self that ends minus of the index that's the places from the end if this is equal to um so we add that by so this is this minus the length of self dot indexes right so that means that we're at the last element this will be negative one and this would also be the length of the last index okay uh i just have to say it out loud so this is the case we want to get the index uh or we want to get the value from in incrementing the minus one um basically we're going to look at the previous value and then solve that indexes of index is equal to r plus one right um and i think we're good here maybe yeah i think we may be good here uh we have to add a base case of course so if index is equal to zero then uh or if okay so let's say we're passing the zero f limit well this cannot be the case unless we don't have it has next so we should be okay um so okay so because this cannot be the case if it does not have a has next so otherwise we just oh i guess this is it because we already did the increment in here um and then now that we have all the indexes we want to um return the element of co i think one thing that i might be a little bit off is though is that okay so just get incremented afterwards but we actually want the value of it now um we might as a result have this recursion finger where um we'll see if index is equal to negative one then we have no more values so we can just return maybe we turn negative once say oh no that's gonna be bad so um yeah okay maybe i just write something like if self dot has next we increment um so then we could get rid of this okay uh otherwise the value is go to um solve.choice solve.choice solve.choice so we want to join the array that is made by um in sub.indexes something like this in sub.indexes something like this in sub.indexes something like this and then of course we return value at the end okay let's give it a spin i'm not confident about it yet a lot of potential typos but that's okay uh okay oh because i do self.n minus one instead oh because i do self.n minus one instead oh because i do self.n minus one instead of um what we want is actually the length of uh i've been mixing the two numbers a bit the n and the indexes and that's why i've been confusing for me but uh but yeah um okay let's see why that is so okay so 0 1 0 2 zero three so i guess i this is not triggering correctly somewhere um because we have three so this goes to zero three somehow but we are incrementing the last number correctly so this is just not going um so okay maybe i'm off by one let's see if index is the last element then this would be negative one and this would be two let's just see if we go here not sure that we do so that means that we don't go here that means that this if statement is off um and it is so i think one thing that i think i did this math based off um based off not incrementing so i guess i have to do this first um there you go uh okay still wrong that's awkward so the length of this so this would go to the second index which is or one in this case so this is one minus um i think this is well i like i said i keep mixing the ends so this is i think i mixed this up yeah i think this should be self dot n minus the length of yeah okay keep on mixing these two i've been really bad about it um but yeah okay so we're good here we just have to return this value which we never did actually so that's why this is awkward um yeah okay so this um that's not accurate no actually it is right 0 1 zero two one two right so why are we wrong here we're wrong because okay so i think what we're doing in incrementation is correct but i think our has nexus is off by or i don't know i mean it's clearly that we uh off by something in somewhere so um has next is true right maybe i'm off on here as well do i have to print him in the other place no so next why is this printing so many times oh because i would call hassnex here as well um okay that's fair hmm might just solve by one this really should be returning true if this is one um if the first element is one and we want this to be uh yeah we want this to be one and n minus this one it should be okay so if this is not and then we have an x right am i missing mixing something up here so okay so this is returning force accurately but why am i returning force on ac or after ac right oh because after ac we increment it um so we're lagging one behind because we increment it and then now that we increment it that has next is whether we can do it again okay so maybe i have to think about it in a different way um so where so has next is okay so this should give us the delay effect uh maybe not uh so this returns oh because this is a chicken and egg thing i have to adjust this here um this is very awkward now to be honest but it looks a little bit better uh let's see if we can do this but for three this is a very awkward interface so i might not test that much because i don't know this is just awkward to write so i added five things if this isn't if i have mix up something i'm not going to do it okay method should be a string away oh oops okay so that looks good so let's give it a submit hopefully this is okay um yep cool uh i think the last few times i did just prove force to be honest and just did it very quickly this time i kind of re proved it from first principles um i don't have this memorized because if i did this would not take so long but also you know it's just about thinking of through what how to represent this and then implementing it which i was a little bit slow about maybe this is a good warm-up for the contest soon i need good warm-up for the contest soon i need good warm-up for the contest soon i need to go grab food but yeah let me know what you think um so this is gonna be you know this is gonna uh this is roughly speaking n times x uh where x is the number of output note that i mean there are some amortizations you can do in math with knowing with respect to combination because map and combinations but that said i'm just lazy right now so we call this end time d or we call this x times and each time it's going to take o of l um operations where that is the number of length um and here this is our one but and yeah and we when we use linear space of course um but yeah but that's pretty much all i have for this one let me know what you think um hit the like button hit the subscribe button join me on discord uh let me know how you did and all that other stuff um cool yeah i will see you later stay good stay healthy take your mental health and take care bye | Iterator for Combination | constrained-subsequence-sum | Design the `CombinationIterator` class:
* `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments.
* `next()` Returns the next combination of length `combinationLength` in **lexicographical order**.
* `hasNext()` Returns `true` if and only if there exists a next combination.
**Example 1:**
**Input**
\[ "CombinationIterator ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[ "abc ", 2\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, "ab ", true, "ac ", true, "bc ", false\]
**Explanation**
CombinationIterator itr = new CombinationIterator( "abc ", 2);
itr.next(); // return "ab "
itr.hasNext(); // return True
itr.next(); // return "ac "
itr.hasNext(); // return True
itr.next(); // return "bc "
itr.hasNext(); // return False
**Constraints:**
* `1 <= combinationLength <= characters.length <= 15`
* All the characters of `characters` are **unique**.
* At most `104` calls will be made to `next` and `hasNext`.
* It is guaranteed that all calls of the function `next` are valid. | Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp. | Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue | Hard | null |
1,576 | uh hey everybody this is larry this is me going uh over q1 of the weekly contest 205 replays all question marks to avoid consecutive repeating characters so this one um this one's a little bit tricky it's brute force in a way but it's um it's a tricky way to do brute force but um the way that i did my code is a little ugly and actually to be honest this is probably the problem that i had the most uh trouble with relatively on this uh contest but my idea was that okay so let's say you have um and i was worried about getting wa during the contest so definitely something to think about uh but let's say like you know at the worst case you could have three question marks right but and what does that mean right that means that each question mark has only two neighbors or just previous and the next right which is obvious but what that means as well as the next step is that well that means that at first with the pitch in the whole principle or whatever you want to call it that means that this could at most be a or let's say and i chose a greedy weight right just so you use a b and c but you could do it with any number of characters but let's say in this case but if this is a this is b then this has to be c right and that's pretty much the concept that i use to solve this problem uh because based off this uh everything else uh yeah because okay if this if one of these is a then this otherwise and this is anything else uh then you just use b and so forth so that's kind of my concept here is that you only have to brute force over using three characters a b and c because at worst you're just going to need a third character um and that's kind of how i uh wrote my code here um i and this is linear time because you know we look at each uh character once but if it's a question mark i look at the previous one to see if then a if the one of them is an a we look at to see if any of the previous ones are b if they're if we're here oops if we're here that means that if a and a b exist so we add a c otherwise we add a b otherwise we just add an a and then if it's not a question mark just add the character because you have to and that's pretty much how i solve this form uh i struggle a little bit with this and also because i got some if statements incorrectly but uh but definitely let me know what you think uh hit the like button to subscribe button and you can watch me stop it live right about now hmm um okay um hmm that's not good oh oops okay what oh this is hmm that was a slow one uh hey everybody uh yeah thanks for watching uh this explanation of this video definitely give me feedback uh ask questions uh because the more questions you ask more feedback you give me then it lets me know what how you know what kind of answer to uh give you for next problems right and so you know i'm trying to learn from this so yeah hit the like button to subscribe and join me in discord and i will see y'all next contest bye | Replace All ?'s to Avoid Consecutive Repeating Characters | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters.
It is **guaranteed** that there are no consecutive repeating characters in the given string **except** for `'?'`.
Return _the final string after all the conversions (possibly zero) have been made_. If there is more than one solution, return **any of them**. It can be shown that an answer is always possible with the given constraints.
**Example 1:**
**Input:** s = "?zs "
**Output:** "azs "
**Explanation:** There are 25 solutions for this problem. From "azs " to "yzs ", all are valid. Only "z " is an invalid modification as the string will consist of consecutive repeating characters in "zzs ".
**Example 2:**
**Input:** s = "ubv?w "
**Output:** "ubvaw "
**Explanation:** There are 24 solutions for this problem. Only "v " and "w " are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw " and "ubvww ".
**Constraints:**
* `1 <= s.length <= 100`
* `s` consist of lowercase English letters and `'?'`. | Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge. | Depth-First Search,Breadth-First Search,Graph | Medium | null |
1,696 | hello everyone welcome to quartus camp we are at ninth day of june eco challenge and the problem we are going to cover in this video is jump game six so already we have solved jump games seven and two in our channel you can check the links in my description and this problem is again very similar to jump game seven we have already solved so as like any other jump game problems the input given here is also an integer array and an integer variable k so now we have to start from the zeroth index and reach the last index of the array and the maximum steps you can take is k so here the score is nothing but the value in the array wherever you land so we have to return the maximum score we can get and there is another rule given here is we have to land in exactly at the last position we should not exceed the last position while we are stepping into our last step so let's understand this problem with an example so here is a given input array we have to start from the 0th index where the value is 1 so we are adding 1 to our result so now we have two options either we can land on the first step that is first index or the second index directly so now if you calculate the first index with one it is going to be becoming 0 because it is a minus 1 but if you add the second index with 1 it is going to become minus 1 which the less the value so we are planning to land on our first step so in that case our value is going to become 0 so now from the first step you again have options to land on four or minus seven so let us consider we are landing on four because minus seven is a lesser value so adding four to our result will make it four again so now from four you i again have two options either to land on minus seven and three so which will increase our value if suppose we are landing on minus seven it is again gonna go in negative answer and from minus seven if you land on three it is again going to stay negative but if you directly land from four to directly to the last index then we have to add plus three to our score so overall score is going to become 7 and that is going to be our output so here how are we going to approach this so as we have solved jump case 7 we are again going to implement the same logic a simple bfs trick in order to arrive at our solution so we are going to maintain a priority queue and our priority queue is going to hold the score so far and whichever is maximum to proceed first that is we are going to start from the index 0 and we're going to reach the index 5 so now to reach 5 we need a maximum score so we are going to try out all possible positions where and all we can land and pick the ones with maximum score starting from the zeroth index our priority queue is gonna hold an integer array where the integer array is gonna have the score so far and the index we landed obviously the first score is going to be one as we are taking the zeroth index so now we have two options to land that is from first to first index as well as the second index so we are going to add both the scores here this course is going to become 0 comma 1 and minus 1 comma 2 because we are adding with 1 then we are going to put 0 comma 1 first because that is the maximum score out of both and we are going to first explore from that path and then move on to the lesser score path so the lesser score is landing on index 2 will give you minus 1 comma 2 now we have reached to the we are iterating the given in array and we have done with two indexes and now we are at the third index here the maximum position we can reach from zeroth index is going to be two because we can reach maximum of only two steps so in that case we don't have any connect from the zeroth index to third index so we no longer cannot reach any other positions from zeroth index in that case we don't need this one comma zero anymore in our priority queue so we are popping that from our cube so moving on to our next one which is in our queue which is zero comma one so from zero comma one the possible positions you can land is index two as well as index three so if you are reaching to index 2 then you will be adding minus 2 to our current score which is 0 minus 2 so the score is minus 2 comma index 2 or we can land at index 3 so the current score is 0 adding the score at 3 is 4 so this is going to become 4 comma 3 so out of these 2 the highest score is for 4 comma 3 so we are going to put that first to a priority queue and then minus 2 comma 2 will be entered because we are going to pick the highest score once first and then explore that path first so now this is it from 1 you can maximum reach is index 3 so we are moved to index 4 so we no longer need 0 comma 1 so next comes minus 1 comma 2 from minus 1 comma 2 that is from index 2 you have again 2 more options to land at index 3 as well as index 4. so now adding the scores and adding them to a priority queue will become so yes we can land to index 3 and 4 and the scores are 2 and minus 9 we again no longer need minus 1 comma 2 so let's move on to 4 comma 3 from 4 comma 3 that is from index 3 you can either land on index 4 or index 5. so now adding the scores of minus 7 and 3 with the current score of 4 then it is going to become yes from index 3 we can land at index 4 and 5 and adding this course would give you minus 3 comma 4 and 7 comma 5 which is actually the maximum score so far and we have a maximum variable to keep track of these scores at index 0 every time we update with the new score and it is going to keep track of the maximum score so far and that is 7 till now and we are not yet done we are going to still explore all the paths and pop out everything from our queue till we explore and add all possible scores from the given array and we are going to add every possible score and explore every possible path till our priority queue becomes empty so once it is empty what is left here in the maximum score is going to be returned as our output so this is it hope you are understanding the solution so this is actually going to work in big o of n time as this is a simple bfs and gonna explore the given array so yes let's go to the code now so yes as i said we need a queue which is gonna hold the integer array and we are writing a comparator that sort the values based on the score given so we are going to store score in our zeroth index and index in our second index so we just gonna sort based on the scores we add so we have added the first index value and 0 as we are starting from the 0th index to our queue so we generally define a variable with 0 but since this have a negative values we are assigning the first index value as the maximum score as we have already added the zeroth index value to our priority queue we are going to start from our first index and as i said if we no longer can reach to a position from some position then we are going to pop that from our queue and i am going to declare an integer array current which is going to hold the top element in the queue and we are going to calculate this core we are directly adding it to max because we have sorted our q based on the maximum value or the maximum score so whatever in the top is going to be added to the current of 0 plus the current value of our numsery and we are going to put that back to our q and once all the iteration is completed our max variable is going to have our result so yes this is it let's run and try so yes we need to check the index that is from one with where we have stored the indexes of the places we land we are checking whether we no longer can jump from that position then we are popping it so let's run and try now yes so let's submit yes the solution is accepted and runs in 142 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you | Jump Game VI | strange-printer-ii | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104` | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? | Array,Graph,Topological Sort,Matrix | Hard | 664 |
37 | hi everyone welcome back again one more session today we are going to discuss my favorite problem with it code number 37 solver so this is the sudoku server is one of the very famous everybody knows what is sudoku what's the game and how we to play it and solve it today we are going to solve this sudoku problem with the programmatically so let's go ahead and start the program write a program to solve the pseudo computer by filling up the empty cells so a sudoku solution must satisfy all of the following rules each of the digital one two niner must occur exactly once in a row and each the second condition is each of the g's equal to nine must occur exactly once in a column third one is each of the digit one two nine must occur exactly once in each of the nine three by three sub boxes of the grid so if you see what he is trying to say that if we take any number that should present only once in a row and second rule is it should present only in once in a column third one is it if we see that you have it these are the three by three boxes one two three boxes four box fifth box sixth box seventh box eight the box and ninth box so each number should present only once in this inside the boxes that is the that is what the sudoku solver so now and one more condition is like the empty cell how to find out the empty cell empty cells are indicated by a character dot so that wherever we found the dot we have to fill that each and every sin by following and these three rules let's go ahead and solve this problem so the input is the characters each and every cell is indicating the character so it's a board so the sudoku board is a character board so but this is a boundary condition if it is null and if it is not nine the rows and columns should be nine by nine matrix if it is non-norton and banana matrix and we are non-norton and banana matrix and we are non-norton and banana matrix and we are simply returning from it we are not going to do anything proceeding so if not then let's go ahead and solve the sudoku with the helper so first here what i'm going to do i'm going to take each and every cell from that to 9x9 matrix so i as i know it's an unbenign matrix so that it's a uh for i equal to 0 is less than an i plus and uh it's a row and it's a column j is equal to 0 to 9 and wherever i found the character empty that whatever we know that the empty cell which indicates a character so that if it dot wherever i found the dot that indicates there is no number in that cell and i'm trying to find out what number i have to fill it from 1 to 9 what number i have to fill in that empty cell so what i'm going to do i'm going to take each and every character and now i'm going to upload these three rules on that cell so that some number will fit into them so that yeah one to nine is valid so that i am writing some other method so that you know to find out whether this uh the one that the first number one is a correct number for a given row and column row i and column j so i'm functioning all these inputs as part of this method so that i is the row under j is the column and k is the target number and the board is our sudoku board so what i'm going to do is whatever the given target which is which satisfies all the three given conditions then i will go and add that number into the board and i will repeat this process since i'm using the back tracking mechanism here i'm going to repeat this process again and again for each and every seller recursively so i'll call other in the same method recursively to find out and um if it is true you then written the true that means i found out the number that given so that this studio board is a valley board so i written that true once you completed everything that returned back that back to the dot so that you know like we don't want to miss the board so it's a written back to the dot there okay so let's go ahead and see the is valid method what we are doing here each valid so this is where actually i'm going to do that you know like check the row and the column so that is 0 to 9 let's check the um if for example the target is a 1 at the number 1 here so that if that number 1 is a present in that row and the column then we are i'm not i'm going to written that false so that the one is not a valid number to fill in that cell so for that i'm going to check all the rows and uh column a particular the given row number and the column number i'm going to find out is the number is already present if it is already present and then written false so and the second so with this loop uh the rule number one and two we are validating rule number three is this is the three by three sub matrix with this three by three sub matrix i have to find out that number is already present or not if it is already present written false else written true so here you see how to find out the uh inside the cell row one column so here is the formula that to find out the inside gravity matrix i 0 and j 0 to 3 by 3 matrix and to find out the new x and y is the inside the 3x3 matrix the row number and the column number so that is a row by 3 into 3 plus i and a column by 3 into 3 plus j for example it says 0 so that 0 by 3 0 into 3 0 plus i 0 same thing here also the column is 0 3 0 and into 3 0 plus 0 so 0 the first one is 0 is equal to target written like that it will you know like it will repeat the loop on a particular given three by three matrix will find all the wrong column dark it finds it returns false otherwise it returns the true so like that we will find out whether the given row and the column under target whether this the given number is a fit or not if it fits then it will return to otherwise it returns the false so like this we can solve the pseudo problem here let's go ahead and run this program perfect so that this is what expected and this is what output we gave this output and this is what we expected and thank you for watching | Sudoku Solver | sudoku-solver | Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid.
The `'.'` character indicates empty cells.
**Example 1:**
**Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\]
**Explanation:** The input board is shown above and the only valid solution is shown below:
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit or `'.'`.
* It is **guaranteed** that the input board has only one solution. | null | Array,Backtracking,Matrix | Hard | 36,1022 |
124 | a legal problem called binary maximum half sum so path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them a node can only appear in a sequence at most once note that the path does not need to pass through the root the past sum of a path is the sum of nodes values in the path given the roots of a binary tree return the maximum path sum of any path so you can see that we don't have to pass through the roots and that basically means that we don't have this the path doesn't have to start at the root and the path doesn't have to end at the leaf node right like if i have a binary tree like this can be one path right or in this case this can also be at one path right if this is if this has another node right has another children node in this case this can also be a one path as well right it doesn't have to start at the root doesn't have to end at a leaf node um and you can also see that this can also be a path as well right and this path have to be one directional basically means that you can only go one path like go like one direction um you cannot be like this for example like this right like coming back to here this is not one direction you can see this is basically two paths right um so in this case we're basically trying to find the maximum path sum so you can see we have the example here and uh in this case we have a maximum sum of six so we have two plus one plus three we can try with one plus two or one plus three right but they will only give you um not the maximum sum right um another example like this for example um you can see we can the maximum path of sum is 15 plus 20 plus 7. um in this case this will give us 42 right you can also try with negative 10 plus 20 plus 15 or negative 10 plus 20 plus 7 right there's many combinations that we have um so you can see the maximum is basically 72 right oh sorry a 42. so you can see the constraints that we have at least one node in our tree and the constraints that we can also have negative values in our nodes right so how can we solve this problem well this problem i think is very important to come up with all the combinations that we can come up with right so you can see that for this subtract let's say we're talking about this subtree right here right 20. um what are some combinations that we can try like what's like how can we figure out what's the maximum path sum for the current subtree okay well we can do is we can say one path could be the parent plus the current node's value plus the laptop tree right plus the maximum power for the left subtree of course right uh so that will be parents to the current nodes plus the left subtree and we can also do parent plus the current nodes plus the right sub tree we can also do is we can do this right we can do left half sum plus the kernel's value plus the right path sum and we can also do is we can just go for current those values plus the left path sum right or the kernel's value plus the right path sum or just current notes value itself right so you can see that we cannot can be able to come up with six combinations and for each and every single combination we get a sum um and we figure out who has the largest value whoever has the largest value will be the maximum half song for the current uh for the current position right um but the thing is you can see that this is really unnecessary right you can see those two are really unnecessary because we're just trying to figure out the maximum power sum for the current subtree right and then we can try to go from the bottom to the top and working our way up and we don't have to really figure out okay who what's the maximum half sum for the parents you know try with all those two combinations because we will every at the end we return back to the parents say the maximum power sum for the current sub tree is this and then in this case for the root level right we know that the maximum half sum is nine the maximum half sum is 35 right and then we can try with same thing we can try with all four remaining combinations right we can either try this way we can either try just this path or just current those values itself right so you can see that we're only left with four combinations now and you can see that those four combinations can also sum them together into one right you can because in this case like i mentioned before this is returning 9 this is returning 20 right so you can see that we can have 9 plus negative 10 plus 20 right but in this case this will always give us the maximum value right if i just say negative 10 plus 9 this will not give us the maximum value but the thing is that there could be also negative value as well right if i have negative 20 here right if i have a negative forget about this subtree right here right in this case if i just have negative 20 return back to the root right i don't want to include this because in this case it will always bring the sum right the value of the sum down right so what we can do is that if i'm returning back to the root um i will compare to see whoever has the maximum value either zero or the maximum value right zero basically means i'm not including the sum the maximum half sum for the right subtree right and same thing for the right of sorry for the left in this case i can in this case include zero or sorry include the left half sum or just don't include it which is basically zero right so you can see that these are four combinations is either um the current nodes value itself right if both of them are negative value then i'm not including any path so that's one combination or if one of them is bigger for example it's nine is bigger than zero so we including the left subtree right or in this case for the right subtree if in this case if um right if this is positive value and this is negative value then we're only including right subtree right and there could also be a situation where both of them are positive if both of them positive we're including both subtree right so you can see those are all four combinations that we have to try right and at the end for each and every single subtree right we have to compare who has the maximum half sum so we're gonna have a maximum variable that keep track of the maximum power sum uh throughout the bottom right so we let's run through an example here so for this subtree we know that the left is in the right is zero so in this case the maximum power sum is 15. so we're going to update the maximum half sum to from infinity from negative infinity right to positive 15 right and same thing here we know the seven the maximum half sum is seven is not bigger than maximum value so in this case we're not going to update a max so we return back to the parent say the maximum path sum is this value right so in this case what's going to happen is that for this uh node we will try to figure out the maximum path sound for the current subtree and then we will make sure to update that for the max right so the maximum half sum for the current subtree um is in this case is 15 plus 20 plus seven right which is basically 42 so we make sure we update the maximum half sum because it's bigger than the max right okay so then uh we're going to return back to the root saying the maximum path sum for this subtree is basically 35 because like i said again we cannot include this is basically one directional like we cannot do this we can only return just the maximum half sum for one branch right it's either this one right or is either this one right so in this case we're returning 35 because we have 15 plus 20 plus right which is basically 35 and then for the left subtree which kind of obvious we're returning zero uh nine because this case is a leaf node and this is basically the maximum path sum is just this node itself which is nine so in this case we have 9 plus 35 and they're all positive value right so in this case we're including both 9 plus 35 which is basically 44 right so we have 44 but we have negative 10 here right so in this case if i have negative 10 it's basically 44 minus 10 which is just 34 and this maximum half sum is 34 right so you can see that we cannot just like um ignore the left path or the right path because they're all positive value they're all bigger than zero so if it's bigger than zero we must include the path sum for that path right so you can see that this is basically how we solve the problem using um kind of like a post-order using um kind of like a post-order using um kind of like a post-order traversal we want to know the left subtrees path on the right subtree path sum then we'd be able to compare or understand what's the maximum path sum for the current subtree and then we're going to return the maximum path sum for this branch back to the root and to make a different decision right so you can see this is our code we have a maximum variable um to keep track of the maximum path sum based cases that if the root is null we just return zero right so if leaf node if the left is null the right is null then we basically return zero for left max and the right max right and you can see the left max in this case we're doing a dfs to search on the left if it's negative value we just don't include it right we just don't include it in our path sum to calculate our path sum right we just set it to zero and same thing for the right now we update the max in this case the max is either max itself right or it's just left map left max plus the right max plus the root of value right at the end we're returning one branch just like i mentioned before um is either right this right or this right it's either the right subtree oh sorry is either the right subtree plus the kernel's value or the left subtree plus the cardinals value right so you can see that we're insured in just only one directional right not like this right so that's how we basically solve the problem and you can see the time complexity whoops sorry the time complexity is basically big o of n where n is number of nodes that we have in our tree and the height is basically the space complexity so there you have it and thank you for watching | Binary Tree Maximum Path Sum | binary-tree-maximum-path-sum | A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root.
The **path sum** of a path is the sum of the node's values in the path.
Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 6
**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
**Example 2:**
**Input:** root = \[-10,9,20,null,null,15,7\]
**Output:** 42
**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3 * 104]`.
* `-1000 <= Node.val <= 1000` | null | Dynamic Programming,Tree,Depth-First Search,Binary Tree | Hard | 112,129,666,687,1492 |
46 | hey and welcome today we will solve permutations interview question in a recursive way soon there will be a backtracking version as well so let's Jump Right In First example here just a disclaimer this video will be a bit mathematics involved but if you landed to this video I hope you already understand what permutations are if not please check some videos on that topic first to get you into the right context there are plenty of people that can explain it so much better than me to be honest but if we get back to the lead code problem now in case of one two three as you can see here there are six possible ways that we can arrange them next to each other and our algorithm has to return them all second example simple enough zero and one and there are only two possible ways that we can arrange them next to each other and finally a single value which we might return it inside of an array this is kind of edge case and Lead code wants to give us a hint that it expects to get the result in a two-dimensional array even if we in a two-dimensional array even if we in a two-dimensional array even if we have single elements inside of that so let's see what we need to do first things first based on mathematic rules permutations of n objects equals to n factorial of course the original formula we see everywhere is this one right here which refers to permutation of n objects taken R times but it's better to note that there are four types of permutations and the one that we are dealing with in this problem is the first one I'll put a link in description for a slide that I found that pretty much helpful in case if you're interested but if we consider our array examples if we have three elements in the array we might expect three factorial possible permutation as a result which is six if we have four we might return four factorial permutations which is 24 and so on so that's been clear now one way to solve this problem is by using recursion in which what we need to do is thinking about checking all possible combination of numbers that can be arranged next to each other that means one by one we have to put numbers next to each other because literally we've been asked to provide all possible cases but how we might do this we can perform a depth first search on each number because if we take a look at numbers we have in a tree mode we might quickly realize that if in each breath of this DFS search that we're supposed to perform we remove the used number from possible choices we have and we keep doing this until we reach to a level that we use all available numbers what will happen then pretty much the picture is obvious but the thing is the pass for each value will give us our permutations that would make sense because in permutation numbers should not be repeated only the position of each should change and as a side note and matter of fact we will have three factorial passes for this example as we discussed it at the beginning but everything seems to be sunshine and rainbow so far until we get into the coding part in code we only deal with an array the process looks simple enough though we supposed to take one number pluck it out into its array and whatever remains will be rest of possible options to choose from which indeed will form their own path and finally we will get into our answer when we run out of remaining numbers to choose from so this is the exact recursiveness part of our solution we need to repeat this cycle of plucking out number and try the combination of that number with whatever remains in our hand until there is no numbers left which would mean that we hit or base case that is the point that we might declare that we are done with this path and this cycle will happen again for other numbers in the array as well we plug it out form the path with each of other possible numbers and repeat this cycle again until we hit the base case where we don't have any numbers left to continue that would mean having all permutations in our hand since we don't have any more numbers left in our main array to do this cycle again with it now with all that explained let's jump into the code to implement the solution so the first thing to do is creating or result Ray and returning it at the end of this function next thing is going to be our DFS search helper function we can either Define it outside of this function or inside but if we Define it outside we need to pass around the result array since we will push our possible permutations inside of that so we will Define it inside and Skip passing around the result rate what this DFS function receives as arguments are two things first is a single array called possible permutations that we keep adding numbers into it or better to say we will form more permutation as we go deep in our call stack of recursion so we call first one as possible permutation second is going to be the rest of numbers in array in each level we go deep but except that number we already use this literally means we pick out one number in each level and try to follow new passes with each of numbers that has left literally forming a pass for every possible option so second one will be rest what will happen inside of this function is quite interesting for each of numbers except the one that we used in each level I mean literally the rest array we will do a recursive call a function itself that means an iteration of a rest array first and next thing we had to do is call the function but with proper arguments first argument is going to be plugging out the number we're supposed to use in that level of recursion as possible choice but note that the first argument for or DFS function is the possible permutation so we need to keep updating that argument as we go deep inside of our recursion levels because at the end of the day we need to add it into a result array and if we lost track of previous numbers from previous recursion we will not have the correct permutation that means spreading possible permutation arguments into first array alongside with plucked out number the one we choose to we continue with then the second argument in recursive call for DFS function will be rest of numbers except that one that we plugged up so we will do the proper slice for that and that will form our DFS search but we are missing one really important thing which is our base case for this recursive function so the definition of base case will be then the rest array is going to be empty right as we discussed it in the slides because that is when we have no numbers to choose as a possible candidate to continue the path we are forming so we will do a check based on that and that is the step we might notice that we are at the end of the pass and the current pass we have is the full permutation one of the possible permutations finally return from that check since we are done with that pass now the only thing that left is to call the DFS function with an empty array as a first argument which will then form more possible permutation and passing nums array as second one which will be used along the recursion levels now if I run this test cases are passing and if I submit we are in a good shape here now let's jump into the time and space complexity for time complexity we will have all of n times to n factorial where n is the length of array obviously first then because of or for Loop and in factorial for the permutations count for space complexity it will be of n factorial again because we found n factorial amount of possible permutation so that was it for this video Just note that soon there will be a backtracking version as well please stay tuned for that one too thanks for watching and please leave a like comment and subscribe to the channel I will put the link for arrays and Mathematics playlist in the description to check it out if you are interested and finally hope you enjoyed this video and stay tuned for the next one | Permutations | permutations | Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**. | null | Array,Backtracking | Medium | 31,47,60,77 |
97 | hey what's up guys this is chung here again so today's daily challenge problem right number 97 interleaving stream okay cool so this one is a very classic you know dp problem so you're given like uh three strings right s1 s2 and s3 and you need to find out if i3 is formed by interleaving of s1 or s2 okay so an interleaving of two strings is s and t that is configured where they are divided into an empty substring such that you know basically the uh the pieces of two strings right uh the difference is smaller than one right so basically you can either be s1 t1 s2 t2 or t1 s1 t2 s2 right so for example right we have this kind of s1 is this is 2 and then we have s3 we can split s1 i3 in this such a way that you know they can form as three right and yeah and the base case right if they're both empty you know it's also true right so that's it right i mean so one thing for i think first i think we have to be uh we have we need to notice that you know actually this thing is actually it's not it doesn't really matter because you know as long as you try to place those two strings together you know the length of the two parts will always be uh the pieces of two parts will always be smaller than one right because if we have this kind of two strings right it doesn't really matter how we split them let's say we if we split them into this right this one and this one let's say we split them in into three pieces right and if we're trying to split this one into one pieces right and then if we do that if we try to add this one in into here okay but then the remaining will become one piece right so actually it doesn't really matter you know how split this string you know as long as you put them together you know this thing is always satisfied okay so then you know then the problem just becomes too you know we just need to check you know for this s3 can it be formed by either uh by any combination of the s3 or s ii one or s2 right and for this kind of like uh two strings problems you know we always uh we always need to have like a two dimensional dp right so in this case we have dpi and j here right so what does this one means that you know from 0 to i plus j in s3 right i think this is going to be a minus one here because this ing and r1 base you know from zero to i plus j minus 1 in s3 can it be formed by s1 and s2 right and since we have two strings right so we only have actually we only have one options you know let's say we have this kind of uh a b let's see the i plus j is here this is the i plus j okay and at this moment we only have two options so either this one can match with the uh to match with the with some lighters in s1 or this slider can match someone in s2 right so for example you know if this one can match the number to match the lighter in s1 right which means that you know we have so this slider will be is the same as the ice letter in s1 then it means that you know we all we need to care is that you know since we already know okay this one matches the s1 so all we need to check is that if the dpf of i minus 1 and j if this one is true right because you know since we already know this one can be matched with this one if the dpi minus one j is true then it means that from this whole part is true right and another option is that is if we also this one can also be matched with some letters in s2 right so that's why you know this there's another option which is i j minus one right so if this one is matched with some letters in s2 right and then if this i j minus 1 is true and then the whole string is also true right basically this one is like the s1 i right equals to the current letter right this one is s2 j right equals the current letter right this thing between this thing is or right so either one of them is satisfied it's fine right basically you know we can with the current i and j you know we can utilize the previously we can basically use the sub problems a smaller problem to get the cut to get to the current one because you know like i said if this one is true and or this one is true and we can simply use this one plus this or this one plus this one to get the current state right and in the end we simply return the dp minus one and minus one which means that you know with everything we have used can we is it true right um yeah i think that's it right it's a pretty straightforward one and let's do a dp here so i have an n i'm the length of s1 and the length of s2 if uh so we have some uh special case we can check so if this one is does not if the total length does not equal to the length of f3 will simply return false right and then for dp we have false right n plus one for this one in range of m plus one right so very basic dp stuff since we will be using the dp uh i minus 1 or the dp of j minus 1 right that's why you know we allocated one more space for this dp so that it's i so that when we loop through this i here we can start from one instead of zero so the base case is like this zero and zero right so zero means that you know there's actually this zero is the example three here that's the uh that's the base case and then since in the dp you know we will be using this kind of thing right so uh one two m plus one right and then for j in range of one two uh n plus one yeah cause i'm doing this way you know basically in this main dp here i'm assuming you know we're always both x1 and s2 are not empty right so if that's the case you know i can just do this dpi and j equals to what equals to uh either this one is even either the current one uh equals to the s1 right then that's the uh s1 dot i minus 1 equals to the s 3 dot i plus j minus one right and then we need to check the dpi minus one j right or like i said we or the current one what is i this uh i plus j minus one equal to the s3 right which is as it goes to is 2 j minus 1 equals s3 dot i plus j minus 1 right and for this one we have we also we need to track the dp i and j minus one right and in the end like i said i would simply return the i minus one uh the dp minus one so that's the two cases right either one of them satisfied it's true under we know okay so this one is true but as you guys can see here right i mean we start from one okay we haven't covered the case uh either i is equal to zero or j is equal to zero right so what does i equal to zero mean it means that the s x one is empty right j zero means j uh s2 is empty so for that we need uh we can either start from zero right and then like this i mean if we do this one you know in here we have to do a separate uh handle here because you know if one thing is zero then we there's we don't have any other options all we have is one options right but so i mean you can do it either way but in my case i just pre-processed them at the beginning so pre-processed them at the beginning so pre-processed them at the beginning so in this case i mean it's the uh so this one is the ice 2 is empty right so when s2 is empty all we need to check is that if s1 is equal to the i3 right so we have this one m plus one right dp i zero is equal to dp so recharge if the x one i minus one is equal to the i 3 dot i minus 1 right because the j is the same actually but the j is 0 that's why we can just use i minus 1 here and the dp of i minus 1 0 right since we only have one string same thing for the other case s1 is empty we have j in range of one plus n minus and one to m plus one this time we have zero dot j has two dot j minus one equals to the s2 i3 j minus one and this one dp i d b zero j minus one right yeah so that i think that's it if we run the code accept it right yeah there we go i mean time complexity m times n right space complexity is also m times n yeah actually there's a follow-up right yeah actually there's a follow-up right yeah actually there's a follow-up right so can you solve this you one using only s2 length additional memory space i think the answer is yes right i mean i think you can just remove one of the dimension from the dp here instead of storing the i and j i believe we can only store j because as you guys can see when we use i here we'll only be using uh i minus one so that's we that's why we can reduce this time complexity from 2d to 1d uh i guess i'm not going to do it here you guys can try it out by uh by yourself if you're interested um yeah i guess that's it right i mean it's very classic two-string problem you know two-string problem you know two-string problem you know so this one is i think it's quite similar to that kind of uh added distance problem right you have two strings and then you want to check if you can uh the distance between two strings yeah very similar i guess and yeah i think i'll just stop here and thank you for watching this video guys and stay tuned see you guys soon bye | Interleaving String | interleaving-string | Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`.
An **interleaving** of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that:
* `s = s1 + s2 + ... + sn`
* `t = t1 + t2 + ... + tm`
* `|n - m| <= 1`
* The **interleaving** is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...`
**Note:** `a + b` is the concatenation of strings `a` and `b`.
**Example 1:**
**Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbcbcac "
**Output:** true
**Explanation:** One way to obtain s3 is:
Split s1 into s1 = "aa " + "bc " + "c ", and s2 into s2 = "dbbc " + "a ".
Interleaving the two splits, we get "aa " + "dbbc " + "bc " + "a " + "c " = "aadbbcbcac ".
Since s3 can be obtained by interleaving s1 and s2, we return true.
**Example 2:**
**Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbbaccc "
**Output:** false
**Explanation:** Notice how it is impossible to interleave s2 with any other string to obtain s3.
**Example 3:**
**Input:** s1 = " ", s2 = " ", s3 = " "
**Output:** true
**Constraints:**
* `0 <= s1.length, s2.length <= 100`
* `0 <= s3.length <= 200`
* `s1`, `s2`, and `s3` consist of lowercase English letters.
**Follow up:** Could you solve it using only `O(s2.length)` additional memory space? | null | String,Dynamic Programming | Medium | null |
240 | uh hey everybody this is larry uh this is me going over day 23 of the february lego challenge searched a 2d matrix 2. uh hit the like button to subscribe and join me in discord so today i'm going to do this out a little bit of a funky order i actually spent some time solving this already and i was i actually came up with two kind of with two solutions that are kind of well one solution that's good and then a couple of naive solutions i actually go over all the details later so if you want to fast forward to the wrong layer you could do that um but one thing that i did forget was the m plus n algorithm uh and i feel like this is where you should have it so i'm gonna go explain this instead uh so yeah so while you do that hit the like button it's a subscriber and drama in discord or whatever you like i don't know if i talk said that already but the thing the key thing to know about this format and i actually did know this but i forgot to um i didn't incorporate in a good way but let me draw some ascii art here um and i actually talk about different ways to kind of you know analyze this so definitely if you have time go watch the rest of the video but if not this is going to be me going over the answer directly and coding it really quick um ideally but yeah but the idea is that okay so you know if you look at any cell what does this tell you right that means that if the target is uh greater than this then um if the target it's well let's do the other way around first if the target is smaller than this that means that um this rectangular corner okay that's a little bit awkward but everything to the left of 16 and then uh 16 and higher so basically this you know these four numbers and these four numbers uh if the target is less than 16 um then you know that is in that quadrant right and that's the only invariant that you need you might use this in variant to come up with a if this is a square matrix i come over log m plus log n algorithm or something like that um or i guess that's log n if this is a square matrix but yeah but since this is not a in this case it's a square matrix but in the general case this is not so what i would do is um looking at that and vary what does this mean right that means that you get to draw boxes um and then try to eliminate it you know one portion at a time so let's start with the target let's say 20 right so your box would be here and let me look at 15 well 15 is too small that means that it's not going to be any of the numbers in this box um so then we go down um and then 20 is still bigger that is not going to be any number because 19 that means that it's not going to be anything to the left or upper so that we can eliminate these you know all together right and then here is 22 is smaller so that means that we know that it has to be in this quadrant all right so then we could eliminate everything um yeah then that means that we can eliminate everything to the bottom of this because everything the bottom of this is obviously bigger than the number and i've been to the right i guess but technically as you move to the left it's going to eliminate so here you know we have 20 so you know we'll remove this because we know that's true so now we're at 16. uh again we have 20. so it's 20 is bigger than 16 we could eliminate this row um and we're at 17 20 is bigger than 17 so we could eliminate this world because we know that everything to level it's going to be smaller and then now here we just you know there's only one row left so the idea is the same but you basically go left and then you're like oh no more 20. so this is sad and then i return so that's basically the idea and because you remove either one column or one row at a time um this is going to be m plus n which is sublinear because linear is m times n um and i go over kind of the in my full explanations i go over the uh the more naive explanations but that's basically how i would solve this problem it's just eliminated one at a time but that's how i would solve it now because i actually i don't know when i was solving it the first time i forgot about this recurrence and i was trying to go from the upper left corner instead and i pray about binary search again i'm not going to explain it because you can watch that video or later in the video if you like and you can fast forward to that but for now we're going to implement this so then we start with uh okay rose is equal to the length of matrix uh let's see okay column is equal to the length of matrix of zero and then now we can start with uh let's just start with x is equal to zero y is equal to columns minus one and then we go uh and then we go from you know to the corner so while x is less than uh rows and columns is greater than equal to zero we check right if matrix of x y so what did we say if this is greater than well if this is equal to target we just return true so let's get that out of the way if matrix is bigger than the target that means that we have to move down right as we said because we just eliminate or everything to level that it's going to be true so yeah uh and then l is if matrix of x plus y is less than target i guess we can just do an else here too right it doesn't obviously doesn't matter uh that we subtract one and that's basically it and then otherwise we return force and yeah that's basically all i have um i would say so you know my life self i actually forgot about this algorithm so i actually looked at the form uh but i didn't look at it damage i'm like oh this is a linear algorithm and as soon as i knew that there's a linear algorithm i was like so i always they're a couple of variations of this form and i always forget i always mix them up which one is rich to be honest um but yeah hmm typo um that's interesting why that's a little sad but we could debug this real quick let me start 15 and then did i get the signs wrong if this is bigger than target then oh yeah i got the wrong one i mixed them up that's pretty much the only mistake you can make on this farm and i made it so uh so yeah uh okay let's give it a submit cool uh and of course this is gonna be m uh m of or o of m plus n because as you can see we go we for each column we only move right once at most uh and then for each row we only move down once at most so that's gonna be m plus n and of course this is all one space because we don't really uh only use a couple of variables here right um so yeah um that's basically all i have um i don't have anything more to say i think i added more context on you could watch the video where i go over um some of this but i think this is i don't like this prompter saying i don't really remember it that much and that's why you know this is a long video but i would say that people keep on telling me that they get this on interviews so maybe practice it enough um i'm okay um and on competitive i would definitely either do you know just look at every cell or do a binary search or something like that or like m times and binary searches um but yeah um that's all i have you can watch me salvage for the first time next and it's gonna be a little bit weird because i'm just gonna do the intro again but um anyway you can watch that next hey everybody this is larry this is day 23 of the february elite code daily challenge a couple of days more to go get let's get to it uh search of 2d matrix 2. hit the like button to subscribe and join me in this call let me know what you think about this problem why didn't you fish an algorithm yeah okay i was going to write an inefficient one but you got me uh search for target value okay it's fun points each row is sorted from left to right each column is sort of from top to bottom so this is a standard ish and it's not standard and i don't even know if you should know it doesn't come up that much and i always mess this up um but people keep on telling me that it comes up a lot so anyway um so okay so you just search for a number uh okay so the obvious thing is that you know if you look at every element it's gonna be linear time uh where linear is every cell m times n right and yeah uh i ideally you can do better than that uh let's see so this is sorted okay so it's actually sorted in both directions so that means that you can do some you know uh do some funky binary search um i think it yeah there are naive the other slightly less naive algorithms but still naive ones are like you know m log n or n log m uh for binary search on each row i think there's an m plus and one am i or am i think of a different problem that might be to be honest uh where hmm you're forced to oh am i thinking of the white one hmm i don't know but uh yeah and i'm gonna try to see if i could come up with this one it's still i mean given the n m is 300 i wouldn't worry that much about it to be honest but with respect to like on a contest i would just do something naive but uh it is you know as a habit of uh by naive i mean quite n times m but also you know this is definitely if you're here practicing you should try to do a little bit better because that would not be uh that would not be acceptable in an interview assuming that they're like okay you can write four loops that's not impressive um okay hmm i would say this is also one of those standard forms that i never get it i always forget how to do it exactly so let me see if i could reconstruct it from my invariance if you will uh so we're going to do a binary search on can we do a research um well okay let's think about what it means right uh let's say that you know we're looking at the southwest what does that mean uh that means that all the numbers that are under it is no good uh and all the not even just under it like to the right and under it are no good right because that means wait is that true no what am i talking about oh god no so if we're looking at can we do some quad uh quadrant stuff so let's say we have the nine now i'm just trying to do something funky let's say we have to nine uh we can eliminate can we eliminate quadrants hmm yeah i mean we can eliminate one-fourth yeah i mean we can eliminate one-fourth yeah i mean we can eliminate one-fourth at least but that's not really that ideal or not sufficiently ideal maybe because you can do the recurrence of like three fourth plus you know uh you know three-fourths of that and so you know three-fourths of that and so you know three-fourths of that and so forth right um so that's not a good series to sum up um is still linear of one man i'm really bad at this so i hope y'all are enjoying it at home um let's see okay let's say we start at one right then do we want to go to the two of the four are we looking for five i guess hmm well we go to the two and then we go for the three that doesn't really make sense right i feel like there's a walking algorithm but i'm i don't remem which makes it n plus m but i forget how that goes do we want to get the bigger number the smaller number um well what does that means to go to the right if it goes to the right it means that it cannot exist in all the things to the left which is not true if we are going to do a walking algorithm um because in theory and i'm just not drawing this let's play around with matrix here let me put it here with some ascii art if you will but you can imagine that what i just said was not true so if that's the case is it only n times log m because you know let's say we put five here then i mean i know that this is unique so okay let's just search for another number then um okay let's make this some x number let me get 5.5 and then for five we if we put it 5.5 and then for five we if we put it 5.5 and then for five we if we put it here then obviously we have to go straight down but i forgot it was 10 but if we put it here we obviously have to go here to the right so there's no decision that so i think by contradiction maybe that i don't think there's an n plus m algorithm but i could be wrong i don't know if that's a hard proof for me but it's just that you know making a decision it you like you don't you know if you only look at the immediate adjacent characters it doesn't tell you where the five could be because it could be here or here right as we said it could be here or here um hmm yeah is there some diagonal thing that we can take care of i don't know what was it was just searching for 20. i've been talking a lot for a problem that i haven't even read any code yet but 20. so whatever you got one and then you know you go to the five to kind of what is the fi so what does a five mean five means that all the numbers to the left okay i could buy that then nine and then seventeen okay i could buy the diagonal argument but what does that mean for me right and you could binary search on the diagonal uh from that from what we just said basically the right diagram what i'm just saying is that diagonal means that everything to the quadrant is force um and then you could do so you do a log of n plus m plus n plus m um which is going to be n plus m right is that true i guess that's kind of an n per sem algorithm so basically i don't know if i said that quickly but basically my idea right now is that we can binary search on the diagonal right um because i forgot it was 10 let's make this i forget what it was eight now it's like it doesn't really matter if it's seven basically we could binary search in a diagonal because we know that one well one is one but five means that everything to the left and up and everything in between are going to be on um it's going to be smaller than that right so we binary search and that means that you know this is strictly true going all the way go so then we can binary so oh that's not diagonal you could binary search at the diagonal to get the row and the column that you're in that the number should be in if it is in there and then you could just do a linear search n plus m on that row plus column and because that's log of n plus m plus n plus m that's going to be dominated by n plus m huh can we do better yeah i mean the answer is yes because now that you have the row plus column then you can just binary search on that so that means that it's going to be log of n plus m or log of n plus log of m huh okay i think i'm convinced i don't know if i could prove this so i guess we'll just have to prove it by ac a little bit now i mean i'm relatively okay i'm happy that i came you know this is a long video and i apologize but i think we've been playing around properly so i think i'm gonna try it i mean i don't know if it's right i'm relatively sure but i don't know that i missed anything so that's what i'm gonna do we're gonna go to oh so what i said assumes that this is m times n and i think it still works without n times m but it's just a little bit more tricky because then now you know let's say i mean in a very basic case you have let's just say this right then we can't really binary search on the diagonal um well we buy searched here or here and then what happens if this is here right um if this is here that means that it still could be in all these other ones so okay so what i said is true for uh for a square matrix so because you know now we have to take care of all these other o's we search those two so that is not good enough because then you have to keep going right hmm is there a way to kind of take advantage of that as well i mean the answer is yes you can do um you know repeat you know do the same logic with retweet double i mean i said binary search but i you can also do uh repeat doubling or whatever but it's the same idea um and you could definitely do it with you know things but it just the complexity is just really hard uh not really hard but there's a lot of all by one potentials and annoying things i think if this is a way more interesting problem with this m is equal to n um only because of that reason otherwise then you have this thing and then what do you do let's see because i mean you could also hmm let's see yeah i don't know i was excited to implement this and then i realized this edge case um or it's not an edge case it's fighter or the other case other than the perfect case but i mean you can do it but it's um it's a lot of yuckiness um so i'm just going to do the i'm going to do the regular m times log n one and a little bit sad because huh that's a cool algorithm can i really take advantage of it no i don't yeah i don't know uh i am a little bit tired though because i do this at 3am so i'm just going to do the naive algorithm and then we'll see um and then we'll go over the solution together i think some of it's just me being lazy to be frank and i apologize for that if you're staying up for that but i hope i gave you these ideas to my insights as i go through this um but you know we'll go over the solutions together i will read the forms or solutions or whatever and then we'll play along with it or maybe i even have done it before i don't know um yeah let's go so for row in matrix um rise like that bisect left uh row of target um if row of index is equal to target return true return force right so that's basically what i would do during a contest and as you can see uh this is done very quickly like i know that i talked a lot but you know this was a contest i definitely would have done this already and um and this is what i would submit especially if this was a yeezy or something or maybe even just a folder really but uh maybe i would have gotten the wrong answer though because uh because i forgot to check one thing but well i mean that's why we i run the tests what oh whoops oops a little bit rusty right now mostly from water talking probably all right let's just go submit oh yeah so this is going to be m times and m times log n or i'm just going to say m times log n you could actually make this a little bit better by transposing the matrix if or something like that maybe not actually transposing it but you know basically binary search the dimension that is longer but uh but i trust you know how to do it if you need to um but yeah but this is going to be oh of i don't know if this is m times log n or n times log m uh whatever same idea so basically um for each row you have log c maybe that's a better way of doing it um you can swap the pointers if uh if r is greater than c um if i as you can see we have a beautiful idea and of course this is um this is all one space because we don't really do anything else right um okay let's you know let's take a look the solution is locked let's go discuss see if anything good anyone got anything good um oh there's an m times m solution or m plus n solution i thought that i couldn't do this is this true top oh you have to do it from top right corner maybe i was a little bit off okay let's go back i didn't really read the entire thing i mean i already had the idea so what did i cook on so 15 11 why is that true i guess this is the same idea that i had except for this is much fancier with the binary search of uh trying to figure out what um quadrant that uh the finger's in and the invariant in this problem is that um yeah let me actually go over it um you know what um i'm gonna actually okay you if you're watching this is gonna be in a weird order um but i'm gonna record this and then put it in the front so i mean if you're watching this it's good explaining to you'll be really weird but anyway i'll see you later so i'm just gonna do my goodbyes i'll see you later uh thanks for watching uh and um yeah hit the like button hit the subscribe and join me and discord and also just take care of yourself take care of others have a good day and you know have to good mental health and i'll see you tomorrow bye | 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 |
387 | hey everyone today we are going to solve Le problem number 387 first unique character in a string here in this problem statement we are given a string s and we have to find the first non- repeating character in it and first non- repeating character in it and first non- repeating character in it and return the index of that character if it does not exist we have to just return minus one okay let's try to understand using an example let's say this s string is given to us and we have to return the index of the character which is not repeating in this thing and we have to give the first non- thing and we have to give the first non- thing and we have to give the first non- repeating so we are going to start from left we're going to check with the L first whether the L is depending or not L is coming only once it means index Zer we have to return so we'll be we will be returning Zero from here let's say if this is the this is our string s given to us here no character is getting repeated in that case we have to return min - return min - return min - 1 so this is our program statement and it's a very important question based on the hashing concept and has been ask in a lot of companies let's first try to understand the Brute Force approach how we are going to do that as we want the first index which is not repeating so we are going to start from index zero and then going forward to the index till n minus one so for the index 0 we will see whether this character is coming again in the remaining string or not so from 0 to n minus 1 we are going to Loop another again for i = 0 to nus1 for j = another again for i = 0 to nus1 for j = another again for i = 0 to nus1 for j = i 2 N minus1 we're going to check again whether it is repeating or not it's not repeating we will just directly return l or if it is repeating let's say if it was l in the last there was l in the last we'll check for the another character whether there is another e or not so for the E also we will be checking whether we have e in the remaining string or not if it is not present in the remaining string it is clear that e is coming only once and we have to return that so let's say in this case L is getting repeated e is also getting repeated t is not getting repeated so what we have to return is three we will be returning from our function and here we are solving this question in order of n Square because we are iterating over string again and again but this is not going to work this is going to give you tle and also it is not a very efficient solution so here generally in this case what is expected from us that we should be knowing all the frequencies of each character like how many times each character is coming to the string and in the constraints also we are given that s will also only consist lowercase English letters so let's move to our efficient approach is Hash approach our efficient approach is Hash table or you can say hashing here what I will be doing is let's say our problem statement is this s is this and I have to return the index of the non repeting character so first of all I will just see uh how many times each character is coming to the string so to capture that uh we are already given in the constant that we can only have lowercase English letter it means all the characters in The String will be from A to Z that is only 26 possibilities so even if I try to make a map and capture the frequencies of each character let's say a is coming zero times B is coming zero times e is coming three times and so on I will be able to capture the frequencies and after that as I want the index not the character so I have to iterate over it from left to right from 0 to n minus one and for each character what I will be doing I will be checking the frequency IF frequency equal to 1 if that frequency equal to 1 we will just return index if no possible solution exist we'll just return minus one okay I hope that clear that is clear to you that we are capturing frequency after we captured frequency we will iterate over our string to check whether any c is having frequency one or not so even instead of just taking a map if I just take a array of size 26 let me call it hash array where the indices will go from 0 1 to 2 till 25 what I can do is as my uh string s is going to contain only character A to Z if I map a to zero B to 1 C to 2 I will be able to map my Z to 25 it means I can map all the characters from this string to this array and what I can do is I can store the frequency in initially it is initialized with zero I will be storing all the frequencies this all the characters from s and later on once I have prepared the hash array what I can do is I will iterate over the string again and for every character I will see whether it its frequency in the as per the hash is equal to one or not if it is equal to 1 it is unique El it is not unique if there is no possible answer I will just return minus one okay now I have I hope that is clear to you and what is the time and spage complexity here in this case what is the time complexity first firstly we are just preparing this hash is taking order of end time after that we will beating over this string s to check frequency of each character that is also order of n plus n ultimately the time complexity is going to be in the order of N and what is the space complexity here I'm taking a integer array of size 26 that is almost constant for every input size so space complexity I will consider order of one so this that's the time and space complexity for this approach which is a hashing okay let's Now quickly code this problem so here first of all I need to capture the frequencies for that I will be taking a iner array of size 26 as I'm going to have only lowercase English letters let's capture the frequency for each character in s I'm mapping each character to the corresponding index and then incrementing the value it was initialized with zero in the starting okay now cap frequency is captured what we have to do is I have to figure out the index as I want the index so I will be iterating over the string s using for loop I = to 0 I less than S do length I loop I = to 0 I less than S do length I loop I = to 0 I less than S do length I ++ now if s do frequency of s do ++ now if s do frequency of s do ++ now if s do frequency of s do character at I minus a so that I map with like corresponding index in the hash if that is equal to 1 it means that this s do character at I is unique if that character is unique we just have to return the index if there is no such index we will return minus one submitting over sample test cases okay sample test are pass submitting the problem it got submitted successfully hope you the problem thank you guys bye-bye | 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 |
1,027 | hello everyone welcome back here is vanamsen and today we are going to tackle a very interesting problem from Elite code longest arithmetic subsequence so it's a medium difficulty problem we will try to implement it in C plus and we will use dynamic programming approach and also uh take a look at constraints that might be really helpful in this particular level one so let's Implement and I will explain right away so size and if and is less than 2 return n int longest will be 2 and Vector of vector of int DP and Vector int thousand and one and four I zero less than n increment and second Loop 4. J less than 0 J less than I increment and in diff num I minus num J Plus 501 and DPI difference will be DP of J difference plus one and longest will be maximum of longest element and DPI with the difference and finally we return the longest element so let's run it and see if it's working so hopefully it work and I explain what we did so yeah it's working so perfect so to understand the problem we are given an array of integer and we need to find the length of the longest arithmetic subsequence in the array so remember sequence is arithmetic if the difference between every two successive number remain constant so and a subsequence is a sequence that can be derived from the array by deleting sum or no elements without changing the order so for example in case number two we have example of 9472 10 and longest arithmetic sequence is 4 7 and 10 so 4 7 10 and difference between each element is free and also the length of the array is free so we need to Output the length so now let's dive into the solution so this problem is a great candidate for dynamic programming and we use dynamic programming array here so 2D DP and the idea here is to create an array of Vector where each Vector keep track of the maximum length of arithmetic subsequence that ends with a particular difference and we start by iterating over RI from the beginning and for each pair of numbers I and J we calculate their difference and update the maximum length of arithmetic subsequence that can end with this particular difference we also because RI is zero indexed and we know that the greatest difference possible might be 500 because it's a problem constrained so we calculate the difference and then at 500 watts so theoretically we can add this 501 here and here to have actual difference but uh then we will have like two additional Atomic operation that are not necessary so yeah the beauty of this solution lies in how we equivalently can utilize the dynamic programming uh Concepts storing and updating our findings as we progress through the array and also uh we take advantage of constraints so it's also important to know the constraint for your problem because this task could be used using a vector with a constant number of uh one thousand two elements or a map if for example we have much more elements so knowing constraint is very important so let's run it for unsynthetic cases and see how it's working so I'm running it and yes so we beat 92 percent with respect to runtime and also 77 with respect to memory and remember the key to mastering this problem uh is practice the more problem you solve the more pattern you will recognize in the future and uh it will make easier for you to tackle new unseen problem and if you have any questions or ideas to sure please leave a comment down below and don't forget to like And subscribe for more coding challenges tutorials and hints uh and as usual keep practicing stay motivated see you next time | Longest Arithmetic Subsequence | sum-of-even-numbers-after-queries | Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* 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.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500` | null | Array,Simulation | Medium | null |
1,818 | absolute some difference so I've solved this problem yesterday so I think today I can still solve it let me first explain the problem so we are giving two positive integer arrays nums one and nums two both of less than so they have the same length the absolute Su difference of arrays nums one and num two is divid as the sum of absolute of nums 1 I minus nums 2 I and for is I inside the range of the array yeah so it is a zero index yeah uh you can replace at most one element of num one so we can only replace element in Num one and at most only one element in Num one or we don't need to replace any element yeah and we what two yeah we can replace this ele any element in Num one with any other element in Num one so for example yeah you in this example we can replace this seven with one or five but we don't need to replace with itself because it means we didn't do anything yeah we need to return the minimum absolute sum difference after replacing at most one element in the array nums one yeah at most we replace one element for example we're going to replace seven to one or to five so the final result going to be three you can check yeah this line or this line yeah but definitely this going to be the minimum value yeah and the final result would be 10 modular 10 the^ of 9 + 7 yeah so we 10 modular 10 the^ of 9 + 7 yeah so we 10 modular 10 the^ of 9 + 7 yeah so we should know about this so this is the absolute definition yeah and the lens of nums one and nums two is 10 to the power of five so this means we cannot solve it by root Force by n Square we have to solve it like o n or n log n yeah so this problem seems to me it is a un Log In Time complexity yeah so let me first analyze the problem I'm going to use the third example to analyze the problem yeah so if I have two arrays so this is number one and this is number two yeah I just want to make an alignment yeah and you can see it clearly what it looks like yeah if we are going to check the absolute difference of each element so root of 1 - 9 it is 8 yeah and what root of 1 - 9 it is 8 yeah and what root of 1 - 9 it is 8 yeah and what about the second 10 - 3 it is 7 and then about the second 10 - 3 it is 7 and then about the second 10 - 3 it is 7 and then it going to be 1 4 - 1 going to be 3 2 - it going to be 1 4 - 1 going to be 3 2 - it going to be 1 4 - 1 going to be 3 2 - 7 going to be 5 and the last one 7 - 4 7 going to be 5 and the last one 7 - 4 7 going to be 5 and the last one 7 - 4 going to be three yeah so this is the absolute value if we don't need to replace anything so this going to be our result yeah so currently we can replace one element in Num one but we need to decide which element we what to replace let's check the answer so the answer from here is going to be the first element we're going to replace one with 10 yeah we just need to analyze why it is this element if you find a solution of this one normally you can solve it yeah so we're going to we want to change this one to 10 but why we can do that currently as you can see that the difference of 9us one or 1 - 9 it is the difference of 9us one or 1 - 9 it is the difference of 9us one or 1 - 9 it is eight yeah but if we since this number 1 to 10 what it going to be yeah so currently the difference will be one because 10 - 9 absolute of 10 - 9 it is because 10 - 9 absolute of 10 - 9 it is because 10 - 9 absolute of 10 - 9 it is 1 so what is this difference 8 - 1 it is 1 so what is this difference 8 - 1 it is 1 so what is this difference 8 - 1 it is 7 why we need to analyze like that yeah because we want to find the maximum difference 8 minus 1 is seven if it is in other plac definitely it is no bigger than seven if we find the maximum distance uh difference normally this going to be our result so the final result would be this numbers plus the seven why yeah because as you can say before so it is eight now after to replace one with 10 so the difference is one so this means our result uh this means this element reduced by seven so the final result should also be reduced by seven yeah because of one element and because it is the sum of all element so the final result would be also be seven yeah if we don't if we use this one so the sum of all those values would be like uh 27 yeah 27 minus 7 it would be 20 and this going to be our result if you don't believe it let's just try another number so for example we want to maybe uh yeah uh let me make the alignment make it better for alignment yeah uh I just want to try another example to explain it yeah so I think this alignment is okay so maybe you don't believe that so what about we're going to replace two maybe uh we're going to replace two with seven yeah can we do that yes so here is the still one and here this two going to be seven yeah but what is the difference 7 - 7 is yeah but what is the difference 7 - 7 is yeah but what is the difference 7 - 7 is zero right but before that it is a two 7 - 2 it is five so 5 minus 0 what is the - 2 it is five so 5 minus 0 what is the - 2 it is five so 5 minus 0 what is the result so yeah it is 5 minus 0 it is a five yeah but what we want to find the maximum difference it is seven but here is five it is it means it is no better than the first one yeah so we want to always find the maximum difference which is seven but how can we find this seven and we can use binary servs why yeah because for each of the element inside number two so for example this is nine we're going to find the close closest element to this nine so what is the closest element to 9 it is a 10 right yeah as you can see it is a 10 because 10 minus 9 it is one you cannot find any other element which is close to nine better than 10 yeah maybe seven but it is a two but you should choose this 10 if it is the first element yeah so this means for the first element in NS two this nine you can change it to the closest element yeah you're going to try if this is better or not yeah so if you try this 10 so the result going to be one because 10 minus uh 10 - 9 it is 1 minus uh 10 - 9 it is 1 minus uh 10 - 9 it is 1 but before 1 - 9 the absolute of 1 - 9 but before 1 - 9 the absolute of 1 - 9 but before 1 - 9 the absolute of 1 - 9 it is 8 yeah so what is the difference of 8 minus 1 so it is seven so actually we just want to calculate this seven we need to find this seven and then the sum of numers two minus this seven going to be the final result yeah similarly for other element we have to try one by one but this is going to be un log in time because we're going to Loop through num two for each of the element and then we're going to use the binary Serv to check in Num one because we want to find the Clos this element and this nums one can be sorted after sorting it going to be log in time so after sorting it's like one two uh four 7 and 10 yeah so we want to find a nine it is closest to 10 and we're going to find three it is close to two and four and we're going to find five which is close to four yeah and we're g to find one by one for one we're g to find this one it is closest and for seven we're going to find uh this uh we're going to find this seven it going to be the closest for this four we're going to find this four it is the closest yeah even we find the closest we should check the absolute value the final result I mean this is seven this seven would be the maximum the final result would be the sum of num two minus this seven because it can always be reduced to a smaller value yeah if you didn't get some uh result like seven or other values maybe it is zero you didn't get any result so it means you don't need to change any element in number one yeah I hope you understand the solution so for me uh my intution is that I F A solution to use a binary search and then I'm going to use a binary search to solve it yeah now let's let me just start coding I'm not sure if I can solve it today normally for yesterday I just solve it like in half an hour so today I just want to yeah try to use um uh solve it quickly um yeah now let me just to start coding so I'm going to use a rape so for I uh let me use N1 N2 or AB yeah let me just use Ab so yeah for I a in enumerate I'm going to enumerate nums one and nums two and enumerate would be a zape I'm going to zip it inside so num one and num two yeah and uh I going to prepare a final result and the maximum current maximum value because the final value would be the result minus this maximum and I'm going to also prepare on mod because the final result would be modular this value so the result would be zero and maximum would be also zero and the mod would be 10 to the power of 99 plus 7 so this is my variables now I can use the binary search but before that I need to sort the array of nums one I need to sort it so uh nums one should equal I going to prepare I going to do some tricks normally I would like to do this kind of tricks because I can avoid of a lot of AD cases for binary search and plus h infinity and you're going to understand why I going to do that but I always do this I going to explain this later yeah if you are familiar with B search uh maybe you yeah maybe you can think about this kind of a tricks to solve a binary search problem otherwise you have to check all the conditions it going to be difficult to use B search I going to explain this later so after paper res number one I'm going to sort it so nums one. sort yeah so currently nums one has already be sorted so this means I can use boundary search to search which value is close to nums two yeah so here nums 2 is this b represent element in m 2 so I'm going to use index Z so this should be equal to BCT I'm going to use a bisect left I'm going to explain this BCT left later I'm going to use the examples to explain it yeah so for the BCT left it is number one and in number one I'm going to search the value of this B yeah so let me check the first value for example uh this is a 175 yeah let me just put 175 after s it going to be the minus infinity 1 five uh 7 and positive Infinity it going to be like this is for Num one in example of num one and so for this Z is a bisector left I'm going to use binary search to search this element B So currently B is two right yeah so for this two you should know about that the index should be this J should be two right yeah so I want to get the uh I would to get the yeah let me think about it I would to yeah get the most closed element to this B to this two yeah so it should be one but how can I uh how can I get to this one yeah so um yeah here I'm going to use this uh yeah let me uh let me tack I'm going to use the most close closed element so I'm going to use a minimum value it going to be the minimum of two values which is a close to this number two yeah because first element so this two would be close to this yeah if I use a bisect left the two would be here because two is more than one if it is more than equal to this number so it going to be insert at this position if it is more than one it going to be insert here so if this is two it going to be inserted at index one yeah but here this is one and my B this number is two so it going to be insert at this position so I can get the minimum value between this B and one and five yeah so maybe this is not five maybe it is a three or maybe this is a 2.5 so the three or maybe this is a 2.5 so the three or maybe this is a 2.5 so the closest number would always be one or five yeah you have to understand something like that I otherwise you cannot solve the problem using binary search yeah BCT left so I'm going to check the closest Value it going to be minus uh number one with Z minus one so because this B is number two and Z minus one Z is two Z minus one it is this value one yeah or it can be another value it going to be uh number one Z and min B yeah and this going to be 5 minus 2 so this is why I prepared this kind of infinity because this going to be easier for me to solve the problem yeah so currently this number is two so for example if this number is one yeah if we were to use binary sear to find this one so for the index it would be one yeah so it going to be the minimum of one minus infinity it going to be infinity and 1 minus one it is zero so for the final minimum result going to be zero yeah and uh my maximum value would be the maximum of this Max which is a minimum value yeah so for here it is a little bit confusing you should understand that so from here I would always find the closest Value it going to be the uh it going to be the minimum but for the maximum value it going to be the yeah let me think uh let me think about it uh yeah let me just think about it so for the maximum value here so uh yeah let me just use this example maybe this example is better to explain yeah so for example for this uh nine uh I going to find a value of 10 is closest so I got a minimum of one and it should be 8 uh minus one yeah I need to find this eight so the eight would be uh this eight is yeah so here I need to also prepare the result should be plus absolute of each of the value yeah I didn't I about that but I need to use that so B minus a yeah so here similarly I need to use the absolute of B minus a or a minus B yeah minus this value so before this is a for the first element it is8 8 minus 1 it is a seven so the final result would be the result minus the maximum modular the mod yeah I'm not sure if you totally understand it or not um but the basic idea is binary Sears you here I just use some tricks for the binary Sears it means I don't need to Tex the add cases and for this one it's just for the result for each of the element I need to plus like 9 minus one I need to plus all the values so here I've got the result but I need to use this result minus this maximum value if I didn't find it maybe it is a zero so it going to be result if this maximum value maybe I've already the maximum maybe this seven is the maximum I going to just minus this seven you can just use this example to uh try to understand my solution I hope you can understand it now let me just run it to check if everything works something wrong yeah this is something wrong yeah let me just check what is wrong with it yeah let me first check this uh result here I going to prepare the result and the maximum maybe something wrong with my maximum value yeah I've always got a Infinity this is a definitely wrong uh yeah uh I should not use this kind of infinity yes because yeah this nums one should not be nums one otherwise I would make it confused yeah because for nums one it should be the length of three and also for Num two the length should be three for the first example but here I've got of plus minus infinity and positive Infinity I make it length to five definitely it is wrong so I should not use nums one I should use nums should equal to this kind of a value and then I'm going to use the binary search to just search the nums I should I think you should understand that because it is currently not nums one yeah and here going to be nums s yeah I have to prepare a new nums it is a copy of nums one but with a uh a padding of infinity and negative infinity and with that we can solve it easily now let me just run it uh the index is out of the range yeah this is also not expected um this is nums one oh it is not nums one yeah because I've already changed it to nums yeah because currently we have to use nums not nums one now as you can see it works so the basic idea is you should try this example and after adding this minus infinity and positive Infinity it going to make the index just inside the RS it going to never be out of the RS and it going to be easier to use this kind of a formula to get the result this is the why we're going to use some tricks yeah I've used this negative infinity and positive Infinity in a lot of binary search problems I hope you can also yeah use this kind of tricks to solve the B research problem easily now let me just run it to check if it works yeah I should delete the print yeah because it will influence my time yeah so after deleting the print let me submit it again currently it is 23 now let me submit it again I think it should be increased yeah because the print takes time and memory now as you can see it is 57% of all missions and can see it is 57% of all missions and can see it is 57% of all missions and the time complexity is here it is unlog in time and also from here it is unlog in time so the final complexity is unlog in thank you for watching see you next time | Minimum Absolute Sum Difference | maximum-score-from-removing-substrings | You are given two positive integer arrays `nums1` and `nums2`, both of length `n`.
The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**).
You can replace **at most one** element of `nums1` with **any** other element in `nums1` to **minimize** the absolute sum difference.
Return the _minimum absolute sum difference **after** replacing at most one element in the array `nums1`._ Since the answer may be large, return it **modulo** `109 + 7`.
`|x|` is defined as:
* `x` if `x >= 0`, or
* `-x` if `x < 0`.
**Example 1:**
**Input:** nums1 = \[1,7,5\], nums2 = \[2,3,5\]
**Output:** 3
**Explanation:** There are two possible optimal solutions:
- Replace the second element with the first: \[1,**7**,5\] => \[1,**1**,5\], or
- Replace the second element with the third: \[1,**7**,5\] => \[1,**5**,5\].
Both will yield an absolute sum difference of `|1-2| + (|1-3| or |5-3|) + |5-5| =` 3.
**Example 2:**
**Input:** nums1 = \[2,4,6,8,10\], nums2 = \[2,4,6,8,10\]
**Output:** 0
**Explanation:** nums1 is equal to nums2 so no replacement is needed. This will result in an
absolute sum difference of 0.
**Example 3:**
**Input:** nums1 = \[1,10,4,4,2,7\], nums2 = \[9,3,5,1,7,4\]
**Output:** 20
**Explanation:** Replace the first element with the second: \[**1**,10,4,4,2,7\] => \[**10**,10,4,4,2,7\].
This yields an absolute sum difference of `|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20`
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= 105` | Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures | String,Stack,Greedy | Medium | 2256 |
373 | hello and welcome to another Elite code video today we're going to be doing the problem of the day for um June 27th it's fine K pairs of small sums it's definitely an interesting problem it's a it shows you how to use a bunch of different data structures which is kind of nice and so and it's super it's not super hard but I definitely say it's towards the harder end of the medium problems so let's read the problem we're given two arrays so let's just say for this first example we're given one seven one and two four six and we need to return all pairs of indices where the sum so actually not all pairs of indices but we need to return three pairs of indices that minimize the sum so we take one number from the left and one number from the right so let's actually think about how we would do this like first of all it's pretty obvious what number you'd pick in the very beginning right so we're just going to pick the smallest two numbers because that's going to be guaranteed to be the best choice okay but now where do we go from there well it's actually been pretty straightforward as well right so there's going to be two ways we can go and then one of those is going to be the number we want we either increase the one on the left by one or the one on the right by one as far as the index because we still want to keep the smallest index of the left or the right array but then we want to just figure out like okay which one do we have to increase and then like what are we going to get and so we have this one too so we can get two different combinations if we increase an index so if we increase this one to a seven then we can use seven four okay alternatively if we increase the two to a four then we can use the one four and so you know that like 1 4 is better so we'll take the 1 4. and then from there what you actually want to be doing is every time you use a number you want to be taking the two numbers that are like right after that number and so here it's actually 1 6 because when you use this one for the two numbers that you have are um like once you use this one for you can either increase this one to a seven or you can increase the four to a six so you're either going to have a seven four or a seven six I'm gonna draw all this out like later but I'm just going to go over the examples for now so we're going to use this 1 6 because 1 6 is the third smallest number so let's go to example two in example two we have one two three and our k equals two so here it's pretty straightforward we're going to take a one here and a one here right that's going to be our first output and then our second output is also pretty straightforward we can move one of these two numbers Well we'd rather move this one to a one because then we retain the one so then we can get the one but yeah like I said I will explain it in more detail shortly so we have this now we have one other example where we have one two and we have three and our k equals three and so here we only actually have two combinations of numbers right we have one three and we have two three and so sometimes we're going to have a combination of numbers that like we're not going to have enough combination so the number of combinations of numbers you can have is the length of the left array and times the length of the write array right so here would be two times one so you can have two numbers here's three times three so you get them nine here's three times three yes let's actually get rid of this but yeah let's say we had an array of length three like let's say this has three elements and k equals 10 . well we wouldn't be able to get 10 . well we wouldn't be able to get 10 . well we wouldn't be able to get 10 elements right because there's only nine total so we do have to that's one thing we have to keep track and they do give us this but let's go back to what I said so now let's do this in more detail let's actually go to the first example and let's figure out like how we would do this how so we need to get the smallest number but also once we get a number we need to figure out where to go from there and so like I said from the first number it's really obvious where to go right from this one two it's really obvious that you're either going to want to keep the one and increase this to a four or you're going to want to keep the two and increase this to a seven well it's actually going to be the case for every number you take if you want like the number greater like let's say you're here let's say you're at this combination and you're when you're only going to want you're going to want like the next greatest combination well you're going to want one of two things again you're either going to want to make this four turn into a six that's going to be the smallest possible increase with a while keeping seven the same or the other way if this four stays then you're going to want to use this and so for two indices like let's say we have i1 and we have I2 or just say I let's just use I and J right when we take I and J the next biggest number like the small the next biggest number that's as small as possible is either going to be I plus 1 J or i j plus one whenever we're at a number and so what we can actually do here like let's say our K let's just try to get six elements here for example what we can actually do here is we can use a heap and the nice thing about a heap is in a heap we can just record the sum and we can record the indices and then our Heap will automatically give us a small sum and the only thing we have to do now though is we will have duplicates if we just don't do anything because like let's say this is let's just go by indices right so let's say we have like zero then we have 0 1 and uh one zero is the two indices that you want to go from those two so once you process this zero you'd want to go to these two because these are the next two smallest numbers because these arrays are sorted but the problem is from zero one you could go to one zero sorry you can go to one or zero two right so when you process this you can go to these two but the problem is from one zero you can also go to one so you are going to be doing repeated work and so the way to avoid this is we're going to do one more thing we're going to have a visited so we're going to have a visited set just to make sure we're not going through the same index twice and we're going to have a heap but the alternative think of a worst case scenario it would be an N squared solution where we'd have to get every single sum and then we'd have to and that wouldn't work or because we'd have to try like one plus two one plus four one plus six and that wouldn't work because each of these is ten to the fifth so you'd have 10 to the fifth squared which would be too big but with a heap we can just process as many numbers as we need so for every number we process we only put in two and so that's going to be like we doubled it every time but that's okay that's not super expensive and remember we're also actually do it we also actually have this visited and so we're not doing repeated work there okay and so let's look what the Heap is going to look like right let's look at all these elements let's just go one by one so at first we're going to start at this element here and this is going to be at index 0. so at first we're gonna store and in our Heat by the way we're gonna store to actually make this pretty big so we have a lot of room for the Heap let's make the Heap like this so we're going to store the sum of the two elements and their indices and the indices are important because then we can figure out where to go next we don't actually need the sum like we don't actually need some value we just need the Heap to sort by some that's all we care and so here the sum is going to be 3 and then index is going to be 0. okay so now let's just show how this is going to look like and let's have this result array so we'll have it over here okay so we're going to say while the Heap while there are elements in the Heap and while K is you know we're going to count down from K so we do have an element of the Heap we're going to initialize it with the first element so we're going to pop this from the Heap and then we are going to add the indices over here so we're always going to want to take this element now remember from this element you're either going to want to go to this is either going to want to go to uh one zero or you're going to go to zero one and also remember that when you pop this you are going to want to store it you're going to want to say you already visited it so you don't visit it again it's actually use k equals three because I think uh because I think with k equals 6 it's going to get too big and it's gonna the heap's gonna get with you big and it's gonna be hard to drop but let's use the k equals three from the example so one zero What's the sum well this is one and this is zero so the sum here is nine and then 0 1 so this is zero this is one and this is five right so some here's fives now we have two elements in the Heap oh and by the way whenever we put an element in the Heap I forgot we're going to mark it as visited so we don't put it in the Heap again so we're actually going to have a one zero one here okay and our result currently has this right here so this is our result okay so now which one do we want to take we want to keep taking the one small sum we can do that with a heat pump so we're going to pop this and then we're going to add to zero one and now we're going to take the two elements that this can go into but we want to make sure that they're not in the Heap already so zero one can go to 1 which isn't in the Heap so let's add it to the Heap that one and it can go to zero two so we're gonna add those in so what we're going to do is we're going to add those two elements into the Heap and let me just actually redraw the Heap here so let's just add it in over here the Heap is going to be sorted after we add in the elements anyway okay so we're going to add 1 what's the sum at 1 well it's the two middle one so seven plus four it's going to be 11. and then the zero two is going to be this zero and then this element right here so it's gonna be a seven so this is zero two okay so now this is our Heap now we pop the smallest sum which is going to be this so we pop it and then actually that's our third K value that we need so then we're going to have a zero two here oh and by the way I did script one thing so actually in this result we don't want to have indices we want to have the values that these at these indices so this zero and things should be the value of this indices so this zero should actually be one two but that's pretty straightforward because we're going to have indices here so all we have to do is just call there right at that index and then 0 1 is going to be this is zero and this is one so one four and then 0 2 is going to be 1 6. okay and that's going to be a result so we're gonna have two things here we're gonna have a heap that like I said once we take a value we can either go we have to go right in one of these two arrays so we try both combinations and then we also have a visited set to make sure we're not doing repeated work because we can get to the same number multiple times and then this would be our result for this case and if we look at it that's exactly what the result is right one two one four one six okay so now let's actually code that up and so what do we need to keep and we are going to initialize the Heap to the first two elements so it's going to be nums one zero and it's going to be so that's going to be these two elements so remember the first element in the array we're going to store in the Heap is actually going to be the sum and so we're going to store the sum there now we need to do the next part for the next part just the two indices and this is just going to be like this and brackets are correct yes okay so it's going to be sum index in nums 1 index and nums two now we do need to have a result we also need to have a visited set and when we are going to add 0 to the set because that's going to be the first thing in there so now remember we have two cases for the Heap so we have while the Heap and while K is greater than zero like once we get K elements we're also done but if there's nothing left in the Heap like let's say the Heap can only have two elements and you want k equals ten you're not going to want to pulp or anything so now we actually don't care about the sum we actually just need the sum to fall from the Heap in the right order so this is going to be hip-hop so this is going to be hip-hop so this is going to be hip-hop keep now we are going to append those values and remember we don't want the indices we want to actually append an array with the values so that's going to be this uh that and then we're gonna have nums two of I2 okay now we're going to subtract one from K because we just took a value now we need to check a couple things before adding the next two values in first of all we need to actually check so let's actually do um let's just do like next I here so because we're going to use this value a lot so this is going to be I one plus one okay and so if next I is less than nums one right like let's say we're at this value well we can't take the next value because we'll be out of bounds so we have to make sure that the next value is not out of bounds and then we also have to make sure that it's not invisited so this is going to be next I and then this can be I2 these are two conditions we have to make sure it's inbounds and we have to make sure it's not unvisited in that case we can push to the Heap keep and remember we're going to push the sum maybe next I Plus nums two of my two so this would actually be uh numbs next I think I did this a little wrong here I did yeah so it should be like that uh so that's going to be I think I have too many here as well so this is going to be that there we go now we have I think this should be good now hopefully I2 okay so we're gonna push that to the Heap now we're going to add it to visit it as well and so it's going to be next I and I2 now we pretty much have to have the same exact yeah that's annoying as always python leap code okay so now we have to do the same thing like we tried to increase the number on the left by one and now remember we have two choices right like if we're at zero we can either increase the number on the left by one or the number on the right by one so we have to do the same thing for the number on the right and so now it's going to be next I equals I2 plus one the same pretty much code so next I less than length of nums two and I won next eye not in visited heat push keep numbs this is going to be i1 so this should actually be numbers one yeah hopefully I didn't make that mistake too many times but let's find out Plus numbers two this is going to be next die and now we're going to do i1 here and the next eye here okay now we're gonna add it to visited next I I2 okay and now we just need to return the result and hopefully I didn't screw anything out okay nice oh we got a wrong answer though oh seems like I'm not adding it somewhere let's just make sure uh I2 so that makes sense yeah let's see what we did wrong here x i equals this next eye I2 is not a visited he push Heap nums one next side plus nums two that should be fine oh this is yes this is the problem so this should actually be the other way yeah so we're just adding the same thing twice okay perfect okay let's do the space and time complexity for this and I think this does depend on what smaller actually it's your K or your size of your like Heap and so I think if K is smaller so I think it's actually a rare case where you can have like a minimum and if your K is smaller then you're going to put in for every element you take out you're going to put in two so it's going to be like 2K or something but that's going to be n log or k log K here and then if K is bigger than both of these combined then it's going to be so if like N1 is the length of uh list one and two is a length of Link list two it's going to be something like N1 plus N2 this is how many he pops and he pushes you'll do because you'll have to put in and put and uh remove every single element so that's going to be this right the max size of the Heap is going to be this and then you're going to remove you're going to heat pop and heat push every single element so you're gonna do it that many times so I think it's going to be that depending on which one's smaller because yeah like for example here the K is three but we're only putting in two elements and so that's or let's say k here was like ten thousand it wouldn't really matter because our Heap would be empty so fast so you do have to do a minimum because it depends on which one's smaller and let's think about the space here so for the space I think it's going to be a Min as well and so if we're only taking K elements like if K is way smaller than length of this array it's actually K visited we'll only have K elements the heat will only have K elements but otherwise visited can have every single index from nums one and nums two and so what's that going to be well that would be every vowel like that would be every combination in numbers one and numbers two and in that case that's going to be actually and one times N2 so that's going to be quadratic but that's only if we have to go through the entire list and it's really big and I do think K is actually smaller so it will save us a little bit so this can actually it can never be quite this big because this is 10 these are ten to the fifth and K can only be 10 to the fourth so the max elements you can have is like 10 to the fourth okay and so that's gonna be it for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I will see you in the next one thanks for watching | Find K Pairs with Smallest Sums | find-k-pairs-with-smallest-sums | You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`.
Define a pair `(u, v)` which consists of one element from the first array and one element from the second array.
Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_.
**Example 1:**
**Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3
**Output:** \[\[1,2\],\[1,4\],\[1,6\]\]
**Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\]
**Example 2:**
**Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2
**Output:** \[\[1,1\],\[1,1\]\]
**Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\]
**Example 3:**
**Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3
**Output:** \[\[1,3\],\[2,3\]\]
**Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\]
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `-109 <= nums1[i], nums2[i] <= 109`
* `nums1` and `nums2` both are sorted in **ascending order**.
* `1 <= k <= 104` | null | Array,Heap (Priority Queue) | Medium | 378,719,2150 |
104 | hey what's up guys it's been a while but it is Nick white back with another little coding video it's still grinding through all the way code problems got to do all of them pretty soon deadlines rolling up for job applications so just getting ready for that this is just max depth of a binary tree if you guys don't know a binary trees are you can check out my other videos I do a lot of the other stuff I check out pre or post order and in order traversal before this but this is just finding the height of a tree so it's kind of like a level by level type deal so there's two ways to do this I'm in the leet code Explorer page I'd say go check that out if you'd like to it explains it perfectly there's literally explanations right here so that the top-down solution is basically that the top-down solution is basically that the top-down solution is basically we're gonna start at the root and we're gonna pass in a depth as a parameter every single time we go level by level down a binary tree so you see this is the tree right and we would go we this would be the depth will be one here and we go level by level and we would check the depth and what we're gonna do in the top down solution is we're gonna call recursively on the left and right nodes right here on the left and right nodes and we're gonna be passing in the depth each time so the first iteration the depth is gonna be one and we're gonna have the root and the root once the root gets to null you know we're gonna be at the end of the road here and then we're gonna return but we're gonna be calling this maximum depth ammas a method recursively on the children left and right nodes passing in the depth with the increment of one each time so we're gonna be incrementing each time we go level by level and we also have this private int answer variable too so we're recursively calling the depth is increasing every time someone we call on the left it will maybe it'll go to three at this stage if we call on the right it would go three at this stage and then we call in the left here we'd get a four and basically what's gonna happen is we're gonna hit a point when we get to the leaves you know right here right if we root out left is equal null and root out right is equal now so this would at this point like we have a C at this point any leaves that we get to we're going to update answer with the max between answer and depth because depth is always gonna have our you know final thing right here right our final depth basically like wow how else do I say that right so when we have when we get to see the depth that's getting passed in it'll be I think it'll be four actually and then you know if answer is three because the answer is getting updated each time so answer would be three already we would just update it right to four and then you know answer is always gonna have our answer and we would maybe return answer if we needed to return it or use it out of route wanted to use it then there's the bottom up method which this is another way of doing recursion this is just a way where we have our both of these have cases where we stop our recursion and this one's a little bit different though I think this one's a little bit easier to write in this case it's just you have the left height and the right height so left upright depth you just recursively calling on the left and right when you get to know you return and then you just have you take the max top met the math max the maximum of the left or I and the right height and you just add one every time so as you recursively call you're just adding one each time which it's pretty straightforward and you just keep it's just level by level you're just adding one each time conclusion I mean I don't know it's pretty I'd say they're pretty easy honestly this is some of the easiest these are some of the easier problems we're still going through I did about a hundred twenty problems already they're all easy problems so trying to get into medium soon but that's pretty much it like check maybe I'll link the explore page this explore page in the description I mean really this one's really easy for Therese so check out other tree videos if you want to get up with those I have other ones on my channel but yeah thank you guys for watching sub check out everything in the description and I'll see you later | 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 |
321 | hey everybody this is Larry this is January 4th um is me doing a bonus question and yes I forgot to click did this in the other video but hopefully you know if you're doing it with Mia here uh you'll see that you know there's an unboxed surprise uh if you click on it you get 10 Bitcoins and a little closer that to a free month of the code or whatever it is um all right so yeah so today I am going to do a bonus if you will an extra problem um just to kind of get my practice on a little bit because the other one I guess I've done it a few times or whatever uh how do I okay to do so that's uh yeah let's do another one uh let's go ing create maximum number okay this looks at an interesting one and again not a premium question I feel like whenever you know uh those of you who've seen me did it a long time ago uh I keep on doing RNG and then I keep on getting premium ones but now that I'm you know um now that I actually have premium uh the RNG is giving me nine premium ones anyway okay so today's problem is 321 create maximum number uh so you're given two individual ways numbers one numbers two M and N okay whatever um so but they are different um different lengths and the digits of two numbers you're given an integer K create a maximum number of length form from digits of the two numbers the relative order of the digits from the same array must be preserved return in a way of decay digits represent a number okay what does that mean number of the length k from what does that mean give me an example this is like I mean these examples are okay but thank you I see this is a wave I mean this is not I don't think this is um in our way just the hard problem I just think this is a really pretty worded problem because you can just be like oh here's some digits make a number you have to explain the words on how to make the number you know like uh like you know uh I don't know just I don't know this is kind of dope but whatever but okay so um how would I do it right so okay K is less than a thousand um I mean the first idea that I'm thinking in my mind is um dynamic programming right um does it make sense also I feel like my neighbors uh vacuum cleaning so if you could I don't know if you could hear it but if you can my apologies hopefully um you know I don't know it just doesn't hopefully it doesn't matter um this is a hard one to actually I think initially I thought you could I mean and N square is going to be fast enough I do suspect it is going to be some sort of dynamic programming okay but I think there's even a more uh let's say 500 right so 500 times 500 is what quarter of a mill right and a quarter Mill times 10 is 2.5 right and a quarter Mill times 10 is 2.5 right and a quarter Mill times 10 is 2.5 mil that's going to be cutting it close so there's a dynamic programming where no maybe not oh well they're not 2.5 million State it's just they're not 2.5 million State it's just they're not 2.5 million State it's just that it'll be hmm I guess let's try that and then we'll see no because then each state will be 10 times some binary search um so my idea was initially that you know basically you ask yourself okay can the next digit be a nine right um and then just greedy if um you know you do binary search on the left to get the first nine or you get the binary search on the right to get the first nine on the right um or numbers one and nums two and then you request based on that um and then now you one fewer digit and then on the next digit you ask can I get a nine can I get an eight Etc right um okay and in this particular problem you always wonder earlier number because that just gives you more option right in a greedy way um is that the way to do it I think the tricky thing is that the banks are kind of tight on python I think one thing that I'm kind of bad at is that oh just PTSD if you will is that python um the code python performance has been kind of bad so um or at least like not parody you know so uh um yeah I'm trying to think a little bit I mean that definitely is a part um but then you have to I think the other thing is this path construction as well so that's actually a little bit tricky my other diet is try to think whether it can be really a greedy um and it's the same idea but instead of doing that recursion that we talked about and then just kind of hope that it works out this is a hard problem actually I was wrong about well I mean I feel like if I was in C plus and maybe I will have to switch I feel like I wouldn't necessarily worry about it there's a quarter of a million States each of those States you do 10 binary search on up to 500 Elements which is less than 10 so 100 so like 25 million operations or something like this um and binary search is pretty fast but it's just a very quick check it's just that in Python it is on the code python it's not parody when C plus I feel like that's maybe even okay foreign like for example for this one right if we say okay let's say we try seven but then we know that we can be seven because we don't have enough digits to fill it out so then now we try sex how do we know which six to take this one or does it matter maybe it doesn't matter well in this case it doesn't matter because there's nothing in between but can it matter let's say we have six seven I don't know like two does that matter still well by definition if this number is bigger than you would have taken that instead and if it's smaller you don't want it anyway because now you could take the wrong one because for example even here if you take this sex instead then you'll have six seven and you can't get the other seven but if you do it the other way you have to take this six to get this seven can I skip the binary search I guess I could skip the binary search if I have a lookup table this is so silly I feel like I'm doing a lot so okay I think I got it maybe um but this is not I don't know we'll see how this goes to be honest but the lookup table is only 500 times 10 so it's not that big of a deal but that's okay let me play around with it I know that I'm not very good on explanation right now because to be honest um you know this is a new plan to me um and like I said I'm not quite sure I'm even right on this one but I am going I mean I'll explain my logic and my thought process but I'm not sure that this is right but basically I'm just creating a over one index for lookup for uh an array so that um we know what the previous number is or the next number but I'm doing it backwards to get the previous number um uh okay yeah so basically what we want is let's say look up is equal to um foreign times uh length of n right and then this uh we want 10 of them right okay and then basically for the digit I didn't know zeros are okay I was there was they just didn't put any okay uh for x and range from zero to nine inclusive um for index and range of n minus one we're going backwards uh let's see so last is equal to n and then basically look up of X of index is equal to last if array of index is equal to X last is equal to in the last as you go to index okay uh let's just say we turned and then that's to create lookup of numbers one you have to say look up one and then look up two is equal to create lookup of nums two and then we print done really quickly just to kind of see if I'm in the right place it should be times n that's why I okay so zero one two so what am I doing all right three four so okay this is kind of a terrible input I need something more duplicate okay fine I guess I'll have to put in a duplicate so basically for example uh let me just say one five something like that okay foreign okay so then now one will look to the next pointer and then okay good all right so we have these lookup tables now I think we can do dynamic programming basically the requirements that we want what is um wait uh I forget that you have to do the output sensor let me think for a second what's the best way to do it foreign I think part of me is just like I'm in disbelief that like this problem could be that hard to do and I could do it but it's just I'm like I'm wondering if I'm missing something more obvious I guess is why I'm a little bit curious to accept and raise a slow six I think this case is the one that I don't know how to do in a good way because we can also skip how do we what do we return foreign like I said I don't know how this one's kind of hard like we could do it with DP but I just feel like that's really hard okay I mean it is what it is um okay I mean I um yeah let me see what I can do first okay so let's just say um possible um let's call i1 I2 for the indexes how am I structuring this and I don't know how to do the typewriter hmm like if this can be a six then what I mean even if you maximize the next digit you have to maximize the digit after that right huh I don't know well maybe I'm doing it really the wrong way oh and usually these kind of farms are very greedy in that you just test to save as sex as possible and sex is possible it's so impossible with three digits afterwards but then now you have a branch and I think that's the point that I don't understand how you can because you have a six and then you have to take it in both places thank you and then in one case you can have a seven possible but then in the other you don't right which is kind of a weird thing maybe not maybe I just have ah this is kind of okay maybe the way that I do it is in traditional top down but just you know a weird sort of Bottoms Up we'll say okay let's try it okay so let's say answer is and we always have to be true because well like there's always an answer is what I mean um okay so basically for you know in k we ask ourselves can this number be possible right um and then we look at that from the other possible set so let's just say I don't know this is quite right it's very weird um so basically yeah for x y and possible uh or i1 I2 maybe that's a little bit better right okay then we want to say um it is possible if we take a 9 here Okay so just say from the zero Force all right so then here if it's possible we always take it no matter what right but basically okay take the one from i1 so okay so then now um look up digit of Pi one so this is going to be the next Index right so ni1 is to go to this so then now also need um N1 is equal to length of numbers one and two is equal to link with numbers two so then basically because I need uh whatever something like that yeah okay fine um basically now that we have a new index so N1 minus N1 and i1 is going to be the number of digits left I need to also do a do an additional frame of just n Maybe so okay pronounce one left as you go to this thing numbers two to left you go to N2 minus I2 because we haven't changed it so then now if numbers one left plus nums two left is greater than or equal to the numbered um so these are the number of digits left and then K minus used is um maybe we want to set it's a k minus used yeah that's number of digits that we still have to fill minus one because it uses zero so then and as we assume that using this we use one of the digits um then this is a good one so then maybe we have a next possible um so then ni1 I2 uh okay and then ni2 is a good lookup of digit of I2 and then we do the same thing really I probably could program per error parameterize this split thank you okay and I guess we don't need a fan it's just basically um oh wait I mean I guess we do so basically now after we go full of it if next possible is greater than zero then that means that we're good and then we can break but we also want to answer that a pen digit and then um yeah and then now possible is your next possible and I think that's the idea I don't know if it's quite right uh to be honest uh oh yeah whoops minus one um I'll look up one yeah you right well do I not progress four oh and yeah this doesn't move for some reason okay so that means that we nine this one doesn't oh it just assumes that this one has it and then just keeps going to the end so we need this to I don't know why I didn't think about this or at least I didn't is you go to n or not equal to n less than n then we do this thing that's what I meant to do but I think I just forgot about it and I was worried about getting a no and not correctness uh yes again thank you are so smart okay uh we missed the first digit but maybe nope we missed a lot of digits really uh okay uh let's actually add an assert here okay so that's good in that you know tell me as well do I have any typo here why is this so weird because it's fuse okay but then for here it does not find a nine foreign after the last one because it finds an eight for the first one but not the nine why not tell me why unless I missed a nine somewhere why doesn't it foreign sex foreign oh because it doesn't count the first digit because I messed up because we technically start from before the first digit okay that's an easy fix actually well relatively um well we start at negative one I guess is to how we do it I don't know that quite works at the formulator with the N1 minus give it to just let me think about this for a second so basically we want to put the next number so okay fine I think I do this and then we do this plus one to consume it maybe and this is where you have to Define this way precisely okay so we're a little bit better but we're still getting a solution now open 9 8 6 5 3 and then we just keep going somehow uh what all right this one is actually normal to hit but why do we get so many no it's right huh why was it printing so much earlier okay well now it's still one for this one but that's okay maybe it seems like I have another off by one let's see 99 yep yeah I feel like I've been off by one because now we move it to the next one on top okay I feel like we're close though we do it's just that uh well we're not right but nine so if things is zero that's actually tricks if we zero two so this is at the end and this is at the end right and then because both of these cases is that true I think this is one um did it actually should be yes so it was here that should be impossible to hit on a white one I don't know why this am I just misreading this I think maybe I'm just confused because I think they the um this is not for this particular I read this as the one for the first input but actually I think this is for like the second or third input that's why um the new UI kind of messed that up a little bit um but I think I just misinterpreted the UI because now it's just missing right okay tell them what I think is more reasonable so this zero two so that means that going from 0 to yeah I guess so and here it could be 939 this could be 989 so I guess they're both true okay so zero and then it gets a nine as a possibility um maybe I should do teach it and then next possible maybe that's a little bit better for debugging for consistency I know that it goes to the next one but I think just for okay right and then now it thinks two is good but that's not true is it I think this is this plus one I think that's why they're off by one hmm okay still wrong why does it think 2-2 is a still wrong why does it think 2-2 is a still wrong why does it think 2-2 is a valid thing to do oh this is just minus this plus one whoops provides maybe that's why okay um this is a very hard problem to be honest now just take it out because they're gonna give me a wrong answer and I can't even debug it I am going to take out this other point statement but then after that I think I'm just going to submit hmm beat 100 am I missing something really obvious I feel like the way that I did it is kind of really hard so what is the complexity here right well this next possible set can only contain n by m and it may not seem possible but because this status order indexes of n by m right so that means that next possible is going to be at most half um at most and one times and two elements each well I mean a lot of those it's not possible it's just that in theory right um and this is obviously o of K and this is O of 10 or number of digits if you will D for digits and then as I said this is going to be N1 times N2 at most so that means that total complexity is going to be o of K times D times N1 times N2 time which for this one um that seems a little bit slow actually because this could be a thousand times 500 is actually pretty slow I mean a lot of these states are not possible but that is scary to think about and you have to I think you have to do some amortization math I guess in the worst case if everything gets hit once well it's not possible to do N1 times N2 because I don't know how to analyze this to be honest um I think I'm just I mean this is an Optima a pessimistic bound I think there's some admirization map on I'm just thinking about edge cases in which this case is uh harder than you know so I'm just trying to figure it out a little bit uh um but yeah it is just greedy well if they're all in the same number then in the case where they're all the same number then this is just um it's not N1 times N2 because that's not possible because if they're all the same number then you almost have a you know um it's going to be just um one of them doesn't one of the end if they're all the same number then you can think about it as N1 plus N2 is equal to K Used right so then in that way it's just going to be K times N1 and that's why that's going to be fast um times 10 I guess for the D and they're all different numbers then you jumped ahead so much that a lot of the things are not possible so I don't know which one is the worst of case but I think that's why you know this is the upper band I think it's closer to N1 times N2 is the bound um yeah and same thing for space because space is just bounded by this anyway um so yeah uh this is a really high problem I don't know that I explained it right um you know okay but yeah uh do let me know what you think um yeah about this problem let me know if you attempted this is not a premium question so you could do it with me but I don't know I clearly struggled a bit with this one so definitely let me know um yeah that's what I have for today let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye | Create Maximum Number | create-maximum-number | You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`.
Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array must be preserved.
Return an array of the `k` digits representing the answer.
**Example 1:**
**Input:** nums1 = \[3,4,6,5\], nums2 = \[9,1,2,5,8,3\], k = 5
**Output:** \[9,8,6,5,3\]
**Example 2:**
**Input:** nums1 = \[6,7\], nums2 = \[6,0,4\], k = 5
**Output:** \[6,7,6,0,4\]
**Example 3:**
**Input:** nums1 = \[3,9\], nums2 = \[8,9\], k = 3
**Output:** \[9,8,9\]
**Constraints:**
* `m == nums1.length`
* `n == nums2.length`
* `1 <= m, n <= 500`
* `0 <= nums1[i], nums2[i] <= 9`
* `1 <= k <= m + n` | null | Stack,Greedy,Monotonic Stack | Hard | 402,670 |
1,004 | hey guys welcome back to my Channel today we're going to be doing an other leak code in our Elite code 75 study plan series uh so today we will continue with the sliding window category uh we're going to be moving on to another medium problem and this one is called Max consecutive ones uh three so uh for the instructions we're given a binary array nums and an integer K return the maximum number of consecutive ones in the array if you can flip at most K zeros so by binary array um they just mean you know zeros or ones uh for our input array and then we're given K which is our allotment of zero our allotment of zeros that we can flip into a one and then we want to con count that subsequence of uh continuous ones and return the amount of ones uh so you can see uh in the explanation in the example input uh what exactly that looks like if you're more of a visual person so uh here we're outputting six because if we flip these two zeros which are bold and right here we'll have a continuous sequence of six ones so let's go ahead and implement this uh first what we're going to want to do is Define the left and the right side of the window so we're going to want to say and left to zero and then we're also going to want to declare a write integer and we're not going to set it to zero because we're going to do that right here with our for Loop so uh right equals zero and then right is less than non-style length non-style length non-style length and then right plus so we're just going to iterate through uh the entire nums array essentially and then what we want to do is uh if nums at Index right is equal to zero then we subtract a k because if you think about it we're given our input parameter K which is a number allotment of how many zeros we get to flip so if we run into a zero then we need to subtract that number because we're running out of a lot of zeros to flip so if nums at right is equal to zero then K minus numbers okay but what happens when we run out of allotted spots uh to flip a zero to a one that's when K becomes negative so we need to check that K is negative all right and if K is negative then we need to move the sliding window so if nums on the left side if nums at index left is equal to zero then what we're going to do is increase k and then iterate uh or increase left by one side uh by one size um and then after that we just return the difference between right and left and that should give us our answer all right cool so as you can see it passes both test cases right here go ahead and submit this awesome all right so um in terms of the space and time complexity um we're just iterating through the uh through the array the input array wants so it's going to be Big O N for our time complexity for our space complexity we're not using any data structures that scale with the size of the input so we have constant space complexity Big O of one uh I hope that this video was helpful for you uh in learning more about the sliding window technique we're going to have one more problem in this category so I'll see you guys in the next video for that if you're trying to improve your skills for coding uh interview preparation or just wanting to learn the sliding window technique then this is going to be helpful for you if you did find this video helpful please go ahead and like it and subscribe to my channel for more related content and as always if you have any suggestions please feel it please feel free to leave those in the comments as well so we'll see you next time | Max Consecutive Ones III | least-operators-to-express-number | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length` | null | Math,Dynamic Programming | Hard | null |
1,268 | hello friends today let's of search suggestions system given an array of strings products industry in search would we want to design assistance there suggests air to most story product names from products after each character of search water is typed suggested products should have common prefix with the search water if there are more than three products with a common prefix return the three lexicographically minimum products with a list of lists of the suggested products after each character of search world is typed so this problem should remind you of the design autocomplete system but this question is simple because it does not ask a word so today by their frequency they just want to sow to buy their lexicographic order so actually this problem is we needed to either rates as a search water and the for every prefix we check whether a product has the same prefix if yes we add their word that you are Canada to list them and they in the end if the list has a length greater than Sri we return the three lexicographically minimal so the brute force solution for the bees easy to find them we just to check every prefix and we generate the matching strings so how to achieve their goal one thing is that we can use our index of function in Java product index or prefix a prefix string Demmings but this product has the same prefix string um if it's more than three we get this first straight lexicographically minimum so that means we need - so - this candidate strings the I - so - this candidate strings the I - so - this candidate strings the I think the tree set is very good for this use we just use a tree set and for every matching string we put it into the tree set and in the end that we check whether the length is greater than 3 if it's greater than 3 we just return the first 2 3 okay so the time complexity will we can take a peek we first needed to iterate I from 0 to an and is the search length a search would at all s and then we'll get it's a prefixes string which is thus search water substring from 0 to I plus 1 this is exclusive and therefore every product will check whether the Protel index of a pre string is theorem and then if yes we add their product to the third so in turtle tank plastic be this one is a search word talents the m is a total number of the products and the list set is k times log k case the size of the set so interval is Big O in terms M times K log K ok but if you look carefully you will find some repeated and useless calculation see this example is the products I named a happy girl happier and the search word is happiness so we check from index 0 in this edge and the usual notice that girl is not matched with this edge in the time we check out once and therefore the h8 it can never match this girl and girl can never match ending prefix of the happiness so in this case if we use this algorithm we actually calculate the girl every time so we should remove this repeated remove this use calculation so once they have one characters that no matter we do not need to check this drink anymore in the future so we should avoid that you um compare this word choose our prefix anymore and because we needed to get to the lexicographically Smalley's to always so we can actually so to the products at first so we in this case we always get the lock lexicographically smallest and then we do the same thing we iterate the search world from zero to none and as this product is all already salted and based on this observation of duration we just check whether their character is matched with their character in the search word if it's not matched we just skip delwood so the simplest way is use two pointers is one name the low one them the high the low check from left to right the high checked from right to left but you should always make sure the index is valid so low should always be less or equal they are high and the products low tolerance should be greater than I what say if the eye is say if it is zero and if the proton load Arlen's equal to zero we can never get the products zero so yes that should always make sure the products lost lens is greater than I then we can get to the index i right okay then the products lot doc charged at is not equal to the social world either means we can never use these products low anymore so we just move low for water okay then this is the from right to left so in this case the products between the index low and the high are valid but we should always make sure there can at most be three products so we get a minimum of the low plus three because the law is valid and we can almost get us three so we plus three low +1 Laplace to the plus three low +1 Laplace to the plus three low +1 Laplace to the high plus one because high is also valid so if I plus 1 that means we can never like exceeded this a high so if it's less than three we should make sure hi is the largest one and then we add the law we added a valid products to the results at least okay so in the end the time complexity should be the big old K times n log N and is the number of the products the K is the maximum length of the ending product for this full loop this is an N in the length of the search word in a photo this two wire loop is just a linear and the complexity should be P Co mm is a number of the products so for this part in Turtles P : products so for this part in Turtles P : products so for this part in Turtles P : times M so in the end of that hand complicity should be K times M log in okay now let's write the code we first needed the result oh sorry just call your result in the array list and then we need to Lester and I will leave the two pointers zero hi also we need an Easter products product store length so the law is there are highs and minus one and the length is the search word tolerance does n 4 into I to 0 I less than length I plus we check whether it is valid so one thing is lost less oil causing high-end thing is lost less oil causing high-end thing is lost less oil causing high-end the we should make sure the products low tolerance if it's less or accordion I or Omega if we less than I or products low charge Adam I it's not equal then the search would charge Adam I shoulda moved law forward and for the right part if the role s all equally high and the products high talents less or equal than I or the search the products hi char at I not equal to search water chart yet I remove hi backward and now we get a valid a scope from low to high so get a minimum which you should be the low plus three and a high plus one this both of these two in two Indians are exclusive so for inter J from low j less the minimun j plus we should I get a list they call it array list and the Dell taste add the product J okay in the end we just a return result oh sorry this place result after this current the list okay I think I finished our answer yes it was I know do you find the back we actually do now so to this products so wish that you thought these products at first okay thank you for watching see you next time | Search Suggestions System | market-analysis-i | You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return _a list of lists of the suggested products after each character of_ `searchWord` _is typed_.
**Example 1:**
**Input:** products = \[ "mobile ", "mouse ", "moneypot ", "monitor ", "mousepad "\], searchWord = "mouse "
**Output:** \[\[ "mobile ", "moneypot ", "monitor "\],\[ "mobile ", "moneypot ", "monitor "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\]\]
**Explanation:** products sorted lexicographically = \[ "mobile ", "moneypot ", "monitor ", "mouse ", "mousepad "\].
After typing m and mo all products match and we show user \[ "mobile ", "moneypot ", "monitor "\].
After typing mou, mous and mouse the system suggests \[ "mouse ", "mousepad "\].
**Example 2:**
**Input:** products = \[ "havana "\], searchWord = "havana "
**Output:** \[\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\]\]
**Explanation:** The only word "havana " will be always suggested while typing the search word.
**Constraints:**
* `1 <= products.length <= 1000`
* `1 <= products[i].length <= 3000`
* `1 <= sum(products[i].length) <= 2 * 104`
* All the strings of `products` are **unique**.
* `products[i]` consists of lowercase English letters.
* `1 <= searchWord.length <= 1000`
* `searchWord` consists of lowercase English letters. | null | Database | Medium | null |
376 | hello everyone so in this video we are going to solve a question complete code it is because subsequence is 376th question read code and this comes under medium category all right so let's start with the problem statement a regular subsequence is a sequence where the difference between successive numbers is strictly alternate between positive and negative the first difference if one exists may be either positive or negative a sequence with one element and a sequence with two non equal elements are trivially biggest sequence all right so let's see the most important point here is strictly alternate between positive and negative all right so we cannot consider equal elements here okay and we need to find out the length of the longest wiggle subsequence okay so let's see the first example in the first example we have 1 7 4 9 2 and 5 all right and let's make a graph for this so that it must be more clear to you so let's see like in this we have one here and then we have seven so seven will go up okay in the graph then four will come to down somewhat here then we have nine will go up okay then two will go down then 5 will go up somewhat here okay so what we can see is this is increasing or we can say this is positive okay then this is decreasing so it's negative okay then again positive then negative then positive okay why we are saying positive negative because this is seven and this is one seven minus one is 6 it is positive and in this case 4 minus 7 is negative so we are just taking is negative all right so let's see in this example what we can say is we have alternate positive and negative pattern so we can consider all the elements here okay since we have alternate pattern of positive and negative so we can say all the numbers are satisfying the condition so we can written six as our answer as all the elements are satisfying the condition so we have six elements here and all the six are satisfying the condition so we can return six from here all right so what we can do is let's say in this we are returning 6 all right so i hope this example is creative let's see the second example to understand how we can take subsequence here okay so let's see in the second example we have 1 17 then 5 then 10 then 13 then 15 okay then 10 then 5 then 16 and then 8 okay and let's make a graph for this so 1 will be here then 17 will go up then 5 will come down then we have 10 okay let's this is 10 okay then we have 13 then we have 15 okay then 10 will go down then 5 will again do go down then 16 will go up then 8 will go down okay so what we can say is this is increasing and then this is decreasing then these three are consecutively increasing okay these three are consecutively increasing so we cannot take all three values like we need to take only alternate positive and negative we cannot take consecutive positive values here then this will go down and this is also go down okay so what we can say is we can take any one of these three so let's say we are considering the first one and not taking the remaining two similarly in this we are taking the first one and not taking this one okay and this is increasing and this is degrees so this is fine okay so what we can say is in this we have one element here this is the first one we can consider this is the second one we can consider this is the third one okay this is the fourth one this is the or we can say yeah this is the fourth one this is the fifth one this is the sixth one and this is the seventh one so total we have seven elements here those are satisfying the conditions okay we have just removed these elements from here or we can say we are not considering these so total we have seven here so we are writing seven in this case okay i hope the example is clear to you we are just considering the alternate pattern of positive and negative values or we can say the up and down pattern alternating up and down pattern all right so this is the second example i hope this is clear you let's understand the approach and you know how can we approach this question in the optimized way so let's say we are storing the values in then however we can take the values in the variables as well so let's see let me first clear this yeah so let's say we have two variables here okay so the two variables are let's say we have up and second one is down okay we have two variables here and we are storing the values in these two variables okay so let's say for the first element it can either go up or it can either go down so what we can do is we can consider both as well okay there are both possibilities so we can consider both the values as well okay now unless we have up okay the next one we have up so we will update up with two the down will remain same okay now let's again we have down the next one we have down so what we can consider is the previous one must be up that's why we are getting down so what we can do is whenever we get down we will just update that down with a plus one okay so this is down fifth one is down this five one is down so we will update this with a plus one so this two plus one is equal to three and this will remain same okay now we have up so whenever we get up we consider that the previous one must be down so what we can do is whenever we get up we will just update up with down plus one so this up will update to three plus one that is equal to four and this down will remain same now again we get up so whenever we were getting up what we were considering that whenever we are getting up definitely the previous one must be down okay so whenever you were getting up you were just updating up with down pressure let's update this up with three plus minutes equal to four and this three will remain same again we are getting up let's update with down plus one three plus one is equal to four and this will remain same it is three okay so we can see here that these three values are same why these are same because this is strictly increasing okay so we are not considering these two values here that's why these are same it means our logic is correct all right so let's see for the next values this is down okay this is down then what we were considering we are considering that if we are getting down then the previous one must be up so what we were doing is we were just updating the down with a plus one so let's update down with up plus one times four plus one is equal to five and this up will remain same again we are getting down this update down with a plus one that is five and this is four okay now we are getting up so when we were getting up we are just updating down plus one so up will be updated two down plus one to five plus one is equal to six this will remain same now we have down so when we were getting down we are updating with down uh plus one so this will be equal to six plus one is equal to seven and this will remain same okay now the creation of the complete a is completed at the end we get two values up is equal to six and down is equal to seven okay since we need to return the longest value so we will be returning the maximum out of this so maximum out of six and seven is seven so we are returning seven from here okay i hope the approach is clear to you if you still have a doubt in this approach feel free to comment it down i will try to explain it again let's move to the coding part so yeah let's take two elements here and up is equal to one and down is equal to one all right now let's send the for loop for end i is equal to one i should be less than nums dot size and i plus okay we can write one more condition here if let's say if num start size is less than two okay if less than two there might be only one elements let's try to return one from here okay so now let's write the few conditions for updating up and down so what we were doing is if we were getting the highest value or we can say we were getting the up here so what is the condition for up let's say this is 7 and this is 1 in the first example so condition for this is let's say that is nums this is nums and this is i minus 1 okay this is nums i minus 1 okay similar condition let's write it here we are just subtracting all the values and we are getting the positive value okay so what we can write it here let's say if nums of i is greater than nums of i minus 1 then what we can do is we can update up with down plus one okay and else if you are getting numbs of i let me write it again um it is num that we are updating up with down plus one and in the next condition else if nums of i is less than okay the next condition might be it is seven and we are going down so this is four in this condition this will come negative okay so or we can say this one is less than this one so what we can write it here if nums of i is less than nums of i minus 1 then we can update down with a plus one okay at the end just return maximum off up and down all right i hope this is fine let's just connect yeah it's working fine let's just submit this yeah it's perfectly fine so let's calculate the time in space complexity of our solution so time complexity of our solution is big o of n since we are trading through all the n elements and space complexity of our solution is big o of 1 since we are storing constant spaces here and this is basically the most optimized approach to solve this question i hope that project solution is clear to you if you still have any doubt in this question feel free to comment it down please like this video and subscribe to our channel i will see you in the next video you | Wiggle Subsequence | wiggle-subsequence | A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative.
* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`.
**Example 1:**
**Input:** nums = \[1,7,4,9,2,5\]
**Output:** 6
**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
**Example 2:**
**Input:** nums = \[1,17,5,10,13,15,10,5,16,8\]
**Output:** 7
**Explanation:** There are several subsequences that achieve this length.
One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8).
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6,7,8,9\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
**Follow up:** Could you solve this in `O(n)` time? | null | Array,Dynamic Programming,Greedy | Medium | 2271 |
834 | Meaning, you will be able to understand it completely from top to bottom, it is ok to make it so easy, so what is there in this question, basically, we have given you notes from zero to and minus one, ok and you have made its graph in it. Okay and how is the graph made, so I have given the same errors, so what is given in it is that N - 1 is today, okay there is an entry and so if we have understood this much then we can understand it from the question. That zero to van should not be done, it is ok for us, now what has to be done in this, we have to get the decision of all the other notes from each note, ok then what will be the answer of zero, its distance is van, its distance is done. If the distance is fine, then you can ask this question, then look, do you know the answer? Sub tree of I am saying that now if I am between these two, then what will be my answer? Okay, then there will be a plus in these, whatever it is, this will add up to this point, and this will add up to this point. What will happen from this, if we look at this later, the answer will be 'A', 'This' and ' answer will be 'A', 'This' and ' answer will be 'A', 'This' and ' This' are ok, and if this one is left, This' are ok, and if this one is left, This' are ok, and if this one is left, we will have to add 'A', so we have added one more, we will have to add 'A', so we have added one more, we will have to add 'A', so we have added one more, ok, then this will be my 'X', the answer will be ' then this will be my 'X', the answer will be ' then this will be my 'X', the answer will be ' No' What will happen, then how many notes will be there in my software? This is my answer of Sub tree of same will be added ok answer of same is equal you if both of these are submitted then count of same minus count of What was this, when there was no engine in the middle of Indore, then the answer of both of them was that it is okay and what do I do on account of this, now this formula of mine is gone, now what am I of if I know this, okay? There is every sub tree but you will say how to get its account, then I want this one's software, then this one's software is ok, then what will I do, if I withdraw N- what will I do, if I withdraw N- what will I do, if I withdraw N- account of I can make anyone a root, I am ok, all these from zero to n-1, I have made notes, right, zero to n-1, I have made notes, right, zero to n-1, I have made notes, right, I can make anyone a root, so I have made zeros a note, so what am I doing now? Where am I calling DFS from, I am calling from zero, okay, U will come, open will come, okay, I will take the account as global variable, so what will I do now, okay, I will go to all of them and do it, he has an account, right? This will come in the condition, all this then I will close this condition and here what will I do about the account plus one function as we went to this from here so it called this okay then how much will this factory account become lol Three, then I am doing plus one, so what will be the account of It will be done, it will be removed, okay now what did I do with my account, I removed all the software from its account, now I go back to the A in my formula which was answer of I can go out by account, how can I go out, I have N - count of Okay, man, take my point, I have the answer to it, what will happen in this case, it will be 12 Sex, so take this man, I know it, I know the answer, 12 Okay, so I know the answer. What will become of Okay, its answer is out, whatever its answer is, it is okay, so now I say that I know the answer to the root, I know their answer, so I ran it from FS route, okay, so I ran it for it and its What will be the answer of children? What will be the answer of this? Once the answer is out, what should we have known? We should have known the answer to the bus route, so now we can get all the answers. By applying another DFS function, we will get the answer to the bus route. We had to fix the question. Now we will get the answer to the route. Let's find out the answer of the root. Just add another DFS function. There is nothing to be done in it. We can find out the answer of this root and we can do the answer of the root. If this formula is fine to get the answer of all the roots then root To get the answer of this route, I have told you that you will not have to set up a separate DFS. Okay, when you are getting the count, you are getting the account of all these people, then I can get the answer of this route. Okay, see how, let's go here. This is the function of our account, so what do we do in it, so what do we do in this, we add this line, we create a sub tree of you, one by one named saptari here, just like we had created the error with n0 account. We all have to make a trick, okay, we can get out in any way, okay, there is only one note, we have to get the answer of zero, okay, then how will we get the answer of zero, then what will we do, okay, then what will happen to the account, this is all tree of U Plus Software Only one zero will be left on it, okay so this zero is left this is also left on zero, now it will return, so one will go left this is also left on zero, now it will return, so one will go left this is also left on zero, now it will return, so one will go on this, okay, so this is done for one number, then what do we do in it We will add that it is for this number, what will happen to it, everything will be free of express account of X plus account of The answer to the route to withdraw the account, now what I told you here is fine, then you will call, we will put this formula in it will run, it will be fine, please subscribe to the channel, also like the video and comment. Down meet if you understand, you can use me. If you want to get the answer of the root, you can also use BFS. If you want to get the answer of the root, we mean basically the answer of the root person is fine. What route have I taken, if it is zero, then I will root you call me. Please like the video and tell me in the comments how you liked the video. | Sum of Distances in Tree | ambiguous-coordinates | There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\]
**Output:** \[8,12,6,10,10,10\]
**Explanation:** The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer\[0\] = 8, and so on.
**Example 2:**
**Input:** n = 1, edges = \[\]
**Output:** \[0\]
**Example 3:**
**Input:** n = 2, edges = \[\[1,0\]\]
**Output:** \[1,1\]
**Constraints:**
* `1 <= n <= 3 * 104`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* The given input represents a valid tree. | null | String,Backtracking | Medium | null |
1,833 | Hello viewers welcome to the video desi ghee sub heading today bhi us here problem Dard ko maximum ice cream 2210 boy want maya is cream and let's start with example suggested to ₹ 90 cost start with example suggested to ₹ 90 cost start with example suggested to ₹ 90 cost cutting 12345 volume maximum number of ice cream tu laut aa mein ice cream But center costing take yes ok list cost ice cream bad taste with logic get list costing ice cream words to admit it properly it is the first of all we can keep sharing and the year before more money than the cost of screen so let's Go to the Next Time SMS OnePlus One Two Increasing The Amazing Love You Too Two Your Sandal Spent All The Amount Of Election Not Be Any One Of Them Are Evil Returns This Particular Country Will Return Service Four Wheels Boil This Point Cream Broadcasting 120 Hungry Just Another Example 16 Maz All And Let's Take Another Example You Understand But I Don't Like This One subscribe And subscribe The Amazing Black Subscribe Button Subscribe And Bull Icon Pura Ice Creams For Plus Two 6 And Count And Wellcome Equal Sinking Boat This Time It's You Who Tried To Go Ahead With Gold 70 Years Not Don't Forget To Subscribe To The New York Times - 1000 And 500 - 1000 And 500 - 1000 And 500 Hai Laptop Dietitian Point Is Equal To Zero ireland cost size plus get rich from it and subscribe my channel what is the full form of be coming late - 121 pylon and serious working status female president election commission on | Maximum Ice Cream Bars | find-the-highest-altitude | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108` | Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array | Array,Prefix Sum | Easy | null |
132 | hello everyone this is your a real world and today I'm back with another series of lectures so I've seen people finding it really hard to solve palindrome partitioning problems which are basically solved by DP so I mean this coming three four lectures will be discussing all the palindrome partitioning problems which are again the hardest problems of leadcore today I will be discussing this palindrome partitioning 2 which is problem number 132 of Utah let's read the question first given a string is partition s such that each and every substring of the partition is a palindrome and we need to return the minimum number of cuts that are needed or the panel of partitioning let's take this example a be okay a B this is string and I need to make cuts such that each and every substrate is a palindrome so suppose I make a cut here first cut so he is a pen in room but a B is not so I need again need to make more cuts in this so this is the only cut which is possible so there with three different sub strings which means there will be two cuts but this is one movie if I make a cut here then a is also padded room and B is also palindrome so this substring in this option both appellate rules so the minimum number of cuts that could be added is 1 let's take one another example suppose the string is a so this string is itself a fan in room so no cuts is actually required so the answer is 0 so I hope you have got this question you understood the question now this needs to the algorithm but before moving directly to the algorithm I would enough to request people to pause this video and think of any of the solutions beat Rufus written by recursion by DP just give it a shot pause this video for once and give it a fun ok I who you people have taught this so let's move to the question how we'll solve this okay first of all if the string is suppose a 8v this is the string so I can meet let's take a bigger string not if bu AC B suppose this is a string okay and now so I need to find that you know how many cuts are there so what would be the brute-force approach the force the brute-force approach the force the brute-force approach the force approach would be take make any one cut from the beginning beat her beat here and find the number of cuts in the remaining substring to make that substring palindrome suppose I make a cut here so I need to find how many minimum number of cuts do I need to make a CD so that and maybe also so that this substring and this sub string is a palindrome I can make a cut here as well so in that case I'll find this substring and this substring I need to find so basically my answer would be cuts in substring 1 plus substring 2 plus 1 good right so how could how can you use recursion in this how can we use recursion so suppose this is the string write a b a c d and i make a cut here okay then it decided and pass it on to the recursion this whole substring then this substring decide who make a cut here so this substance would be calculated the number of person this substring would be calculated take another case ie B is C B take another case in the second iteration I'll make a cut here so this substring would be passing the wreckage and this substring will again make a cut here so you can see that a CD easily the number of cuts here and here are calculated more than once so we can save the time there why to calculate it again in a.m. write it again and again then we in a.m. write it again and again then we in a.m. write it again and again then we can save the answer and we can save a lot of time so we'll do the same thing we do the same thing so I think we have got the coach right we have got the approach so suppose I maintain an area which will contain the number of cuts in the remaining substring so for this index which is equal to 3 which is like a third index I will maintain how many number of minimum number of cuts are required to make a CD a palindrome a CD you know partitioning a CD so that each and every substring is valid room for index number to L so how many men minimum number of cuts are required for making each and every substring of BAC be a palindrome well I guess we should dry run one of the example right because when I am a-b-c-d suppose I am working when I am a-b-c-d suppose I am working when I am a-b-c-d suppose I am working for this and assume that my array is filled with for these three integers my array is filled for these three indexes so what are the possibilities so suppose I start from this index only my start is this and my end will move from this index to the same mix so in the first iteration I check whether the whether my substring from starting to ending is a palindrome or not affects a palindrome then in this case it is because b is a palindrome so I just need to find how many cuts are required in a CD which is obviously stored at the same then I can shift my end by one which will this in the next titration I can check whether B is a palindrome you not know it's not a palindrome so there's no point partitioning at this now I again move my index to see BAC is obviously not the palindrome so there is again no point partitioning here be a CD is also not a palindrome so there is no point partitioning here okay so but with my minimum answer for this index would be partitioning here plus new number of cuts required in a CD right suppose I am working for this index again my start would be here my ending would be here I'll move my end by one from this index till this index I can make a cut here and I can find with the number of minimum number of cuts required to make this into panin roots which is obviously stored at this index then I can decide to make a cut here which will again so you can see it divided it in it basically decreased the number of cuts good so they're less an answer lesser number of cuts required in each and every nitration so I guess you must have been here with this algorithm we can move to its drier obviously so let's start from the last index ID if this is the only sub array the number of cuts required are obviously zero now let's move to this index which is CD so in the first iteration I'll make a cut here so making one cut is one plus the number of cuts required in the left sub which is d is zero so the answer would be one initially in the first iteration but again in the next iteration my end would be here CD is not a palindrome so one is the answer for sub-string or CD now a CD listening to a sub-string or CD now a CD listening to a sub-string or CD now a CD listening to a CD my first cut would be here my second cut would be here my third hood would be here for the first cut my answer would be one I am making one fight and for the rest is one so the number of cuts would be if I make a cut here I need to first check that whether a sees a palindrome or not it is not a palindrome so we can't make a cut here now I make a cut here and check whether this is a palindrome or not you see these are they're not a pageant room so two coats are required now let's move to be a CD okay I make a first cut here check whether this is a pattern of course this is a panic room so the number of cuts required in ECB is two so the number of cuts in now is three my Elwood means by one index which is this will check that the B is a final no it's not a palindrome so I'm moved by one BA sees no be a CD is a palindrome no so now let's work for this index and partition here first a is a panel room so the number of minimum cuts required for be a CV is 3 so the answer would be 4 I check for my n would move by 1 which is a B is not a palindrome a be a now a B a is a palindrome so I can make a cut here and how many cuts are required in CDs one cut is required so clearly the answer is two for this index 2 now a BAC is not a man in a be a CD is again not so best possible answer for this index is similarly we can do for this also this index also and what will be my answer would be suppose this area is arr so it would be error of 0 because I need to find how many cuts are required from this index 0 I hope you have got this algorithm and dryden so I think we should move to the poor let me explain you the code yes okay so this is basically the function how you can check whether a string is an in room or not between any two given indexes okay this is a very small video do not hit this I have mentioned a link in the description you can watch that video - you can watch that video - you can watch that video - you check if the given string is a palindrome oh not good I am maintaining a DP array this is my initialization I am initially initializing each and every index with int max because definitely the answer is all the time int max you can initialize it with minus 1 also okay for my last index unsterile obviously be 0 because this is a single element if you remember just now we did an example maybe a CD so if this is the only substring of length 1 string of length one should always be see you okay and if I have a empty substring empty string my answer is also 0 so I made basically once I is greater than the size of swing my DP is one size greater than the size of string so if the string is empty then also my answer would be 0 so I have started with my loop has started with second last index which is here and it is moving I have taken a second pointer which is basically an pointer denoted by G which is going from ayat index in the end so every time I am checking if first if the given substance is a palindrome it means I can make a break here I can cut cap so every time it is important to check now second important check if suppose this is the string and I'm working for this index I make a cut here so how many minimum cuts are required basically this is no good this is pseudo cut because it is outside this room so the answer is obviously zero because it this completes string is a palindrome so this is what I am checking if G is equal to my last index and my string is a palindrome so basically new cuts are required so this is what I have done that it would be straight away zero otherwise it would be one because I'm making a cut hair making a cut and Plus suppose I am working for this index and I am making a cut here so this would be G Plus Ones index because this is I this is G Plus first index so er R of G Plus 1 and straight away we can change dancer because if this is the this is minimum or this is lesser than the parents for dancer we can shift on and at last I have returned my answer so I hope you have caught this video I would like to request everyone to try this problem for once and if you have any kind of doubts you can ask me in the comment section below I would be really happy to answer them so thank you so much if you liked the video you can hit the like button and subscribe myself thank you | Palindrome Partitioning II | palindrome-partitioning-ii | Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**Example 2:**
**Input:** s = "a "
**Output:** 0
**Example 3:**
**Input:** s = "ab "
**Output:** 1
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters only. | null | String,Dynamic Programming | Hard | 131,1871 |
1,615 | hi everyone it's Oren today we have a problem when we are given a when we are given CDs for example in this case we are given four CDs and Roads which means that the connection from one CD to another so for example CD Z is connected to cd1 and the three cd1 is connected to cd2 right and the cd1 also connected to CD3 so in our case what we need to do we need to return a maximum Network rank so what's a network rank Network rank of Two Cities is defined as a total number of the directly connected road to either City so for example in this case the maximal network rank for CDU let's say zero and 0o and one is equals to four because there are four roads to one it's one and two to cd2 and to CD three and for Z it's uh for to CD3 and cd1 and also if the road is directly connected to both cities then in that case it's only counted once so for example in this case if we calculate the netw rank for all cities the maximum one is for the zero and the one which is four okay uh let's take our previous example and work on it so we have four CDs CD 0 1 2 3 and the roads that are connected to them so what we are going to do the first thing that we are doing here we are creating a hashmap with the key is being the road with the key is being the CD and all other CS that are connected to that for example to CD zero one and two is connected right so to CD one is 0 two 0 2 and cd2 and three is connected and for cd2 cd1 and for CD3 zero and one then after that what we are going to do we are going to go over each pair for example for the 01 02 03 1 2 and 1 3 and we are going to calculate the network rank for them and if we see that for example in this case right let's take the for the zero and one if we see that either zero contains one or one contains zero so we should not uh count the same if they are if the connection is be directional it means that we should count it as one by requirement right so in that case what we do we are going to subtract from our sum that value for example for C CD 0 and one right so for CD 0 and one we are taking the size of our value in this case we have two cities that is connected to zero and three cities that is connected to one so 2 + 3 gives us five connected to one so 2 + 3 gives us five connected to one so 2 + 3 gives us five right and since Z contains CD 0 contains cd1 and cd1 contains it zero so it means that the connection is B directional so in that is we are subtracting one which gives us four okay uh first thing that we do here we are creating a hashmap let's call it connected CDs and then we are just initializing for each CD and for the value we are choosing to use hashset because in this case the lookout would be constant so then the next step is we are going over our array roads and for each connection right let's say that the 0 to one so let's say that the CD 0 is connected to cd1 or cd1 is connected to cd2 it means that the cd2 is also connected to cd1 so we are adding for each let's say that the for cd0 we are adding cd1 and the for cd1 we are adding cd0 after populating our connected CDs what we do we are creating a variable Max rank that we are going to return and we are going over our CDs and for each pair we are calculating the total Network rank right so total Network rank is the network rank is of the first CD and the network rank of the Second City if there is any if the CD One contains CD let's say one and two right let's take example of CD one and two if the CD One contains cd2 it means that the directional is they are this is it's B directional so in that case we are substracting from our current rank we are substracting that value we are subtracting the value because we should not count the same rank twice and at each step we are just updating our maximum rank so we are taking the whatever the maximum rank we had and our current rank so it's the time and space complexity of this solution so time complexity is we are using these four Loops gives us n Square so because 4 and four and we are taking the upper Bond so our time complexity is n square and the regarding the space complexity is determined by our hashmap in our case let's say that the worst case scenario right every CD will be connected to every other CD so in that case space complexity also will be n Square okay uh that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye | Maximal Network Rank | range-sum-of-sorted-subarray-sums | There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**.
The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities.
Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_.
**Example 1:**
**Input:** n = 4, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\]\]
**Output:** 4
**Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
**Example 2:**
**Input:** n = 5, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\],\[2,3\],\[2,4\]\]
**Output:** 5
**Explanation:** There are 5 roads that are connected to cities 1 or 2.
**Example 3:**
**Input:** n = 8, roads = \[\[0,1\],\[1,2\],\[2,3\],\[2,4\],\[5,6\],\[5,7\]\]
**Output:** 5
**Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
**Constraints:**
* `2 <= n <= 100`
* `0 <= roads.length <= n * (n - 1) / 2`
* `roads[i].length == 2`
* `0 <= ai, bi <= n-1`
* `ai != bi`
* Each pair of cities has **at most one** road connecting them. | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. | Array,Two Pointers,Binary Search,Sorting | Medium | null |
1,971 | hello welcome back today let's try to solve another lead good problem 1971 find its past exists in growth this means we are giving a graph yeah the component may be connected or may not be connected what we're going to do we first needed to attack if we have a source like this number one to a destination like this number two if they are connected or not if they are not connected we're gonna return a force for example this is a 0 to 5 they are not connected and in this example 0 to 2 they are conducted so how should we solve this problem we can use the DFX and BFS of course but for this problem it's a very template problem to practice unified because Union fat is a very good algorithm to calculate the connected component because it is just needed all in time to tag if this component connected to this component so here the on I mean it takes the time for building the union father array yeah now let me go to the Whiteboard to explain a little bit about the unit fat then go to the code Editor to finish my coding foreign yeah as you can see from here this is a something I prepared to our example so for this example I'm only going to prepare zero to one to two so this is a zero connected to one connected to do and this graph is also undirected by directional yeah it is a bi-directional directed but it does bi-directional directed but it does bi-directional directed but it does matter so it is not connected with what's going to circle the source is a zero the translation is two if they are connected or not of course they are connected but how should we use as a union file for unit 5 I'm going to use a union file array so this is a unit file array so inside it will be the numbers from 0 to 2 because there are only three nodes and the representation of nodes is started from 0 to n minus 1. this is why we will keep it exactly the same because the index is also 0 1 2 and our node is also zero one two this will make the catalysts much simpler further unified template so this is the first step we're gonna Define this UF array so for the Second Step we're going to Define this file function so what is the meaning of the fund function basically the union file is to check the component if they are connected or not the unit fat is a tree structure it's a three data structure from the beginning we're going to prepare these three naught zero one two and they are not connected as you can see here 0 1 2 this means the index from 0 1 2 they are not connected then we continue fight if we don't do any Union for edges if we use the file to tackle fight zero it is a zero because we just set the UF array inside the UFO really index 0 it is still zero for index one it is still one yeah if we don't do any connections so the unit Spotify function Phi zero it is a zero because zero is apparent not and one is also the parent node and two is also the parent node itself because there's only one knot now we're gonna to use Junior after we finishes the union we're going to use the fight let's do the First Union zero to one after we finish the First Union zero to one if we're gonna divide 0 as the parent so the one will come to here as the child of zero because as I said the union file is a tree structure and all the components will be a forest it means a number of trees and now for this three the parent is a zero as a child is what because with data unit for this 0 and 1 then we're gonna do unit for one and two so if still one will be the parent two will be the child so two will come to here yeah so they are not here anymore one two will be here and there now we're gonna adjust the SEC 0 to 2. because after updating the union inside the DF array so for the index one it will be 0 and index two it will still be zero now we exactly gonna return the UF yeah you have sauce and UF doesn't it means we're gonna do the fighter zero and fight two if we do five zero it is still zero as you can see it if we do five zero it's parent it is a zero if we do a five two from two we know it five is the two side of the parent so the parent naught is zero so zero equals to zero this is why we're gonna return two also we can start inside the union final array it is a zero and zero now we can directly use the five now let me go to the code Editor to finish the unit file template and then if you understand the unified basic algorithm then you can directly use the template to solve any unified problems in this code as I said for the unit file I'm gonna Define a UF array so inside it will start from the not because the node will start from 0 to 2 and -1 so here similarly I will Define and -1 so here similarly I will Define and -1 so here similarly I will Define my naught from zero I for I in Ruins for I invoice this means for this example the node will start from zero to two now I'm gonna Define my and file function file will be a number and after that I'm gonna Define the unit function the union will be two numbers means two naught and one and two let me first finish the five and then finish the union so for the five we're gonna just need to attack because I'm going to use a recursive function let's talk if you have a not equal to l it means if we are going to use a number to find its parents if they are not equal it means we have to recursively call this five so the file inside of course it will not be anymore because we find it and it will be ufn Union fighter finally if they are equal it means UF is equal to it means the index equals to itself we just gonna return policer and you turn this number and yes this so this is the file let me give you an example for example we're gonna find zero one two so if we adjust the 5.0 at the zero in so if we adjust the 5.0 at the zero in so if we adjust the 5.0 at the zero in that it is still zero we don't need to do anything because you have zero equals to zero what we're going to return we're gonna start to return zero because Zero's parents is itself it is a zero if we're gonna find one they are not equal to uh unified yeah if we first find one it is a still one itself now let me do the Union function so for the union we first need to put a the two nod connected the two naught is coming from the edges the two numbers like zero and one so for the union we just need to do the UF find this uh let me put the N2 as a child and N1 as parent so it would be 5 and 1. so here 5 and 1 means I'm going to find the parent of N1 for my example if I'm going to find another two experiment is zero so it's gonna return a zero if I'm going to five zero itself it will still be the zero yeah so this unit means I will put my node 2 below the zero and two will be connected after that I just needed to yeah uses the union to connect to the component so for UA in as this I'm going to Junior and one and two yeah for this operation it means all those nodes will be connected yeah and deserves our parents like a tree structure as I explained in the Whiteboard now let me go to the Whiteboard it will be something like this is the data structure so 0 will be the parent and one will be the child and two will be the child over one it will be like this so after that we just gonna check if fried Source equals to 5 Union the five source is equal to zero for the Destination 2 is also zero as you can see the union final has already updated to zero so finally we just need to return if it is a true or false so we're gonna find source equal by the union without need to do tax the fighter destination yeah so the file Source equal to 500 destination we just need to attack if it is right on wrong now let me run it to tag if it really works so there's some typos and one is not defined versus my own one yeah here is U and the way I'm just need to Union this UI way from here it's a typo for me I didn't think about this address it's the yeah as is for you anyway after connecting all the answers I just need to talk if they are connected or not I just need to use file to tag and by the way this is our own algorithm and also the space complexity is also because we need the unit file array and once we use the unit outside it is a successful one calculation and also for here in such as it means how many edges we have if we have an address so finally the time complexity will be on if the edges is much bigger than the vertices now let me check how many edges are there so for the edges it is the two times the 10 to the power of 5 so this means this is a 4N so the time complexity is for o and for this one thank you for watching if you think this is a helpful please like And subscribe I will upload more lead code problem like this see you next time | Find if Path Exists in Graph | incremental-memory-leak | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. | Simulation | Medium | null |
1,318 | Hello everyone welcome to my channel with Mike, so today we are going to start a new playlist of beat manipulation and please note that this is a playlist of questions, here I will teach and explain the questions and a playlist of concepts of bit manipulation will also come in the future in which I will tell you the concept but how I approach the questions will be the important thing, first it will be only on the questions but do n't worry, it is not like that if you have not studied the concept then questions will not be asked, it will be explained in such a way that without the concept you will understand a lot. Basic concepts are based on it but I am in the playlist and sorry neither are the questions mostly based on it. Ok so let's make the first question today but I have the lead code number of PlayStation 1318 medium but I will give tuition when I build it. From there you will understand that this question is going to be very easy, okay and we will make it from two approaches, the first approach and the most basic approach which will come in our mind, which you should make in the interview, I will tell you first and then We will go to the second approach, the name of the question is Minimum Phillips, you make A and B equal, you will be given an interior, you will be given an integer named B, and you will be given an integer named C. Okay, this is telling you, let's see in the question here. Before Microsoft asked this question, give a question to understand what is the question. Look, pay attention, give three positive numbers, you have ABNC, now you have to say, minimum, how many philips will you do in A or B, if you get the true date A and B then that. Minimum number of flips will be equal to C. Okay, so it is best that brother, let us understand it with an example. Here it is given that a2 is b6, c5 is given. Look, what is A given here, what is B, and my K is given. Okay, so pay attention, it's an obvious thing like I write here zero, make this zero and B one or you can flip both of them but I have to find the minimum, how many minimum flips will you do and you know. Key and I, if there is one, then the answer is one, A. Okay, so one flip is done here, I have to keep count of the flips here, one clip is G here, okay, we have solved the problem of the first beat. We will have to do a clip of Diya. Now let's come to the second beat. C's here is zero. Okay, now you obviously know C and when we get zero in the operation, when can we get zero when both the beats are both zero. It should be right, okay, so look here, what is this beat of A, it is one, that means one has to be flipped, this one of B is also flipped one, so one more flip has to be done, okay, so this is my zero, then it will become zero, right? So I tell you that you will have to flip both of them, I have flipped both of them, it's okay in zero, now the answer will be zero, so this problem is also solved, okay now let's come to this beat of C, this is one, okay so one. For what I said that at least one beat should also be one then the answer is one and in operation it is zero, no problem it is one but ok so what do we have, if we get one already then one There is no problem, here we have already one, so we don't need to flip, so this problem is also solved, okay, this is 00, let's leave it, so the answer is 3, we will read to flip, see, the answer is our three, okay So if you look at what I have just explained to you, we are trying it one by one, first we saw this beat and then we saw this also, so actually this is our most basic approach and we will keep comparing. Okay, now it has come to the point that each one Let's see the beat, how all those tricks are, first of all I will tell you, okay, the basic things that you should be aware of, right, first of all brother, if anyone has given you number one, zero one, mother. Let's take it and you have to find out what is its right most beat. Okay mother, let's take it, there is nothing to do with it. You will do A and one. Otherwise, you know what will give it. What else will it give the right most beat? What else has to be done with one and one. It is okay, let's send one, it's okay, the rest will be zero because these are all zeros, so you see right most beat, one came, that means it must be getting made, right now mother, let's take an example, what is it, I What will I do with one and then I will get 100, okay that means the right most beat will definitely not be zero, okay, so this thing keeps you in mind that brother, how will we find out which is the right most beat, okay and I have added one more. One more thing you should learn is that if you have to shift, like Maa Lekha 1001, it is okay, so I was saying that if Maa Lekha, you have to remove it is okay, Maa Lekha, you have reduced this beat, then you have to remove this beat. So hit right shift, this is ok, so hit right shift, what will happen, this zero will go here, this one will go here, ok so what happened, zero one will go to a, and then zero will go to a, and what is ok, this is what happens And I will also show you how to shift right, it is very simple, where you go right there, give it = go right there, give it = go right there, give it = how many times you have to shift once, you have shifted only once, right, so these are two important things. Keeping you in mind, it is okay to solve this problem and I am repeating again that you do not need Ratan, all these formulas are not right, Ratan, right, you are an example, that is why I showed you an example, let you understand why and By doing one, we are getting the right most beat, it is okay, that is more important, till now it is clear, so we have understood both these things, now we are ready to make the question, okay, so let us start the solution of the question. Let's definitely start. Look, intuition. Already, we have done a little build that we will move on by comparing the build by beat. Okay, and we have to note down this thing and keep it. I am still doing it. Ratan, don't you have an example of this thing? Take any example, take it from one and extract the operators. C has to be written a little separately. Our 5 is 101. Okay, so let's start weight by weight. So, first of all, what I said was that we will check the rightmost beat of all three. Okay, so it is C. Look, is it one? Okay, so how will you find out the right most beat of C? We will do C and one. If it is equal to one, then it means which is the right most beat of C? Then we will apply IF and check like this if If there is right most but one then it is okay then one so if this time there is only one then what I said in one that if both are zero then it is okay then I will definitely have to flip at least one because what happens in the else operator That is if there is one Okay but look here how both of them have zero but we need one okay so what we have to do is we have to band one of them, we have to flip minimum so I can flip only one. Okay, so what will I check here, I had checked earlier, remember that if the right most beat of C is one, that means we need one, okay, then what will I check here, if the right mouse beat of A is zero, okay? Both are zero, one has to be flipped, so this condition is understood that if the right most butt of C is one, then it is okay, I erase it is cleared for us, okay, now let's move ahead, this is the science of our beat. The tension is over, okay, what will happen if we shift, it will disappear, so I will erase it completely, it is there now, I will make it easy, okay, now see what we will do again the rightmost beat will come out. Again we will check the same thing, is C and 1 = 1 or not? What is the meaning of C this time? If there is 1 = 1 or not? What is the meaning of C this time? If there is 1 = 1 or not? What is the meaning of C this time? If there is zero on the right side of C, then zero will come once. Okay, so understand what to do in zero. Okay, now see what I told you about and operator. What happens if any one band, whether the first one or the second one, becomes one, if any one band becomes one or both become one, then the answer is one A. Okay, but look at us, what do we need here? What is required is zero, so when does zero come to make it zero and in the operator, when both are zero, then if any one of the two becomes one, then there is a problem, we have to make it zero by flipping it, so here But you see, A, B is one and B is also one, okay, so what will we do, we will check, then we will have to do plus because we need zero, here we need zero for C, so both will have to be zero, okay. So I again did plus one, this is also cleared, so if our Bitcoin is finished then it will be finished, it was flipped for B too, so it is flipped twice here. Okay, now coming to the last one, let's see, right most but one will come, this time C's okay, so right most beat, if there is one, then the same condition A will come, brother, there is at least one, then means if both are zero, if Brother, if both are zero then we will have to flip. When the right mouse beat of A is zero then only we will have to flip because if both of them have zero on the right then the answer will be zero A and if but we want one then it is ok here but here both There is no zero in C, there is one, so we do not need to flip because its already and operator will come only one and this is already one, only one is needed in C. Okay, so now that means this beat will also end less. If we hit right shift on these too, then now if we hit right shift, then the sir number itself will be destroyed, right, this will also become zero, so we will be taken out of the A loop, so if we pay attention then wild look. What will work if A is not = 0 or B What will work if A is not = 0 or B What will work if A is not = 0 or B note is equal to zero or C note is equal to zero till then it will continue, any one will be non-zero, meaning we have to keep going, be non-zero, meaning we have to keep going, be non-zero, meaning we have to keep going, now all three have become zero so it should be water. This too will be burnt, this too will be burnt, we must have removed the file from the loop and it has been supported in our flip. Look, the answer to this is 3. If we look at it, then the breakdown of this question is only these two things, so today's first video. In this, we have learned a very good thing that how to do right shift and how to get the right most beat. Similarly, in the video of bleaching every beat, I will tell you one thing after another like this, keep on posting notes to all of you. And I repeat, never do Ratna, while solving it, the masala itself will be stored in your brain memory, right, but Ratna Nahi, sometimes, okay, while practicing, it will get stuck in your mind that yes, by doing this, the right most bed comes out. And by doing this, the right shift occurs. Okay, so this one is the easiest. Our weight by weight, we were calculating it by comparing, okay and we have used the and operator very well. Here, first let's code it and you will You must have already understood the story that what we were doing was beat by, so how if that story is point one, what I said in this is that IF A's right mouse beat will also be zero, then neither of both will be zero, then A will be zero. But if we want one, then what we have to do is that at least one person has to be made one, right here in date men, you will flip one to one person, meaning what have you done, if you have made one, then the answer will be my one, which is what we need here. But it is okay for C and if C's flip here, look at this if right most B, if it is zero should be required and B's also right most this zero should be zero, then it means if A's right most beat, if it becomes one, then still make the flip. It will be necessary because if we want zero, then it is good for both of them to be zero. Okay, so with just these two story points, our entire question will be solved, so let's code it and solve it first, so here. But we write the interplays this is equal to zero and till when A note is equal to zero or B note is equal to zero or C note is equal to zero if any one is non zero then this loop should continue right if all the three are zero. Done, then people should be a band, okay, so remember what I said earlier, what was the story point, that if C's is the right most beat, if that one is, then okay, if its one is the right most beat, then what I said is that For that, it is okay to flip us, so see what I said here that 11 right most beat, if it is one then slip plus will have to be done because it should also be zero and right most beat of B is okay even if it is one. You will have to flip, both are different for both, so you have put a check for both, okay, there is a very good shortcut for this that you can flip plus make it equal, you can also do it like this and one plus, I comment this because This one is worth understanding more But also Phillips will give late examples which was quite simple, one brother checks every single beat, just two new things, what did you get to see, how the rightmost beat comes out, okay and how to shift right, here I will write. I am giving right shift, it is ok till now, it is clear, so now let us solve it with our second approach and in the last we will see what is the time complexity of both, okay, it is very simple, look here, let us take the number of bits, which is right? If it is N then it will run with more time because we are eliminating one beat every time. Okay, so the approach here is simple. So let's move ahead. Let's go to the next approach. So now look at our approach. Which will be a very good discourse, but it will be a little difficult if someone asks this approach in the interview, but I think if you practice such questions then things will start coming in your mind, if it is okay then see, first of all understand what to say in the question. It has been said that take out A and B. What comes out is A and B. It must be equal to C. So let's subtract one. First take out A and B. Take out A and B and see what will come. Then zero will go to zero and A. 10 one will go to A and 011 will go to A. Let's go to A and B. Now it is asking the question is it equal to C? 10 1 which is given is okay is it equal to C? So what did we do here earlier. We were comparing that according to my husband this is zero, this is one, leave it, what should we do, is it equal or not? First look at the beat, this is zero, this is one, brother, this is not equal, so we will have to flip one, right? If you are clicking, then I am going to do one more flip. Now come to the bed of the third one. Look at the beat of the third one. One is one from both of them. Meaning, if you will not have to fit further, then the answer is our Philip is equal, Tu. Okay, so this is going to be very simple, you take out A and B and take out 101. The seat is given, right, this is not a camera, that means you have to flip right, so you have to flip here, either take it F, okay if If both are not equal then you will have to flip. If both are equal then you will not have to flip. Then you have cross marked it. Okay, so see how much to flip. The word is one or two and our answer was also two or are you paying attention to one thing? You must have read your emphasis, remember what used to be that if it was done from both the beats then the answer would be zero, here both would be one, otherwise what would be the answer, one would be one. Remember, the emphasis used to be this, here we actually took out the emphasis. Its symbol is like this: took out the emphasis. Its symbol is like this: took out the emphasis. Its symbol is like this: Okay, wherever there is one, it means that there must be different bits in that number of positions, that is, it must have been flipped that many times. Here, it had to be flipped twice. Here, there is one. So, we don't have to do anything right now. If you look at it, we have taken out A and B. Here it is and we are kissing it hard. Right from C. Number of one beat, how many are there, account them here, how many one, two, my answer will be two, okay, Underscore Belt. By doing this pop count, there is some function which I am going to do, I will tell you in the code what it does, you just give it a number, simply tell how many one beats are there in it will tell you directly or you can use a separate function. You can write in which you are watching each beat one by one and counting whether it is one or not. Okay, it is so simple. In some number, that will be your answer. But is this correct, which is now known from the example. We have to understand well which mostly people do not understand, in this they understand that in the example I told, A was there, B was on c5, so one became this, zero became 10 became 100, this became okay, so if you think of it as my If you solve it using method number one then you will definitely get the answer. Okay, we counted one. If you get the answer better than that, okay, then you reduce one. First, let's see from our method which is our approach. Let's take it, okay, so what to do, so you remember the right most build of first C, saw that it is one or not, then when will you have to flip, when both of them are zero, then look, if both of them are zero, then it is okay to flip one. We will have to flip one of them, okay, this is also going well, now let's come to this beat, C has zero, okay, it is zero, so what I said, if when does zero come, when both of them should be zero, okay? This is zero, it is very good, if it is not zero then one flap will have to be done here. Okay, now coming here, there is one here, no, there is one here, what was in the one that if both are zero then only you will have to flip, see here. Yes, this is zero but if this is not zero then there will be no need to flip because if you do anything else then only one will be A, so look at the answer, still I am the one who came, which is also correct, here also you were the one who came, didn't I count? If 1 beat is fine, then where is the problem, the answer is correct A, but now I will change the example a little, now you guys find out what is wrong with it, okay, what do I do? = 4, okay, what do I do? = 4, okay, what do I do? = 4, I have added one more one here, I have reduced it to six, now let's see what will be the problem, then first write here, what was our C was our five, okay, so now first reduce one. We solve it with our approach one. If you do n't see what answer will come from our approach one, then remember it was very simple. In that we used to check by beating one by one. We went to the right of C. There is one here, isn't it okay when both If both are zero, then look, both of them are zero, which means if you flip one or the other, the answer will be A, so you have to flip it, that is, both of them have to be zero, only then you get zero, this also ends, now coming to this, it is one. If any one beat becomes one, then my [ __ ] will go down. Look, beat becomes one, then my [ __ ] will go down. Look, beat becomes one, then my [ __ ] will go down. Look, here one bed is one, so we do not need to flip here, so see the answer is three A, isn't it? From approach one, my answer is three A. Okay now. Our approach is one less, we have just learned it, let's solve it from approach one and let's see the answer brother, how many have come, three have come from approach, let's see what is there in approach, simply take out A and B. What are A and B? Will go zero one ok A and B this is done then which C to C what is the value of 1 0 1 So the emphasis comes out first one A is gone here zero A is gone how many beats are set right? How many number of bits are there whose value is one, if it is only two then the answer is mine, two will be A, according to that it is right, this is wrong, the answer should have been three, the date is A, you must have understood that there is something wrong, now you understand. What is that problem, do we have to pay attention to some extra things, which will solve our question, then you must have understood that yes, A and B were emphasized by C and who counted it. One beat is okay. We understand how much we have missed from this, first understand, see, I will not tell you that yes, one more thing will have to be added to it, I will not tell that directly, I will first tell you where that thing was missed by us, see, you understand. What did you miss and what should you pay extra attention to? You remember from Approach One, when we were shooting, when we compared these two, we realized that one clip was definitely needed and one of them had to be banded. Neither so that we get one here, then when we came here, we saw that brother, both are one, which means we will have to flip two, because we want zero, neither will have to be zero, so we will have to flip two, it is necessary to flip the last one. No, it was not necessary to fit in it, so look, we had to do two flips here, which is becoming the last one, which we are not going to take out in another 20 years. Look, pay attention, look, pay attention, how is that missing? Here one has gone, here also only one has come, either one or zero will come in the result, so when we are counting one, how much is coming out, two is coming out, okay Whereas there should have been three, right there should have been three accounts, so now you see where the mistake happened A and B, here one came, second son, this was made and the secondary bet was here, we had to flip two, which is We don't know what is happening here, how will we find out, we don't know what is happening, so if we look closely then we know actually what we have to find out is how many such positions are there where both the beats are one, repeat again how many such positions are there. How can you find out where both the beats are one? Think yourself, how can you find out where both the beats are one? If A and B come out, if A and B come out, then it is okay, what are the positions of both the places? Where if I do both the beat bands A and B, I will get to know where both the positions were 1, then when I do A and B, I get 0 1 0, which means I know that this is the position which made a mess for me. Why because it has both beat lines, here are both beat bands, so let's go A and B, now we know what to do, now pay attention to one thing, do you remember we had taken out A here and B loud C here, what came? There was zero, one, there was no, so I write A and B, there was emphasis, we took out, what came, 0, 1. So remember, what was the problem, we just counted these two ones and said the answer. That's two, ok, the answer has been said, two, but that's a mess, no, that's a mess, now you know what we will do, one more thing, give the answer from here, so we have taken it out, ok, but remember, where is the extra flip? I was going where both the beat sets were wanted, only then after finding out the operator and applying the operator, we found out that brother, this was the position where both the beat bands were, now pay attention to one thing if you Take this and this were, now pay attention to one thing if you Take this and operator, then see what will come, here one will go to A, okay no, every time, it is okay, what will happen to this one, where we had only single account, A and B and C, one and two came, only one. There was a miss, okay, here is one which will give both the beat bands at this position, then we will know that okay, this was the position where both the beat bands were and we have a confirmed missed account, okay, so which we are here We will add from number one, if it is ok, then we will have to pay attention to two things, remember the answer that came from it, the answer from number two is ok, the account was calculated from the number one, the result that came from A and B. What will be known from this is that one beat was known as to which positions both were in. Remember that, we had taken out another kiss, which was taken out by A and B, loud C, already mine, okay, so A and B and Take C in the result and store it in some variable. A and B are stored in temp. A and B were counted as C, that's why it was 112 A, so this, but Google, we did it wrong, but how did we catch that A and What we found out from B was that this was the position where both the beat bands were there and if neither of them had given one milk here one then I came to know that it was for sure in this position that we did a count. We must have reduced the count at how many places. We must have reduced the count by one wrong place. Because there was only one place where both the beat bands are there, right? So the answer is, therefore, if we ever counted one here, we removed one. Isn't it more than one, if you add these two then the answer is three, I would suggest you to take the example of multiple and example, I had done the exam by doing three, so I had cleared it better, either you can watch this video. You can see this area again to approach you, either if you do not know it in two-three exams, then generally you will not go into that much depth in the interview. Approach one is most important. It is okay for your interview. It is okay to understand approach one well. So let's just do this, we have to find out its number of one, how many beats are set, we have found out that and we will find out how much is the number of bedsheet one, we will add both of them, okay, so let's code it, so let's do our Let's solve this also through approach. What did I say first of all that in the name of a result, what will we find out? Party, was it completely correct? No, it was not completely correct. What were we missing? If it was not done then how come it is not part of the final, let's figure it out first. Brother, how many such cases are there where both the bitsets are one, okay? For that, what will we have to do? Take out A and B. We will take out A and B and then store that in a separate result one. Result one is equal to you A and B. At this time, how will we know where Bitset One was? Both are fine and then our result came in which what did we miss, how did we miss this one, then how many cases have been missed and the operator finds out, okay, we store the inter result in you. That Result One means A and B will do further to this is fine from the result, we will do further to this, till this is cleared, the result is A, now all we have to do is, brother, the number that came from this is number one, how many numbers are there in it? is of bits and how many number of bits are there in it, the count of both will be my answer, then what we have to return is how many number of ones, this is our answer, let's see great way, we have this question using and second approach also and if seen then you can see it as one You can also solve the return in line, change it in this, what is there in this result, this is the whole of it, put it here, it is ok and the result has been applied and the result is this one, this is the result, that is, this one is ok, this one. Please remove all this here, you can remove it, but it is not necessary to write so much complex code, okay. | Minimum Flips to Make a OR b Equal to c | tournament-winners | Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation).
Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
**Example 1:**
**Input:** a = 2, b = 6, c = 5
**Output:** 3
**Explanation:** After flips a = 1 , b = 4 , c = 5 such that (`a` OR `b` == `c`)
**Example 2:**
**Input:** a = 4, b = 2, c = 7
**Output:** 1
**Example 3:**
**Input:** a = 1, b = 2, c = 3
**Output:** 0
**Constraints:**
* `1 <= a <= 10^9`
* `1 <= b <= 10^9`
* `1 <= c <= 10^9` | null | Database | Hard | null |
785 | yo what's up nerd it's your favorite alpha male programmer today i'm going to be going over is graph by apartheid i actually already shot this video but um obs came out really laggy for some reason so i like have to completely redo it i'm actually going to do this in segments so if it's like you notice skips it's because i want to make sure it's not lagging before i waste my entire time so let's jump right into it um but first subscribe to my channel and like this video now given an undirected graph return true if and only if it is bipartite recall that a graph is bipartite if we can split its set of nodes into two independent subsets a and b such that every edge in the graph has one node in a and another node in b so first thing we need to do is understand what bipartite means um a bits well first let's draw it out so how are graphs if they give us this i have this written down on the whiteboard if they give us this as a graph representation um let's convert it to a visual representation of the graph so this is the zeroth index this is the first index second index and third in x um my ipad's lagging unfortunately so for the zeroth index um it's saying it's connected to one and three so let's go ahead and draw zero and let's go ahead and connect it to one and three there we go and then for the first index it's connected to zero and 2. um i don't know why this is lagging so bad i'm going to close this try again okay it's still a little laggy whatever so it's connected to zero and two so let's go ahead and one is connected it's already connected to zero so let's just go ahead and connect it to two i'm gonna put this closer to my mouth and then two is connected to one and three so we already have two connected to one let's just connect it to three and then three is connected to zero and two which we already have so this is how you represent a graph this is how we create the graph so now how would we go about salt well first let's go over what is bipartite so bipartite is saying it just wants to split it into sets of nodes whether each set is um not connected to any of the nodes in the same set so basically the easy way that this is represented is via color so if we color zero as red zero should not be connected to any other nodes that are red and same for all the nodes that are red so let's color the nodes that are connected to zero are different colors so let's go ahead and do like yellow orange so let's color one and three is so laggy i'm sorry guys and then so let's color the ones that connected to one and three red and if red doesn't touch red at all and orange doesn't touch orange at all then this is bipartite in which case this is true so that's how we do this problem for man sorry obs just looked like it was really likely so i stopped and checked but it wasn't so that's how we represent this problem as a graph now how are we going to solve this problem so we're going to want to keep track of the notes that we visited and we're going to want to keep track of colors since we're only using two colors we can use a boolean array so if we just do like boolean color and then boolean visited and we're just going to want to loop through this graph um so once we're going to want to check all the nodes and then when we're in a node say we're in the zeroth index we're gonna want to check all its neighbors color them accordingly set them to visited and we're just gonna do this so basically what we're doing is uh a bfs approach because we're checking all the nodes first in zero so we're basically like starting here and then we're gonna check out here and here the ones that are connected we're not doing dfs i guess dfs it would be if you go like that so um since we're doing bfs we're gonna need a data structure i'm just going to use q so bfs or obs looks so laggy when i look over i hope it's not i'm going to use aq so let's just go ahead and jump into the code my computer's just laggy i'm just going to restart my computer i'll be right back guys all right what's up nerd sorry for the interruption again um video came out super laggy so i have to redo the coding part again um i don't know what's wrong with obs so hopefully that fixed it i think google chrome was just like hammering away the cpu usage so anyways um yeah so i said we're gonna do bfs and data structure so let's go ahead create boolean uh visited equals new boolean 100 and boolean uh for color equals new boolean 100 and where did i get the size of 100 from um it's in the constraints right here graph length is never going to be greater than 100 so it's not going to have more than um 100 of these so this is one two three four it's not going to have more than 100 and let's go ahead and create our queue of integers and it's a linked list interface so new linked list and you could use a different data structure i'm just using a queue because i'm just going to pull it off the top the node that i'm interested in so then let's go ahead loop through the graph so we're going to do graph dot length we're not doing graph i dot length that is for all the neighbors we're doing graph length that's saying how many um rows it is i guess yeah it is rows it's basically a 2d matrix so um if graph of i so if there are no neighbors in the node that we're visiting so if it equals zero um or uh visited of i we've already visited it then we just want to continue go to the next iteration of the for loop and now here's where the good stuff comes we're going to want to add i to the queue set it equal to true and color of i equals obs still looks laggy true and i keep pushing my ipad okay so now we're gonna loop through the queue dot is empty okay so now we're seeing while the cube basically looping through all the nodes that we add into the queue and um first thing we want to do is grab the node from the queue so q dot pull it's going to be an integer and we're just going to want to loop through that node's neighbors so for integer neighbor in graph of node and so if um visited if we haven't visited the neighbor then we're going to want to do a few things to this so what are we going to want to do well first we're going to want to add it to the queue remember this is a dfs problem or um oh okay add the neighbor and then visited a neighbor equals true um and color of the neighbor equals true um so that's it for if we have uh no this is if we have not visited a very good thing i caught that else if we have visited neighbor then we want to check if visited or no not visited the color of the neighbor is different um equals color of node and if they're the same then they're not bipartite so we return false and that's basically the whole problem if we get through all of that we've looked through all the vertices and edges and we can return true so let's go ahead and run this and we got wrong so what did i do wrong it visited never graph node or q is not empty y equals true of color oh um yeah duh equals the color the opposite of the color of node so um i think all these interruptions with obs and stuff is throwing me off if you guys know how to fix obs when it's laggy let me know i don't know what's going on it's actually why i haven't been shooting videos as much so this works um i got a better written time before 12 6. i think the memory is messed up i don't know why so let's go over the runtime is o v plus e i just said that because we're visiting all the vertices and all the edges um so in the key we're gonna add zero let me just do this represent this real quick i don't know where we're gonna add zero and then we're gonna pop it off and we're gonna visit one but we're gonna add one neighbors so we're gonna pop one off at zero go back to zero um and finish it off so we're gonna go three and then pop that off with a zero because right here that's basically how this problem is going to work so like i said we're visiting the vertices which are these and then the edges are its neighbors basically um so that's why the runtimes o um o v plus e and the space complexity we're using a queue to store um that's all i got for you guys | Is Graph Bipartite? | basic-calculator-iii | There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties:
* There are no self-edges (`graph[u]` does not contain `u`).
* There are no parallel edges (`graph[u]` does not contain duplicate values).
* If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected).
* The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them.
A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`.
Return `true` _if and only if it is **bipartite**_.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\]
**Output:** false
**Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
**Example 2:**
**Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\]
**Output:** true
**Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}.
**Constraints:**
* `graph.length == n`
* `1 <= n <= 100`
* `0 <= graph[u].length < n`
* `0 <= graph[u][i] <= n - 1`
* `graph[u]` does not contain `u`.
* All the values of `graph[u]` are **unique**.
* If `graph[u]` contains `v`, then `graph[v]` contains `u`. | null | Math,String,Stack,Recursion | Hard | 224,227,781,1736 |
1,649 | i think this is definitely a good question for a whiteboard interview okay and if you don't know bit your interview is timed that means you don't have all day to come up with a perfect solution done is better than perfect your first priority is to implement a working solution you can always optimize it later if you have time hey guys welcome back today i have a problem from lead code in this problem in short i will say we have to actually take the elements from the instructions array and we have to form another list which is actually a sorted array if you see this example finally we are getting one two five six but the given array is one five six two right so finally we are going to get a sorted array or sorted list so there is a cost that has to be calculated each time we insert an element finally we will return the total cost from this operation so what is the cost here okay let's take this example one five six two okay and uh while creating this sorted array initially we will have a empty list okay and after that we take this one and we insert to this element for this operation what is the cost we will calculate how many numbers how many elements are there in this particular list which is less than 1 and how many elements there are in this list which are greater than 1 and the cost is minimum of this left and the right count okay for this first operation 0 for the second operations one element which is less than 5 so left cost is 1 okay and the there is no element which is greater than five in the list that's why the right cost is zero and mean cost is zero okay and the last step while inserting two if you see this is actually already a one five six is already sorted so we have to insert these two in its proper position and once after the insertion we see that one element is less than two and there are two elements which are greater than two right so that's why minimum of one two is one if we closely see this operation what we are doing so we are inserting an element to a sorted list okay which means we can use binary search here right and also while calculating the total cost the number might be very large that is why we have to return it modulo 10 to the power 9 plus 7 okay now the constituent also says that the numbers are in between 1 to 10 to the power 5 okay so we'll use all these things and we'll solve this problem let's look at this example three this is a little bit interesting because numbers are repeated here right so let's look at this line cost is minimum of five and zero five how five because it is counting all the numbers which are less than four even though three is repeated three times okay so this is another thing that we have to consider okay let's look at this example where we are inserting two to this list one two three four if you see this two it is getting inserted here okay so the left side the left cost is one okay how many numbers which are less than two is one that's why a mean of 1 and how 4 it is not considering this 2 and it is considering 3 times and 4. so if we see this line what we can do here we can find the range right we have to exclude all the twos right so we have to find the last index of two we have actually done a very similar problem where we find the range of numbers right in a sorted array so i think we have got some idea now what how will we solve this so let's try to write some studio code so we are going to create a list here so list of integer new array list for linked num in instructions right as i said we are going to use the binary search and we are going to insert that into a list again i would like to emphasize on the exotic binary search video that i did okay you can watch that because that is what we are going to use here okay so let us paint i equal to ebs will pass the list and the number okay this i is nothing but the left cost right now this list is empty right and if i will do evs on this list for any number it will give me 0 as my insertion point there are 0 number of element which are less than me and also zero number of elements which are greater than me right so i can say this is left cost for now okay i can call the same ebs to find the last index of this number in this sorted list right yeah let me do that i can say int last index equal to last index of the number right last index of the number equal to list num plus 1 okay if we pass num plus 1 to the evs we should get the last index of the number so this is possible if we have already inserted that number into our list so i can say list dot add my left cost or the insertion point okay with the number what i did here i found the instruction point i inserted that to the list and found the last index of that number by searching the next number once i get the last index the right cost is nothing but the size of the list minus the last index right yeah so what i can write here int um write cost equal to list dot size minus last index if that is greater than 0 then i can say list dot size last index else 0 okay fine now we have left cost as well as the right cost so we can say in cost equal to math dot min left cost right cost so minimum left cost and right cost will take and finally we will calculate the total right so i can say in total cost equal to zero and total cost keep on adding this cost and to stop the overflow we can say total cost equal to total cost modulo 10 to the power 9 plus 7 okay fine so and finally after the for loop will return total cost okay fine let us do little more optimization here okay if you see this last index okay last index we are doing ebs list and num plus one what we can do we can actually pass the first index the left cost right to the method to search for the last index of that number you are beginning from the left cost right so this is one optimization i would do the second binary search is required only when there are duplicate numbers otherwise not first evs also will update with zero so starting index will start with zero okay we can actually get rid of the second call also so as i said ebs is nothing but our exotic binary search so i have made a video on that's a little bit of modification to the planetary environment search which will return us always the insertion point for an element if it is not present and if it present it will return the index of that particular number okay so i have copied the exotic binary search here let's call it ebs okay we are dealing with a list which is list of integers so i'll just modify this ebs little bit it will take nums list of norms ok this should be size okay and this will take another parameter i will say start okay and i will get rid of this start okay now this is nums and this would be nums dot get because you are using a list here not an array so norms.get fine norms.get fine norms.get fine and the target okay so this is our evs method which will return us the insertion point if it doesn't exist and if it exists you will return the index of that particular target okay this one i'll yeah left cost last index right cost this should be question mark okay run code ok accepted now we will take ah this is the example one okay this is actually most important if this will pass then we know that our code is working fine because we are doing two ebs calls cool nice this is nice now let's just submit this cool okay this is accepted now as i told we can actually get rid of this second evs call if we know how many times the number is repeated right okay to know how many times this number is repeated what we can do we can actually introduce a cache we can use a count array okay of size because the numbers are in the range of you know one to ten to the power five so what i can do one four zeros one we can actually get rid of this second evs call right cost is equal to listed size minus left cost first okay and then we will also deduct the number of times this number is present so that can be done like plus count array number okay this is only possible because of this constraint if this constraint is not there then you know i feel free to use two binary search and that is still an acceptable solution okay good now let's submit this we can actually further optimize it by you know using a sorted list but we are using a list here which is actually increasing the time capacity here so the time capacity for this uh solution is not actually n log n but n square so even though this evs operation is log n this guy right here is actually eating our time so if we would have used a sorted list here then we can say that the time capacity here is n log n okay because this is log n and this will also be a login operation okay now if we see some examples here from the discussion they are using binary index tree in many of this example they are using binary industry but my goal here was to show you a solution which you can come up in an interview environment okay that's it for today guys and i think this is definitely a good question for a whiteboard interview okay and if you don't know bit remember this is an acceptable solution so you can write the solution okay and you can always tell that if we use a sorted list then the time constitute will be and login but because we are using a list here this is increasing the time complexity i understand it you can always tell that thanks for watching guys and this is my channel i'm not going to do thousands of problems in the lit code in my channel but i would like to you know target certain questions which are very helpful to you know open your thought process for cracking a coding interview you can encourage me by subscribing or liking my videos stay tuned and see you next time until then bye take care | Create Sorted Array through Instructions | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The number of elements currently in `nums` that are **strictly less than** `instructions[i]`.
* The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`.
For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.
Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`
**Example 1:**
**Input:** instructions = \[1,5,6,2\]
**Output:** 1
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 5 with cost min(1, 0) = 0, now nums = \[1,5\].
Insert 6 with cost min(2, 0) = 0, now nums = \[1,5,6\].
Insert 2 with cost min(1, 2) = 1, now nums = \[1,2,5,6\].
The total cost is 0 + 0 + 0 + 1 = 1.
**Example 2:**
**Input:** instructions = \[1,2,3,6,5,4\]
**Output:** 3
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 2 with cost min(1, 0) = 0, now nums = \[1,2\].
Insert 3 with cost min(2, 0) = 0, now nums = \[1,2,3\].
Insert 6 with cost min(3, 0) = 0, now nums = \[1,2,3,6\].
Insert 5 with cost min(3, 1) = 1, now nums = \[1,2,3,5,6\].
Insert 4 with cost min(3, 2) = 2, now nums = \[1,2,3,4,5,6\].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
**Example 3:**
**Input:** instructions = \[1,3,3,3,2,4,2,1,2\]
**Output:** 4
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3,3\].
Insert 2 with cost min(1, 3) = 1, now nums = \[1,2,3,3,3\].
Insert 4 with cost min(5, 0) = 0, now nums = \[1,2,3,3,3,4\].
Insert 2 with cost min(1, 4) = 1, now nums = \[1,2,2,3,3,3,4\].
Insert 1 with cost min(0, 6) = 0, now nums = \[1,1,2,2,3,3,3,4\].
Insert 2 with cost min(2, 4) = 2, now nums = \[1,1,2,2,2,3,3,3,4\].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
**Constraints:**
* `1 <= instructions.length <= 105`
* `1 <= instructions[i] <= 105` | Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal. | Array,Hash Table,Greedy,Prefix Sum | Medium | null |
357 | uh today we are going over the lead code problem count numbers with unique digits including whiteboarding approaches and solutions count numbers with unique digits is a dynamic programming problem that requires some knowledge of combinatorics specifically the multiplication principle so hopefully you've attempted a solution to the problem if not no worries i'm going to solve it today so the description reads given an integer n return the count of all numbers with unique digits x where x is greater than or equal to 0 and less than 10 to the n so an important caveat is that we are counting numbers with unique digits up to the specified constraint so in other words if we were given n equals 7 we will be counting unique digits up to but not including eight digits so for example when n equals seven ten to the seventh is equal to this which contains eight digits we have one two three four five six seven and eight however since the constraint is specified as then we only count up to this quantity so a solution to this problem is possible with nested for loops uh however it is also possible with a single for loop and hence we can achieve a big o of n worst case asymptotic complexity so we are given the following constraints like previously mentioned the n corresponds with the maximum amount of digits that will appear in the number within that range another important caveat is that the numbers to be counted can contain only one occurrence of a digit from zero to nine no repetitions so it's tempting to iterate through each number and take the modulus result and hash it but this will result in a time limit exceeded and even for practical purposes it takes too long to execute so i won't be doing that today so consider the set of decimal digits there are 10 digits total to choose from the set since the question is asking for the amount of numbers with unique digits in other words integers of certain length that contain exactly one digit from the set of decimal digits this also includes integers with a single digit two digits three digits and so on we must also include the amount of integers with a lower magnitude in the final result so for example if we were given n is equal to five we count all integers of length five with unique digits and then we also count all integers with length of four with unique digits n equals three n equals two n equals one and n equals zero so consider a number or an integer length of four when we have n is equal to four two three four in order to calculate the amount of unique digits we take note of the cardinality of the set which is the amount of digits we can choose from and select one digit from that set so starting from left to right we also have to consider that integers do not start with zero so initially we have nine digits to choose from in that set instead of 10 so we choose the first digit where k sub i is the digit afterward we choose the next digit but this time we can choose 0. so the number of choices in the set will be 9. third we choose the third digit since we pick two digits from the set and there are no repetitions allowed then we have eight digits to choose from lastly we choose the final digit since we picked three digits from the set we have seven digits to choose from what happens each time we choose a digit is that we multiply the current amount of choices with the previous amount so the final result will yield the amount of numbers within unique digits it's important to know that we do this for each length of digits up to the specified n so before i begin the approach i'm going to illustrate how the calculations look like for n length integers so observe that as the length of integers increases only one additional factor is multiplied with the previous result so we can use this to our advantage to begin we consider the base cases when n equals 0 and n equals 1. when n equals zero there's only one integer with unique digits and that's just zero so our account is going to be equal to one when n equals one there are ten integers with unique digits which is uh zero it is very important to note that we do not want to double count whenever we get anything above what one then we are simply going to say that it's 10. so since our table will be slightly off if we include these cases then we simply check and return this expression at the beginning of the solution so this will cover the case that n is equal to zero and n is equal to one next we define our table since the calculation is relatively simple we need only a single array of size n we then initialize the first value to 10 since we're not going to start counting at 0 and 1. next we want to keep track of the current product and minimum factor so we declare two locals since we initialize the first column of the table to 10 there's no need to begin at zero so we iterate beginning at one all the way to end so inside the loop we will update the latest index with the current product summed with the previous result so we calculate the current product with a minimum factor and decrement the factor next we update the current entry of the table now it's important to note that we have to sum the previous result because that is the amount of digits of length n finally since the result has propagated from the beginning of the table to the end we simply return the last element so now i'm going to go ahead and implement the sim code there so you can see it okay so now i will test and then submit there's a pass and then there we go accepted so can we do better uh yes we can actually completely get rid of the table and simply keep a local that holds the current amount and we have to make sure that when we do this we initialize this to 10 because we're actually starting from integers that have a length of two digits we can go ahead and get rid of this for loop so you may have noticed we can also use a while loop instead of a for loop to avoid creating any more variables than necessary i know that i ended up creating a local here but we did get rid of the array and we don't have to declare another counter uh to make sure that we iterate through the loop so finally we just simply return count at the end after this is done calculating so i'm going to go ahead and submit this or test and submit there we go pass the test and there we go there's our accepted submission so one important takeaway from this solution is that we have saved time by storing the previous calculation since each integer length followed the same pattern this is certainly better than a brute force solution anyway uh i hope this video helped and have a good one | Count Numbers with Unique Digits | count-numbers-with-unique-digits | Given an integer `n`, return the count of all numbers with unique digits, `x`, where `0 <= x < 10n`.
**Example 1:**
**Input:** n = 2
**Output:** 91
**Explanation:** The answer should be the total numbers in the range of 0 <= x < 100, excluding 11,22,33,44,55,66,77,88,99
**Example 2:**
**Input:** n = 0
**Output:** 1
**Constraints:**
* `0 <= n <= 8` | A direct way is to use the backtracking approach. Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. Let f(k) = count of numbers with unique digits with length equals k. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0]. | Math,Dynamic Programming,Backtracking | Medium | null |
958 | hey everybody this is Larry this is day 15 of the legal daily challenge hit the like button hit the Subscribe button join my Discord let me know what you think about 958 uh check completeness of a binary tree apparently I haven't done this farm so I'm excited uh yeah let's get into it hope everyone's having a great week so far uh it's ah just been nuts here in New York uh it's snowing a lot and I just came from outside it's cold everything is in my face I don't know my top my eyes are tired anyway let's go so giving a video of a binary determine if it is a complete binary tree in a complete mining tree every level except for possibly the last it's completely filled and all the notes in the last level are as far left as possible it can have between 1 and 2H notes inclusive in the last level Edge okay oh yeah it has to be as far as possible yeah I mean I hmm let me think right there are a couple of ways you can do this uh you have to look at every note in the tree ish um to kind of get into it so there's only 100 nodes so you can feel a little bit lazy and sloppy but you should be able to do this in linear time and the way that I'm gonna do it yeah is yeah I mean I think a couple of ways you can do it and I don't know that this is the kind of nautical way of doing it but and especially since to be honest it probably doesn't work with a big enough um it probably doesn't work with a big enough uh number of nodes because it doesn't do that way but I think the way that I'm gonna do it is the way that I'm gonna do is just numbering the tree and then see if there's any numbers missing is what I was going to say um I think this is definitely not the way that they recommend but wait what are the values that's what I'm going to see I'm just right now I'm just double checking that the values do they have to line up or they just happen to line up or do the values have to be just anything right and it's just I don't know why they have it then but okay fine so yeah um so then maybe get Max you know node if node is none we return otherwise well we um maybe something like this but otherwise get Max node no dot left which is current times 2 plus um so we have 0 1 2 so 0 times 2 plus 1 right I think my numbering is different from deal numbering which is why I just looks a little bit weird uh wait and then just return get Max of this right or this is a little bit off actually because then now I think this is just divided by two to get the previous one maybe that's a little bit better or maybe this should just return zero and then it does this and then it also returns uh the current value yeah and then maybe that's better actually and then basically now you have you know Max is you've got to get Max of root zero right oops what did I do uh and then um I'm just trying to think whether I could do this without you know storing every number right because obviously that would be easy but uh let's try it the other way so uh find Gap Maybe right and this is going to be the same oops so uh yeah if this is none then and hmm then we just return true or under the force in that there's no Gap maybe and then otherwise we want to if current so that means that the current node is none oh yeah well if Curran is less than MX then we return true otherwise we return force and then yeah that's it and then we turn find Gap note that left current times two plus one and note that right oops and find Gap know that right current times two plus two this is a very janky way of doing it but you know we'll see if this works uh I don't think I recommend this way at all but we just wanted to try something new uh so yeah so this return first why tell me why oh my conditioner is weird so it's either this or this yeah okay no it's just even more well doesn't put anything at all it is missing five which is true uh the numbers don't really match but I think this okay yeah because we want to because this we touched by it has a gap so we want to nod it I don't know logical things let's give it a quick submit hopefully I didn't have any silly mistakes and I don't yay we did do this in a funky way I don't know like I said I don't recommend it I think you probably should just like do some other logic but like I said I wanted to try something funky something new so let me know what you think let me know how you did this problem and yeah what is the complexity right so it's gonna be linear time linear space uh or all of each space usually it's all of h space because you know the stack uh the stack size is going to be of H but in this case it is also over H because this is current tick this is going to multiply by two so it's gonna take one bit per H for height right so this means that this is gonna actually um get even bigger so yeah uh that's basically the idea uh and depending how you want to count it this actually could be H squared so maybe that's actually really bad to be honest but uh it's just that is less than 100 so that's why we get away with it because on a stack space every size on the stack is going to be of each size on the stack so actually it's gonna be oh H Squarespace the way that I did it but I wanted to try something funky so I don't know let me know what you think uh but yeah like yeah let me know what you think and that's all I have with this one uh I am going to do the weekly premium one next just because well why not so definitely hit order button sub hit the button like button subscribe and join me on Discord and also yeah stay good stay healthy to good mental health I'll see you later and take care bye | Check Completeness of a Binary Tree | sort-array-by-parity-ii | Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000` | null | Array,Two Pointers,Sorting | Easy | 2271,2283,2327 |
1,025 | foreign and today we will be solving a new lead chord question that is divisor game and just before starting to solve this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel let's read out the question what is the question is asking from us and we will be solving this question with the help of JavaScript so now let's read out the question sees Alice and Bob take turns playing a game with Elise starting first initially there is a number and on the chalkboard on each player's run that player makes a move consisting of any choosing any x with 0 less than x less than n and n mod x is equals to zero replacing the number and on the chalkboard with n minus X also if the player cannot make a move they'll lose the game return true if any if and only if Alice Winsor came assuming both player uh play optimally so what we have to do here let's I will just explain it to you that what is the game is and you can just see that there are some examples here which says that n is equals to do which is returning to at least two this one and Bob shoes Bob have no more smoke and what if the game here is let's understand the game and then we can just understand the solution with this so let's see uh let's see what is the game so what is the game there is a chalkboard and the player has to play a game and while Alice has to start from so a lease has the first done all right and then choosing any X means that any action you can choose let's say uh we have a value n is equals to 5. let's say it's a 4 all right and then what will be happen uh in this four there's this number is on the chalkboard and each player has to make a turn Alice has to start from first she has the first turn so she will be choosing any number which will be ranging from X less than and X sorry 0 less than x less than n so which means she can choose any value which will be less than n so if she can choose what she can choose if n is equals to 4 she can choose uh one two and three but uh but she cannot choose a value see she cannot choose a value which is not the factor of n so she cannot choose three so she has to also make sure that she cannot choose a value which is not the factor of n so if it's 3 and 3 is not and three let me just write it here that 3 is not a factor of n that is far that is 4 so it will be removed all right so it will be like these numbers so she can make a turn with one or two all right let's say if she chooses a value as let's say a one she chooses one so what will be left here is if she choose is one so let's say let's see at least chooses one here all right so if she chooses one what will happen here is if she choose is one then the uh then what will happen it's the condition here is replacing the number on the chalkboard with n minus X so now X is equals to what x is equals to 1 if I reach to this uh X is equals to 1 x is what x is the turn what number you are choosing so she chooses X is equals to 1 then what will happen the number on the chalkboard will be which will be displayed will be uh it will be n minus X right so n minus X it will be 4 minus 1. all right so it will be 4 minus 1 which will be equal to 3. now again I uh now again the game will be played and now it's bobstone box turn it will be now let's say box to this uh let's say Now Bob's what will be option for Bob will be having the option as one and a one and one two and three right he will be having one two and three as the option sorry it will be not three will be excluded because it is less than the nth value so now n is equals to what n is equals to 3 right now so he will be having only two options to choose so she he cannot choose why because uh A2 will be removed also because 2 will be removed because 2 is not a factor of 3 so now what Bob will be having Bob will choose Bob has to choose uh has to choose one only right because uh two will be removed and it will be only one left so uh so what will happen uh the Bob has to choose one so now what will happen and will be is equals to 2 because it will be n minus X and N will be equal to now and will be equal to what n will be equal to 2. now again Alice will choose Alice will have to choose from what Alias will be having to will have to choose between uh zero less than uh less than x less than n so now she has to choose between X so now X could be any value so now n is equals to 2 x could be any values which will be ranging from uh which will be ranging from let's understand this that it will be fun only all right because 0 1 2 so now Alice has to choose one and now Bob will have no more moves left why because uh because n minus X should be the number which will be displayed on the screen so n minus X will be equal to 2 minus 1 which will is equals to 1 but we know that then but when uh when one number is displayed on the screen that is the loss of the player so if it is 1 if 1 is displayed on the screen which means that the player has lost the game so what I mean here is that if let's say if it's one is displayed on the screen what will happen Bob's turn will be there Bob's turn pops turn will be there right will be there now what will happen if it's the Bob turn and now n is equals to 1 and what will happen here is box run and then n is equals to 1 and the range will be 0 is less than x less than n and we know that n is equals to 1 so it will be n uh so now what is there X is the value between 0 and 1 which will be no value right because we are dealing with integers so what will happen Bob will lose so now I hope you have understood this question so what will happen here is that now Bob will lose the game right why because C one will be displayed on the screen and Bob will lose the game and this is what the game is all about so let's see uh what how we will be doing this question how we'll be approaching this question so there is a simple uh mathematical trick and what I figured out is here is that if you see that return an mod and mod 2 is equals to 0 which means that all of the even numbers are uh if what we have to return if at least wins the game so all the values which are even numbers and that is the value of n which is the starting value of n let's say it's 16 18 20 all of these numbers will be giving us the value as the winning number for Alice that is what I have figured it out so now we will be discussing this too that how even numbers will make her win now let's understand that how she will be winning we have understood the game and I have taken n is equal to 4 as an example that was also making the uh Elise win now we will be taking some another example let's say if we take uh eight as the number so let's say we have eight or let's say uh let's take an extra attack take a smaller number so that we do not have to repeat the thing again and again so let's say n is equal to 6 here what we will be doing first of all n is equals to 6 so Alice has to choose between uh choose between 1 2 3 and 6 right but six will be not included because 6 and NXX n is excluded from the uh n is excluded right so we'll be not taking the S the number itself as a factor now she has to choose between one two and three if she chooses let's say for example if she choose three so let's say a lease chooses three right if you choose a three what will happen it will be 6 minus three so and now n is equals to 3 Bob has two n is equals to three and now Bob has to choose between what between um between 1 and 3 and we have already studied it above that when n is equals to 3 and it's Bob's in here uh what will be coming up here is the theme thing which we have studied before see it's the same thing which will be coming up here because now f 1 and 3 are the factors and so this is the same thing will be happening that it will be n minus 2 uh if the Bob have to Bob has to choose one as the factor and two will be removed and 2 minus 1 will be 1 and then Bob has to choose one only and then when n is equals to 2 and this can only choose one and then what will happen the one will be left and we cannot choose one uh because F1 is listed on the play report uh chalkboard in fact so Bob will be losing if you can take more example you can try more examples let's say if you try it you will be seeing the same as I have shown it to you so this was the let's just write it here that this was the coding understanding part and this above part was the gaming understanding part now let's run the code and see what we have got so let's try and run the code and you can see on the screen let's beat and you can see that we can run both the test cases successfully that when n is equals to 3 what we are getting false SD value why because we cannot win let's take an odd value uh let's take an odd value and understand it let's see if we have a if we have 5 as the value let's say n is equals to 5 initially so Alice has to choose between one and five so now Alice has to choose between 1 and 5 but 5 will be excluded so she has to choose one right so she has to choose one then what uh one will be late so what will be happening five minus 1 will be four will be half for four wheelers so Bob's turn bobstone and she he has to choose between what uh one two and four this will be factor of four and now he has to choose between one two and four let's say he chooses uh but four will be excluded because 4 is for the number itself is not a factor so she he has to choose between one and two so let's say he uh choose two and what will be left uh four minus two will be left for at least so what she is what will be she will be choosing uh one or two write one or two but she cannot choose the number itself so she has to only choose one so this is how uh the things will be happening here and ultimately she will be losing the game so let now let's see when n is equals to 8 and run the code and try uh yeah see even for eight it's it is running successfully it's showing us the uh vary which we have discussed right now let's try for another values as well let's add some test cases here let's say n is equals to take some greater value let's say it's 100 here and let's try and run the code it is running successfully and showing a green signal for our 100 value as well right all right so I hope you have understood this question we can add more test cases if you want to we can try for more uh test cases here if we try let's say a value an odd value here and put let's see if we put an odd value let's say 17 if you put a random odd value and try to run the code it should be giving me a false value with a green signal let's see yeah see it is giving me a false value so this shows that our logic here works and this will be applied here you have to understand the question first and this is was all in the question guys I hope you have understood this question and if you do so please comment down in the comment section that you have understood the question thank you guys for watching this video and see you next time thanks | Divisor Game | minimum-cost-for-tickets | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null | Array,Dynamic Programming | Medium | 322 |
354 | Hello Viewers Welcome Padegi Tak Hum Dr Niswat Khushveer Who Can Be Seen That State Government Yadav A Bluetooth Settings Ko Band Shamil Aircraft Enrique Nominee Loot Website Introduce This Subject 1111 Minor One Busy Schedule And Always Person 125 This Question From Electronic Media 2006 123 Likes This point and subscribe pacific symptoms bhi mulk hai saudi arabia and welfare destroy were motive ₹1 boss season welfare destroy were motive ₹1 boss season welfare destroy were motive ₹1 boss season equal teachers day overwrite if left side effect this mic pass human boxing incident settle when office more comments half multiple best songs unauthorized 1234 into its state sport first Values in ascending order descending order se 5 to 6 subscribe our channel subscribe looti suicide on this right side shot dead in descending order per second column pimples ko birthday wish will change something nice admin this right very first intake cloud Services Limited's Basis Overlapping Rear Track I Don't Need To Go And Come Half Hour Do Subscribe To That Praveen Mein Daal Da Ya Se Again Other Special Topics Included 25 Kapoor Six Ka Do All six commercial festivals Difficult liberation-in-life Ikshvaku All obstacles Maintained divinely 6 - Dravid to 10 Eggs 6 - Dravid to 10 Eggs 6 - Dravid to 10 Eggs Must subscribe Subscribe to my channel Video not blind 210 quid but in difficulty - 2070 Sikhs were separated in the first test against West Indies From To-Do Plus Volume Liquid From To-Do Plus Volume Liquid From To-Do Plus Volume Liquid Friends To Role To Investment To Letter To Tension Death Is Looking At To Railway Arrangement To Turn On The Thing Should Give One Is Born Into A Great Efforts Into The Ascending Order Of The First Indian To Win The Election Ajay A reminder to add embroidery to cash withdrawal from that country of zinc that if and to par from 0.2 withdrawal from that country of zinc that if and to par from 0.2 withdrawal from that country of zinc that if and to par from 0.2 to z10 aniv corresponding chart lens ki i plus allahabad vikrant suicide point jan20 both ke rishtey nibhaye end share presented me sadak hai subscribe my channel 600 per fervently memo a place in the middle ages that idea and write under last step hence they religion icon its value screen more plastic youth incomplete current value than previous volume plus top that after all broken America problem development kiss a pain saturday satisfying Baikunth Dham Positive Finding Aa Value For A Ditch Cigarette Beneficiary System Site Twitter Facebook Update Mez Pe Aaye 15.2 Facebook Update Mez Pe Aaye 15.2 Facebook Update Mez Pe Aaye 15.2 Kar Di Peech Gaye Laxman Ki And I One Sentence With Exciting Aunty Gautami Tweet Finder Maximum Volume Skimming Chashma Episode Veerwada And Default Value Aa Show Exam Point Old Is Gold Channel Set Maze Pe y51 Placid For Various Activities In Valley Of Life And Death But As Way Can We Channel Subscribe Now To Find The Value Of India In Tubelight I Chain Here Sorted By Check Inside You For Be Id In A Special Result Equal to match card me result committee history channel subscribe and different 11 2010 250 subscribe to the Video then subscribe to subscribe our device where but alarm set phone operating in issues oh my god jewelers role is also locator 200 that subscribe to edit footer par kisi Ko Mistake Hai Dabangg Jaisi England Ko Five Subscribing Toe Print Subscribe Ajay Pathak Do And Hot Scene Issue Poddar And Line And Private Subscribe Ki Pooja Whatsapp Images Love Oo Hua Tha And Can Increase Top Order Times Pair Doing Allu Company Syed A Any Were Looking Great for the Value Especially Mid After Which Will Give Some Years Between Husband and 0 Guests from President B Co of Inquiry Against All Odds and Vigorous Investigation Questions Tags for this award-winning radio show is Mrs. award-winning radio show is Mrs. award-winning radio show is Mrs. Smart Enough for this Duration for Watching And Video Education 200 This Code And Father Private Practice Of Advanced Age Study List A Professor Of Forces Into Bed And President Sports Internal Effect Overall Deficit Medium To Back To Years And Starts At Which Truly Is Just Stopped In Matrix Index The Amazing Spider-Man Admin Spider-Man Admin Spider-Man Admin That iPod or account reduce in decker container a basis which side of polling set following order conditions wife indexing updated to give some more life it to waist thriller come Bigg Boss diploma course 6669 in it equal view his condition has no side effects such as women help Line with this commission was set up dysfunction shift available p.m. Model Song Romance shift available p.m. Model Song Romance shift available p.m. Model Song Romance Vikas Going Two Plus One Unko Doosri Then Modern Work Border Aa In Case You Have Any Questions In Between Comment Section In Kaise Lighter Permission Place Tubelight Phate Nikle Problem Channel Please subscribe and follow continue with support from public aa apni life and water no IF YOU LIKE THIS VIDEO GUYS PLEASE | Russian Doll Envelopes | russian-doll-envelopes | You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_.
**Note:** You cannot rotate an envelope.
**Example 1:**
**Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\]
**Output:** 3
**Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]).
**Example 2:**
**Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\]
**Output:** 1
**Constraints:**
* `1 <= envelopes.length <= 105`
* `envelopes[i].length == 2`
* `1 <= wi, hi <= 105` | null | Array,Binary Search,Dynamic Programming,Sorting | Hard | 300,2123 |
1,796 | welcome back guys today we are going to solve lit code problems 17 96 second largest digit in a string given an alpha numeric string s return the second largest numerical digit that appears in s or minus 1 if it does not exist an alphanumeric string is a string consisting of lowercase english letters and digits so for example like this right so some digits are there like here and some english letters are there small lowercase so we have to find out the second largest digit in the string so let's just take this example over here quickly so how we are going to solve this problem is using a priority queue so uh we will take a pointer first uh this is a string so we will take a pointer it will point to zeroth character in the string and we will be iterating the whole string this is uh let's say n is the total number of characters so all the digits all the characters we will iterate and we will keep checking if the character we are on is it is a digit or not if it is a digit so zero then we will go here one then we will go here two then we will go here three so as soon as we see a digit we will check if this character is a digit yes then we will put that character into our priority queue here right and we will also maintain a set here right set of integers so this is a set of integers so we will also add the character in the set you know because there are there can be duplicate uh digits in the string right so we will go here too then we will check into the set it's not there so we will add it into the set and then we will add that same uh digit into priority queue here right so 1 2 and then as you can see you know so when we are adding a 2 here then 2 will be in the front of the queue because this is a priority queue so always the largest element will be in the front so we will go to the 3 then we will again check into the set there is no 3 into the set so we will add a 3 into our set and we will add it into priority queue so we will actually when we are adding into priority queue it goes automatically here so largest element is always on the front so after that we you know we keep checking two then one so we will check it into the set right two is there one is there so we will not add it into priority queue because it's already there you know so afd we will not add anything because these are not uh digits so at the after we are done processing this string we will uh check you know the size of the priority queue if the priority queue size is equal it if it is if this size is less than 2 right less than 2 then we are just going to return minus 1 in that case because there is no second largest element right if it is less than 2 if it is not the case means it is a greater than or equal to 2 then we have a second largest element to return so in that case we will just pull the first element from the priority queue and then we will again call the second element from the priority queue and we will return the second element as our answer right so as you can see here the 2 is the answer that is how we got the 2 here so this is a very simple solution of uh you know we can implement using priority queue and set so i took both these examples over here so um let's first quickly uh go through this implementation that we discussed so we took a set here which is set of integers then we took a priority queue of integers now here we are using b minus a right because we want the priority queue to be like in a decreasing order so highest element will be always on the top basically and then we took a pointer that we will be like iterating through all these uh n characters of the string and we will keep checking if the character we are on is a digit you know there is a method called as is digit in the character class so we will use that and then we will check first if it is in if set does not contain that character then we will add it to priority queue so uh whenever we have a character and we want to convert it into integer then we have to just use it like this you know minus and then uh 0 here so it actually converts the character into a corresponding integer so that's what we are doing here so after the loop is over we will just check the queue size if it is less than 2 will return minus 1 otherwise we will return the second highest element here right we'll call and return second highest element so these test cases let's just execute quickly and make sure it works uh so yeah so we are seeing the correct answer here um so for the second example we don't have any second highest element there is only one element one here right that's why we are returning minus one so let's submit this solution so the solution works so this is how we can solve the second largest digit in a string so if you like the solution subscribe to my channel and click the like button i often create videos related to you know lead code problem solutions as well as related to java j2e related interview questions for junior mid-level and questions for junior mid-level and questions for junior mid-level and senior java developers so if you are interested in this stuff please subscribe to my channel thanks for watching the video | Second Largest Digit in a String | correct-a-binary-tree | Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_.
An **alphanumeric** string is a string consisting of lowercase English letters and digits.
**Example 1:**
**Input:** s = "dfa12321afd "
**Output:** 2
**Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2.
**Example 2:**
**Input:** s = "abc1111 "
**Output:** -1
**Explanation:** The digits that appear in s are \[1\]. There is no second largest digit.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters and/or digits. | If you traverse the tree from right to left, the invalid node will point to a node that has already been visited. | Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | 114,766 |
189 | what's going on everyone so today we are looking at lead code number 189 it is a question called rotate array and so here we're given an array and we want to rotate the array to the right by k steps where k is non-negative so here we have one two is non-negative so here we have one two is non-negative so here we have one two three four five six seven k is three we're gonna shift everything over to the right and we get five six seven one two three four example two we have minus one hundred three and ninety nine we shift the array twice two spaces and we have three and ninety nine in the front okay so there's uh two ways to kind of do this there is a trick to doing this question and there is a brute force way of doing this that's a little more intuitive so we could do a brute force approach at this just create two for loops right and go ahead and push in the five six seven and then concatenate the one two three four and make sure we keep track of it's that it is the correct array and then go ahead and return that you could do it that way it is a little more complicated and you do the performance is not as well a much better way of doing this is let's say we took this array and we re reversed it okay so we have one two three four five six seven we could have seven six five four three two and one all right and now we find the k-th all right and now we find the k-th all right and now we find the k-th index of this reversed array so here we have zero one two three four five six we're gonna move this k three spaces so k is gonna come here one two and three k is gonna be here at uh at this 3. sorry k is going to be here at this 4. it's going to be on the third index we're going to go 0 to 1 to 2 to 3. okay so now that we have k in the correct position let me clear this out here okay so now that we have k in the correct position what do we want to take the element right before k which is k minus 1 right over here and we want to reverse everything on this side of the array and reverse everything on this side of the array okay so what's that going to give us that's going to give us 5 6 7 and then if we reverse this part of the array we're going to get 1 2 3 and 4. okay so we could do this in uh in place we just need to reverse the array up front and then we need to go inside of the array and reverse the subarrays and so what is our time and space complexity taking this approach well we are scanning through the array once to reverse it and then we're going to have to do two reversals that will definitely be under n which n is the length of the array and so we're going to have 3n and that's going to abbreviate out to o of n on time okay space complexity we're not creating any new space relative to the size of the input so our space complexity here is going to be constant space okay which is pretty good indeed so let's go ahead and jump into the code so what we're going to do here is first we want to mod k because if k is larger than the length of nums then it's going to keep on cycling so we want to just go ahead and say k is going to equal k mod nums.length and now what do we want to do well we want to reverse the input array so nums.reverse the input array so nums.reverse the input array so nums.reverse that go ahead that goes ahead and reverses the input array in place and then we can create a helper function and we can say um reverse nums okay and that's going to take in the nums array a start which is going to be 0 and k minus 1. okay that's going to be our end index we're going to do a second helper function rev nums when we're going to take in nums and we're going to start at k and go to the end okay and so that's all we have to do for our main function now we just have to write this helper function so here we're going to have const rev nums that's going to take in our nums array a start and a end okay and so now all we have to do is we have to say while start is less than end what do we want to do we just want to swap the values okay and reverse it so we can say nums at start nums at end it's going to equal nums at end and nums at start okay and now what we're going to do is just increment start and decrement end okay and so that's all we have to do for this so let's go ahead and run this and we're good okay so not too bad uh i would highly suggest try to approach this trick to it um and just be familiar with it's a great way to kind of solve this problem quickly and elegantly uh and you can do the brute force away uh brute force way but there's a lot of bugs that can you can run into going that approach okay so that is lead code number 189 rotate array hope you enjoyed it and i will see you all on the next one | Rotate Array | rotate-array | Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative.
**Example 1:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 3
**Output:** \[5,6,7,1,2,3,4\]
**Explanation:**
rotate 1 steps to the right: \[7,1,2,3,4,5,6\]
rotate 2 steps to the right: \[6,7,1,2,3,4,5\]
rotate 3 steps to the right: \[5,6,7,1,2,3,4\]
**Example 2:**
**Input:** nums = \[-1,-100,3,99\], k = 2
**Output:** \[3,99,-1,-100\]
**Explanation:**
rotate 1 steps to the right: \[99,-1,-100,3\]
rotate 2 steps to the right: \[3,99,-1,-100\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
* `0 <= k <= 105`
**Follow up:**
* Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem.
* Could you do it in-place with `O(1)` extra space? | The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements. | Array,Math,Two Pointers | Medium | 61,186 |
1,658 | hey everybody this is Larry this is day 20th of the Lego day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's farm and type why did they do this that's not even like a referral thing that's very weird all right uh oops today's problem is 1658 minimum operations to reduce X to Zero hope everyone's having a great week so far New York is pretty nice today a good time of the year 70 uh well 70 degrees Fahrenheit during the day um what is that in Celsius like 15 or something like this like 16 17. very nice breezy day so I'm gonna enjoying New York September for now anyway let's take a look at today's Farm um let's see okay you're giving an angel away nams and an integer X in one operation you can either remove the left most of rightmost element from numbs and subtractors value from X note that this modifies the way for future operations return the minimum number of operation to return X or reduce X to exactly zero possible otherwise we turn negative one okay yeah um okay so um thank you I think there are a couple of ways to think about this I mean I think this is actually one of the problems where I think it would be more interesting if we didn't know it's difficulty I think the medium kind of gives it away a little bit um because I think back in the day I might have at least kind of maybe like I want the possibility of overthinking it you know uh that part of the difficulty sometimes is that you may you know come up with some crazy scheme uh just to realize that you don't need a crazy scheme uh but and those of you who kind of did daddy problems way back in the day they didn't used to have this format but in any case uh we don't have to kind of you know go Nostalgia but basically the idea is I think the idea is going to be this right so you can only take some prefix and some suffix so there are a couple of things so the way that I think about is how can I prove first right and what I mean by that is by testing everything as possible um and like I said you only need to take the prefix or the stuff uh some amount of prefix and some amount of suffix right it could be an entire way but some amount of that and here's the way that I think about brute force is okay let's say we text zero element from the prefix how many do we have to take from the suffix let's say we take zero element from the prefix how many do we have to take oh sorry did I say that already if you take one element from the prefix how many do you have to take from the suffix right so for example if it's zero then you remove it would require the last two if uh and there are no negative numbers right nope uh if you know you have one you only need the last one right uh if you take two you only need the last one as well I mean I say the last one but obviously one plus three is nine you go to five so it's incorrect but you would only take up to one uh you take two right uh that adds to five and you know there are two ways to uh to be honest um and these are the things where you know you kind of think about it and you explore it and you get the solution by the exploration right and not gonna like the my initial thought was to use a suffix sum um which is prefix sum but going backwards and then maybe have a lookup table so I could be like oh um and then you know there's zero so let's look at five right um and then here's one so let's look at well I mean yeah here's one so then because it's X is five we only look for four uh the prefix is two so now you only look for three dot so forth right and you know that's fine um and that also will give you know constant time per operation so it'll give you probably linear time linear space or something like this right but then you know that is the benefit of kind of looking through it a little bit is that you also realize that as we kind of increased uh numbers on the left side on the prefix side we tend to decrease on the right side right so because of that I think you know you can kind of use two pointers in that way one for the prefix and one for the suffix so I guess two pointers mean something else so maybe that's a bad naming but yeah um and this all predicates on the fact that X is great uh positive right I mean with zero I mean it would be the same thing with zero it's just that uh you know you could greedy it away because well you know you're trying to minimize the number of operations but here um we're gonna always be monotonic or another monotonics will be strictly increasing um so yeah uh cool I think that's all I have for this to kind of get started so yeah let's uh let's actually code this thing then right so okay so um uh oops best is equal to Infinity for now and then here uh we'll start by well let's just have some suffix Index right is you go to n minus one yeah so then while uh and then maybe like a current total is equal to zero well current total is less than x strictly then current total we added to num sub uh nums of suffix index and then we move it to the left right and we need a and suffix index is greater than zero okay right and then after this condition ends and this condition only ends with either suffix index is equal to zero or current total is equal to uh X so if current total is equal to X then best is equal to Min best uh and this is a little bit awkward but n minus suffix Index right or is it off by one this is off by one because this is not inclusive so let's actually um trade I wrote is a little bit awkward yeah because we wanted to be yeah inclusive so I think this should be fine yeah okay right and then uh yeah I think there is something like if current total is less than x then we return um negative one or whatever it is but I think that's like I think that's true but I think to keep it kind of stupid simple we just do if some of nums is less than x then when we turn negative one right uh there may be other ways of doing negative one just because you know like if none of the sums somehow adds up to X in some way that'd still be true okay so then now we have some prefix indexes equal to zero right so then now current total we added to prefix index and then while uh well this should be numbers of this anyway but I would maybe actually rewrite this as a for Loop for prefix index in range of n but and then while current total is greater than x we subtracted from the suffix there's also another thing though this is a little bit yucky because prefix index can go over it um so we actually also have to be um yeah so while prefix index is greater than or equal to suffix index then current total so that we don't double count though I think this is a little bit this is off no I think this is fine so if current total now is equal to X then the math is a little bit yucky uh so prefix index plus one is going to be the number on the prefix side and then plus n minus suffix index on the suffix side so this is I guess prevents on this doesn't change anything and then we can return best but if best is greater than infinity or if you go to really then negative one I think that's the only thing um which line is that 27. oh yeah I did forget to check hmm uh okay I think I missed the case where basically the prefix is now bigger than the suffix index so I think this is well this and suffix index is less than n then we're good yeah I think we need to do this here as well and I think it's more cleaner to write it the other way but I guess this case cannot happen or this cannot be out of bounds because by definition prefix is not out of bounds uh okay to be honest very uh this is a lot of kind of kinky uh yeah well maybe a little bit but uh if you're into it uh this is a little bit messy kind of cold so I'm not super confident very many places for potential off by one so I'm a little bit worried but because this is a daily and I'm lazy so let's quicker Summit Yellow and see how that goes ah okay good 1268 wow couldn't have solved this three other times don't remember it how did I do previously oh I did what I said I was going to do with the suffix uh sum which to be honest is still like I don't know I feel like that's easier if I was doing it in a contest I did it this way as well prefix so I have a prefix sum and then uh yeah oh this is cool uh I guess this way instead of uh trying to get the sum of the prefix and the suffix uh I take that as the total minus the prefix and the suffix so then now it is the two pointers to get the middle that's actually okay good job past Larry didn't do it that way this time but good job pass today and this one I use the table again so okay so apparently this is the first time I've used the two uh the pointer way uh because so that's kind of cool too I mean something new because all these um this is linear time and linear space uh this is also linear time linear space and this is linear time linear space so this is the first time I've done a linear time constant space and yeah that's all I have for this one let me know what you think and yeah uh stay good stay healthy to go mental health I'll see y'all later and take care bye | Minimum Operations to Reduce X to Zero | minimum-swaps-to-arrange-a-binary-grid | You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations.
Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`.
**Example 1:**
**Input:** nums = \[1,1,4,2,3\], x = 5
**Output:** 2
**Explanation:** The optimal solution is to remove the last two elements to reduce x to zero.
**Example 2:**
**Input:** nums = \[5,6,7,8,9\], x = 4
**Output:** -1
**Example 3:**
**Input:** nums = \[3,2,20,1,1,3\], x = 10
**Output:** 5
**Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
* `1 <= x <= 109` | For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's. If there exist an answer, simulate the swaps. | Array,Greedy,Matrix | Medium | null |
1,832 | um hello so today we are going to do this problem called check if the synth sentence is um pentagram um lead code number 1832 um 1832 so a panorama is a sentence where every letter of the english alphabet appears at least once so every letter appears at least once of the english alphabet given a string sentence containing only lowercase english letters when returned true that sentence is paragram or false otherwise so this one true it contains at least one of every letter of the english alphabet and let's call it false okay so well we can just um so we probably need the alphabet itself um let's call it something like this and then we just need to make sure that every character appears once so we can just say we can have it in lower case so this can be in lower case just so because the sentence is guaranteed to all be lowercase um and then for c in the alphabet we can just say if um if c is not in the sentence then we can return false otherwise we just return true right um and then this can be made easier by just checking right so just return they all have to be there right so you can just all see in sentence for c in alphabet right so we can just return that just we need to the alphabets letters english uh english alphabet uh lowercase oh can i get all of them just copy faced um yeah let's just do github here and do a b c d e f something like that just to get um the code for that um oh wow okay um okay uh python english alphabet okay that's it okay so alphabet is going to be equal to this and we can just return that okay let's try okay so that should pass if we submitted okay so that passes yeah so this is very straightforward right it's just um a check um let's see the topics here string it's right over string and map each character is found using paneer or any other similar way check if the number of found characters equal to the alphabet yeah that's also another possibility like every time you find one just count and just check if the length is equal to the length of the alphabet as well um you can we can also have a body and right of 26 i think it's 26 characters right so if i do print a ln for the length of the alphabet can also just um oh sorry it's not print in column in python that's um sorry syntax is wrong it's different yeah so it's 26 characters so we can just keep track of the boolean array and just set it to true uh every time we find it and then at the end count but yeah that doesn't make sense we should just exit as soon as we find one of the characters in the alphabet missing um yeah so i think yeah this is pretty much it for this problem | Check if the Sentence Is Pangram | minimum-operations-to-make-a-subsequence | A **pangram** is a sentence where every letter of the English alphabet appears at least once.
Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._
**Example 1:**
**Input:** sentence = "thequickbrownfoxjumpsoverthelazydog "
**Output:** true
**Explanation:** sentence contains at least one of every letter of the English alphabet.
**Example 2:**
**Input:** sentence = "leetcode "
**Output:** false
**Constraints:**
* `1 <= sentence.length <= 1000`
* `sentence` consists of lowercase English letters. | The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n). | Array,Hash Table,Binary Search,Greedy | Hard | null |
1,639 | all right what is up here back and uh we're gonna be doing today's uh liko daily challenge uh so it reads the number of ways to form a Target string given a dictionary so you're given a list of strings of these same length words and a string Target your task is to form Target using the given words under the following rules Target should be formed from left to right to form the ith character of Target you can choose the Kate character of the Jade string inwards if Target I is equal to words J K you can use the Kate character of the Jade string of words oh no once you use the K character of the Jade string onboards you can no longer use the X character of any string in words where X is less than or equal to K in other words all characters to the left or left of or at index K become unusable for every string and you want to repeat this process until you form the string Target and uh you can use multiple characters from the same string words provided the conditions above are met so essentially you're trying to use a collection of strings to form a Target string and the restraint is that when you pick some index of some string in this array you can no longer once you pick that choose any index which is equal to that or less than that so for instance if I'm trying to form ABA over here then let's see if I choose to I'm trying to form ABA with these strings let's say I start off with choosing this a if I start off by choosing this a then essentially I can no longer choose characters that range from well zero to zero right index zero I can no longer choose a character uh I can't choose this beat and I cannot choose this C nor can I choose this a right so if I select this a initially then I cannot choose this B I cannot choose the C and I cannot choose that a but the good side is I do get an A for free and then let's say I'm trying to get a B if I'm trying to get a B then I mean there's so many options let's say I wind up choosing this B over here or if I choose this B what that means I can no longer use the first two characters or actually for that matter the first three characters of any of these strings right I cannot use the first three characters of this I can't use the first three characters of this and I can't use the first three characters of the last string so I mean it seems like a restrictive constraint but I it realistically I think sets up the president for a well-known algorithm so there are six well-known algorithm so there are six well-known algorithm so there are six ways to form Target uh ABA index zero so let's see your first index is okay if your a your first a comes from that then you choose this B and then you choose that a then you can say a you choose that b get that a okay this makes sense so far then you choose that a you choose that b and you choose that a that makes sense as well let's see what else um you choose this a you choose this B and then you choose that a didn't we see that already hold up I feel like we saw that or was it in a different ABA wait hold up didn't they already do that so let's see a is this not a duplicate am I misreading the question so let's see Acca b how is this not identical to this case right over here this might be a typo it might be a typo but let's see irregardless let's see we have uh c-a-c-a uh two B is a b oh wait I just realized I think what they're doing as you know I don't c a okay I'm just going to assume these are all six unique ways I can't really spot the bug right now but you know modulo 10 to the nine plus seven the once you choose a character index uh at index J from any of these you can no longer choose any index lower than that and then you're trying to form some gold string and this is screaming Dynamic program right it has all the constituents of a classic DP problem so what should our state be right in any DP problem you need States any new transitions so I think that the state should probably take some form of like DP of IJ right where I so DP of i j what does this represent this represents the number of ways to form the string consisting of the indices zero to J over here right so you're forming zero to J of Target so I get okay we should like formalize this so DP of IJ this is a hunch not exactly sure if this is true but dpfij is equal to DP of IJ is equal to the number of ways e divided equals the number of ways DP of I J equals the number of ways to form the characters zero to J of Target using the indices from 0 to I or maybe using the index I'd have to think about that but in fact I think it's probably easier if we say the number of ways to form the Jade's character the number of ways to form the Jade character of Target using an index I from one of the elements of words that okay that's kind of a hunch right DP of ijs the number of ways to form the Jade's character so basically how many configurations of these processes have that the Jade's character of Target is being formed with the I index of some element in words that's kind of the idea and then our answer right our answer that we're reporting at the end would be what well essentially you're trying to form the last character of Target let's take care of target has n elements right let's say this has like magnitude n right so then it would be like DP of I mean zero n is probably not possible right you can't use the zeroth index but yeah DPF would say like zero n plus DP of one n all the way up until or I can't okay we're doing zero indexing we have to be consistent about it so let's say that this is one indexed or let's say actually let's just have both of them be zero Index right so the last index of Target would then be n minus one right if it has length n so then yeah our final answer would be DP of zero n minus one plus DP of one and minus one plus DP of two n minus one all the way up until DP of what DP of it would be what it would be well let's say the length of these strings is M would be M minus one n minus one right so basically the current DP which we might have to modify but is my initial hunch is that how many ways can we do this process over here such that the Jade character of the Target string is being formed by index I of one of these element strings and then our final string right what do we know about the final string well the last character of this gold string has to be formed by some index of one of these so it could either be the first one which might not happen in many cases but it could be the second one it could be the third one all the way up until the last one so I'm pretty sure this is a good DP State I just have to figure out if this has fast transitions so let's see DP of i j would then equal to what how do you relate DP of IJ to smaller States so um so dpy J uh number which one of the J character using index I so then you have to start relating uh so I think the easiest relationship that you can form is you can form a relationship to DP of like X and then J minus one so DP of sum I'm just going to write X star and then J minus one so this is the number of ways to form uh use let's see this will be the number of ways to form so DP of X star J minus one what would that be that would be yeah you have to relate to DP of X star J minus one so DPO so DP of J minus one would be like the number of ways to form the J minus first character using some arbitrary index so basically I think you want to sum this over all relevant X so basically the in that case DP of i j becomes GP of i j which is the number of ways to use the I index of one of these words to form the Jade character of Target well this will simply be the number of ways to use some other index X to form the J minus first character and then you're doing this over all possibilities of x and then X obviously has to be less than or equal to I so this is essentially for all X less than or equal to I this should be the running or actually X has to be strictly less than I right X has to be strictly less than I so the formal solution so okay this and then we can easily calculate this with some sort of prefix sum so that shouldn't be too bad so hmm okay so if we're being more formal with this DP of i j right just to reiterate it's the number of ways to form the jadeth character of target with an ith index of one of these elements of words and then the reason this works is because let's think about our final answer right our final answer of like Target we know that the last character has to be formed by some index of one of these elements so let's just do casework over what that index is let's say it's the last index well okay then that's defined as DP of it would be in this case what DP of M minus 1 n minus one right if these have length M and then these have length n right it'll be DP of M minus one n minus one okay now let's say it would be uh DP let's say that the last element of Target is formed by the second last index of somebody in words so then it would be DP of M minus two n minus 1 and that logic recursively falls down so I think this should work so basically this is what DP of i j is equal to and then our answer would be that DP of i j is equal to DP by J oh no our answer right the one that we're reporting that would be what that would be R is equal to the sum uh as I don't know I ranges from 0 to M minus one of DP of what DP of it would be essentially I and then uh n minus one this is our answer and obviously you have to take mods so okay so this should be our algorithm and now let's try to code it up so let's see we're gonna need uh I want the length of each of the words so I'm just going to call that M so that's words dot length and then I want the length of Target and then we should have the mod uh 10 to the 9 plus 7 we should have that stored as well and then our goal is just to return uh we'll see so the result is zero and then we Loop through words or actually we have to Loop through the DP table but I said okay let's just form the DP table would be of this form right DP is long MN right so essentially this is the number DP of IJ is the number of ways to form the jth character of Target with a with the ith index of some element in Word of some oh wait I feel like I haven't fully thought about the DP I haven't fully like thought out the DP yet because the number of ways to form the Jade character of target with the ith index and then you know the ith index of some element in Word and then yeah so the number of ways to form the Jade character of target with the ith index of some element in word and then what else do I know I'm always from the jith character Target with the ID index of some Element word words right and then so the way you define DP by J well DP of i j the number of ways to do this will simply be uh DP by J it'll be well it depends right so it'll be the number of it'll be the frequency of the Jets hmm it's actually tricky so I said it's not that okay basically in the eye element of word right or oh in all the it indices so like the second index in this one right it'll be like b or a right that's our like letter set so to speak I think that we need to have that information stored but basically how many height indices have the same element of T sub J or have the same character as the jth character in Target and so the occurrence or number of elements number of I indices that uh equal uh T at the index J multiplied by this expression is going to be multiplied by what this is going to be multiplied by the sum of like DP of would be what I minus one no so yeah I minus one J minus 1 was DP of I minus 2 J minus one plus DP of I minus 3 J minus one all the way up until DP of zero uh J minus one all right so yeah this is our transition so to speak and then yeah our final answer will just be I just like to get that ahead uh get that done ahead of time so our final answer will be this casted so our final answer is uh we Loop through or rather we do case work on how this last character of Target is going to be formed so it can either be formed by an M minus first indices or an A minus first index it can be formed by a second last index it can be formed by a third last Index right so we do casework over how this last character was formed so that'll be four and I zero I less than m i plus result plus equals it'll be DP of i n minus 1. and then we obviously have to mod it right make sure you're not overflowing and then yeah we just cast it and return the answer so this is going to be our answer now we just have to work out the DP so to get this the number of ith indices that equal T sub J I think are the characters only lowercase that is relevant right so are the characters only lowercase down so basically for each index of these words so to speak I can make like a 26 by I or what it would be or it could be like an I by 26 table where like for each index I report the frequency of each character right so like for instance in this first index of this collection the element or the word c will like appear once the word Beetle appear once and then the word a well Peter wants or like in this last one the word a would like appear twice so we can use that type of idea and then yeah so we can try to use that so first let's assert those frequencies so frequency uh new end would be it would be some maybe the length of the words and oh wait no there should be like word zero dot lens right so it'll be the length and then 26 and then basically we Loop through each of the elements in words so four string W inwards now I Loop through each of its indices so four and I zero I is less than m i plus and essentially if the character at I the frequency of the character at I so the frequency of the character at I hmm the frequency and the of the character at I so basically first I need to get whatever word this is so Char C is equal to w dot chart at I right and then I say frequency at C minus a is equal to what no wait so frequency at yeah frequency I at C minus a uh I can increment that so basically at the ith level or the ith index we have seen this character one additional time so this allows us to get the sources to compute this in much quicker and then honestly I can make this along just to make life easier so I don't have to worry about casting and stuff later and then I should make this a 2d array as well okay great so then uh what can I do now I can uh create the DP table basically so four and I zero I is less than m i plus and then four into J zero J is less than n j plus one or actually we need J minus 1 to be fully computed I feel like it will be if we have computed I thoroughly then we've computed J thoroughly right I'm trying to think yeah bro I might as well all the J's have been complete so yeah this should work and then so basically DP of IJ so it depends right so there are base cases so if J is zero meaning that we are trying to form the first character that's all we're trying to form right so if J is zero then DP of i j is pretty simple it's just going to be the frequency of this Jade character so I don't know what this J's character is I'll get the value of it'll be what Target dot Char at J minus a right that's the J that's the value of this Jade's character and then yeah that's the value of this Jade's character and then what else do I know target.chara J minus yeah so that's the target.chara J minus yeah so that's the target.chara J minus yeah so that's the value of this Jade character and then yeah and just be the frequency of this across the ith index thank you and then otherwise basically what this is saying is how many ways can we form the if J is zero that means how many ways can we form the first character of Target using the ith index that's basically what it's saying and the number of ways we can do that is just what is the frequency of this jth character or in this case the first character what is the frequency of the first character across these ith indices in words and then for the second one if I is not zero that's when you have to use this summation so that means DP of i j uh there's two parts to this right so the first part is we have to find what this summation is equal to and then so the easiest way to compute the summation we could do a for Loop but I think that's gonna yeah it's gonna run over time probably so we have to use a more efficient way so I'd say prefix sums so that means we have to track those prefixes uh so that's a little additional bit of bookkeeping but I'm just gonna call it PR new long MN and this is just storing prefix sums I guess it would be for the column is fixed so it'd be over a row you're getting the prefix of a row okay that's something just fun uh okay how do we store those prefix sums as we go along I feel like the way to do that would actually be to do what the way to do that would be so like just to visualize this we are like storing the prefix of like this we're storing what this sum is equal to up until a certain point we're storing cumulative sums so to speak so if I want like the sum of these elements well that'll simply be the sum of this plus the sum of all these elements so that'll be like DP of the column is staying fixed the rows what's changing and we need to keep that like as an ongoing aspect so what would that be so DP or prefix of IJ so to speak PR of i j which is the sum of what is PR of i j so that would be the I throw in the Jade column that's like over here and you're summing these top elements over here you're summing or no purify J yeah so this is like the uh element i j you're essentially summing p r of I minus one J PR of I minus two J PR of I minus 3j so forth right so yeah this is like PR of I minus 1 J PR of I minus two J I minus one J or actually you should include I let's just include I right so PR of I no this would be like DP of i j Plus DP of I minus one J plus DP of I minus two J right all the way up until DP of 0 J so how do we calculate these as we go along hmm so let's see prefix of i j should equal to so should we do it I think we should be doing it inside the for Loop so prefix of i j should equal to the value of dpij Plus PR of I minus one J right this is provided that I is not zero so if it's not zero so if I is not zero then right okay we essentially we initialize PR of i j to dpij so PR of i j is equal to DP of i j and then we say that uh PR of i j and if I is not zero then we can claim that PR of i j is equal to DP of oh no then you add you would add what would you add to it you would add a PR of I minus 1 J PR of I minus one J and then you would uh mod it so PR of i j mod whatever that big Prime is and the reason we do this is that we would like to avoid overflowing so that looks fine to me and then we can say that DP of i j is we'll initialize it to be here of it would be I minus 1 J minus one right yeah that makes sense I minus one J minus one and this is provided I is not zero if I is zero that means you're forming the J's character with the index I so if you're trying to form the Jade character with the index I so what's the restriction on J now that I'm thinking about it what do I know about J definitely has to be less than I right J has to be less than I or less than or equal to I yeah J should be less than or equal to if it's not less than or equal to I it's effectively impossible because like let's say I'm trying to form the like fifth character of this with the third index that's not possible we can't do that um because yeah all those five characters that you have formed of this need to like build in order they have to get bigger so yeah J definitely has to be less than or equal to I so then we can say that uh yeah so if J is not zero then yeah P or of I minus 1 J minus one strange children think what if I could still be equal to one right so let me think I has to be greater wait if J is not zero I know that I is definitely greater than or equal to J right so that means I is greater than one so I minus 1 is a functional value yeah p r of I minus 1 J minus one I agree with this and then mod it which even though PR of i j is modded so just be safe take extra precautions you don't want overflow and then we say we multiply it by uh the frequency of I value and then uh we mod it again so DP of i j no you're not modding with PR okay you're modding with mod and then you mod it again so okay yeah this should theoretically work but now we're gonna probably have to debug a little bit uh oh wait okay you have to multiply it by oh no uh what's the issue oh yeah it's the strings you need those parentheses any other issues Target yeah it's a strings need parentheses yeah it should work index one out of bounds for negative four oh wait if I is not zero you know what else uh line 24 okay line 24. Okay so target.j oh and JSP less than n right J target.j oh and JSP less than n right J target.j oh and JSP less than n right J has to be less than n that's another criteria okay looks like it's working for the first two um do you want a more subtle case yeah let's try this funnel case I own a case where the answer is like okay let's say I'm trying to form I don't know yeah same trying to form ABA right a b a so in this case uh there should be 27 ways foreign for case three yep okay let's try a fun case let's try uh let's make all of these the same like once again let's try that same type of trickery let's say these are all like a I'm gonna copy paste this I don't know the length of this but point is the answer should be pretty big so how many words are in this let's see we have three we have another three we have little double so three another three uh hold up bro uh yeah so we have six till then another three yeah we have like shoot I think this one's 12 right yeah this is one twelve so for each of these characters you have three options in terms of How It's formed so the answer should be three to the twelve whatever that is three to the twelve oh that's a small number to be honest uh let's run it oh I mean I don't know why I thought it would be too big but okay it looks like it's getting it right so okay good stuff let's submit it let's hope we're right okay looks like it works uh okay let me describe the algorithm it was honestly a textbook DP problem not much fancy here but essentially here's what we have right so DP of IJ we defined this has to be the state so DP of i j is equal to the number of ways to form the number of ways to create T sub J with an ith index of words right so to form T sub J with an ith index of words so with an ite index of words the number of ways to form an ith index of words right this is what um this is what DP by J is the number of ways to form T sub J with an I think X of words so then DP of i j is equal to the sum as uh I ranges from zero to so in general right the transition is that it's the frequency of the Jade character across ith indices so I'll just write that as F sub i j the frequency of the jth character across ith indices multiplied by the sum as I don't know some variable X the sum as uh X ranges from 0 to it would be I minus one of uh DP of I minus 1 J minus one so that was the algorithm and then there's edge cases base cases but this was the basic premise and then our answer was well we can just do casework over how the last characters formed it could have been formed by some character here and uh so forth so that was it for this one and uh I will see you next time | Number of Ways to Form a Target String Given a Dictionary | friendly-movies-streamed-last-month | You are given a list of strings of the **same length** `words` and a string `target`.
Your task is to form `target` using the given `words` under the following rules:
* `target` should be formed from left to right.
* To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`.
* Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string.
* Repeat the process until you form the string `target`.
**Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met.
Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba "
**Output:** 6
**Explanation:** There are 6 ways to form target.
"aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ")
"aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ")
"aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ")
**Example 2:**
**Input:** words = \[ "abba ", "baab "\], target = "bab "
**Output:** 4
**Explanation:** There are 4 ways to form target.
"bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ")
"bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ")
"bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ")
"bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ")
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 1000`
* All strings in `words` have the same length.
* `1 <= target.length <= 1000`
* `words[i]` and `target` contain only lowercase English letters. | null | Database | Easy | null |
201 | okay are we live i think so what's up stream hello world let's just make sure we're live hello sweet okay so welcome we are going to take a look at another question for lee code right try to spend not too much time on this rather yeah another medium question 201 bit wise and of numbers range given a range m n where zero is less than or equal to m less than or equal to n less than or equal to it looks like two to the 32nd minus one or is it two thirty first because to the thirty first minus one it's probably unsigned meaning there's one less bit quickly check yeah it's 2 34 minus one given this range of unthrough unsigned into positive untimed integers excuse me turn the bitwise end of all numbers in this range inclusive oh that's interesting so oh very unusual so one approach is looks like this um actually you can do it this way that works too so this is one approach however the problem with this is two this is slow this won't work for very large num range ranges i mean use the brute force approach um you can do two one four seven four eight three six four seven just make sure you did that correctly um yeah we did okay and this might be too slow though yeah okay time limit exceeded all right so pretty simple oh um you know what i forgot something also oh no i wanted to get my stream uh where is that how do i get that i'm pretty sure um where would i go i would go to where is it live though my question would be my channel maybe i'm already here but that's okay here we go post this quickly there we go um so this is brute force now the question is hello hey how's it going fedo welcome back hello welcome the question is how do we um how do we improve this run time we want to do anything that's either constant time or logarithmic time but linear time is not going to work so we want what do you want to think about this um how can we do this also a question fedo uh you don't have to answer this if you don't want to but are you erica by any chance because i noticed um i don't know i'm just curious you might be i'll just say i'm curious i got this suspicion that you might be in i'm wondering i'm curious um if you end so the deal with ending things there's got to be a way to do this right so the deal with like if we just did one through ten right um what's interesting is so one two three four five uh yeah six seven eight nine ten 6 7 8 9 10. so the deal with and is the first bit is going to be a zero if you have at least two numbers right because these are all consecutive numbers right so if you have on audited even this is going to be a 0 always in the first bit the only time it's a one is if it's one number and a the range is only one number and it's an odd number what i want to do is i want to do a bit wise sort of interpretation basically you could do a logarithmic time or bit wise you know or you call it linear in the number of bits if you consider each column and you have a relatively quick way to figure out the value of each column so that's the condition for the first column um there may be a better way to express that but that's um nope not erica okay all right i was curious for the second column though if you have an element from so if you only have elements from i guess you have to make groups right so you've only have elements from these groups then it'll be excuse me did that wrong this yeah this group oh no i did it right and then it would be 11. if you have only have elements from these groups of two these uh alternating groups of two right obviously zero you could say zero now another question though is there's kind of another issue where if you only have elements from these groups of two then that second bit is always going to be a one otherwise anything else you're gonna have a zero for that second bit and you have a similar condition for the third bit um one two three four really i should where it's got to be in these four fourth groups it's got to be exactly this range pretty interesting question let me um i think i could maybe come up with something just from this alone um thinking i could come up with something here i like i prefer to use underscores i really don't need to do that but i like to do it that way um so my thinking is really each bit is like that right so the first bit it's got to be every group starting at a 1 every other group right so that's 2 to the 0 is that has that pattern then the 0th bit or we could do the if minus 1 bit right so zero the zeroth bit then for the second bit it's groups starting at so the index you start at is actually um if you make this 0 1 2 this is that's the to the first so for the second bit right let's start there and then the third bit starts here right um that's sort of the grouping of these patterns and then you've got to have in order for that so you can loop these for each bit you have this sort of rule that starting at that position if your range is exactly um that size at that starting position so size one starting at position one or is that size and starts at some offset so it would be like um for four you have another four that are zeros um so you'd have some offset i don't know we'll call that uh two raised the i minus one um plus another offset that's like an initial offset and then there's also the size of the range and then an initial offset of some k let's just say k uh where k is an integer right k is just some integer um times that same offset times i minus one is that right or how much is it offset by no this is offset by two it's actually k to the i so it would be one with the size of one three with the size of one five are the size of one right at these indices and then uh the next one with two would be starting off at index two now obviously this is zero with index zero indexed these eyes you could maybe call if you call the eyes the zero index also then this is actually slightly more we would make both of them zero indexed the first bit would be the zero index it's a little confusing but we could do it that way too so then the four the groups of four will be starting initially at um four and being a side of size four right so four five six seven and then also could start we could also have so it's four and then plus um eight so we'll go to 12 would be the next starting point right which is exactly i don't know um yeah which is exactly correct right that would be this next bit this should be a one here um so four twelve twenty et cetera so what you can what you do for each bit is you check the you can use this rule for each bit to determine whether or not that bit is a zero or whether or not if this rule holds that i just described for each bit then that bit is a one if it doesn't hold then that bit is a zero um and so you can determine bit by bit what the uh and so you can build your in the returning integer using that so that should be the algorithm that we want to write so let's see if we can uh let's see if we can code that uh what that's going to look like is so this is our initial this is a brute force initial kind of approach and now we want to say um int ret we'll call we'll start with zero and now the thing is um yeah we can go backwards that's stuff that's fine i think because i want to push to the left um the bit that i'm interested in so um excuse me uh we do 32 bits that's fine yeah okay we can do right or excuse me if you do is it 31 bits with 32 bits let me see let me just see something here um i use i we could use x 32 i think it should be 31. um x is greater than equal to zero or just greater than zero or even just x right that's yeah that's great zero and then minus x i'm gonna go kind of backwards and then we're gonna red um one and then return red i just want to see what numbers do we get when we do this output zero um oh yeah oh that's interesting right because it's okay yeah so the reason why this is a zero is because this is an unsigned integer which means so actually we have to do it this way then yeah we do really that's very interesting um let's start off with a one and then we need to do or not with a zero rather if we do zeros what do we get if we do this we should get the largest value oh no wait um oh no really i don't know i don't actually know i think i'm making i'm doing something wrong here oh okay i think i know i'm doing wrong all right i think i got it um this is a bit shift by one to the left which is not the same thing as um what should what i want is or one i wanted to actually push a one and then [ __ ] shift one what does that and then [ __ ] shift one what does that and then [ __ ] shift one what does that do yeah that's more what i was looking for i think why uh let me get negative two okay that's interesting um there's another way to do this too which is there's another way to do this which is uh probably better um one shifted to the left x times what does that look like no uh can you do 31. why though maybe um maybe that's why i got i've had this wrong yeah it's okay that's it's a little confusing but yeah that's what i'm doing wrong okay i understand now um however we actually want rep to be itself to be bit shifted by one and then or that with a one that's more what i want to do there's a slight different slight difference between these two operations you could kind of tell what i'm what it's what's happening but this one you actually are just bit shifting a one to the this x position and then you're ordering these two integers with this result with this red value so you're flipping that bit to a one setting i'd importantly setting it to a one um i'm not sure this is any faster slower than i think this uses slightly more operations to do it this way this on the other hand actually takes the same integer that you're already working with and shifts everything down and then ores a one with the uh actually i think i like this better i think it's better due to the way that i think this is it's better to do it i think this way because you could start off with zero the zeroth index and then say stop at um the 31st position and then we can increment x this way and this will work um what have we got negative one okay yeah all right that makes sense the so there's 32 bits in an unsigned integer um a zero at the front means it's positive on the in the 31st position it's the 32nd position but from zero index is the 31st position so we don't want to touch that bit or if we set all the other bits to a one we get two to the thirty second to the thirty first minus one now also interesting thing about unsigned integers or science sorry it's a signed integer the interesting thing about signed integers is their two's complement which means all zeros i think is a zero and all ones is a negative one something like that it's kind of funky how it works um two's complement so the way that you calculate a negative number so if we set i think we did something like um i think you can if i remember correctly i think you can do uh something like this you can do zero i think you do something like this can i do it a binary literal a boolean literal integer literal um there we go zero b yeah that's pretty interesting so if we do zero b and we do one two three four five six seven eight nine ten eleven twelve thirteen fourteen 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 and we return test this should be a negative oh zero b what is uh um first digit is the most significant oh okay right so this is so this that's kind of neat so this is the one we had up here but what we want is something like this if we throw a 1b in there no that should be i think a negative one oh really like crazy i'm missing something here uh shucks can i not do what i'm trying to do what does the capital b do i'm a little confused i throw another b in there what do i get oh okay so i think if i don't fill all the way to the end with the so yeah so the first digit is the most significant i think that means this is reversed so if you do um having some fun with integer literals here um if you do like zero one i would expect that to be a three but actually i think it's going to be um six you might think that's a three but i think it's a six oh it's a three no kidding i guess they just i guess to the left they append a zero then so if i did huh so this should be i could do this then and this will give it should give me the same thing as test two yeah okay now we can figure finagle with two's complement so what's going to happen is if we want a negative one i believe this is negative one and two's complement i think what you do is you flip all the bits and add one or subtract one or yeah add one and that's the negative value or is this negative two actually i don't know what this is going to be i don't remember what the algorithm is for two's complement that's what i'm trying to remember how it works it's like you flip every bit to flip every bit so this becomes a one and then i think either subtract one or add one i don't remember we'll find out if it's subtract one this should be zero if it's add one then this will be a two and if it's either zero or negative two for number five negative two so you add one right that was why we were getting negative two before you flip every bit and add one so if you want like i don't know um and you do the other way around if you want to go from the negative you want to go from the positive to the negative you would subtract one and then flip every bit right so if we want negative three we're gonna go these are all zeros and hold on let me do it this way um if we want negative three would normally be this guy right yeah see three if we want negative three what we would do is subtract one and then flip every bit so everything becomes a one here on out this should give us negative three unless i'm mistaken there you go yeah so that's two's complement pretty nifty stuff so in our case though we want to keep zero in the most significant bit all the way to the left um that's what i was trying to get at a little bit confusing not confusing but just a thing of note and then you say so there's an if condition here and that if is what we were just describing before with this algorithm say two's complement's kind of interesting but that's how you fit um negative and positive numbers integers in 32 bits is that you put the first bit as a zero or one and then you have a little algorithm that's very simple algorithm to convert between um negative numbers how to represent negative numbers and converting between negative and positive excuse me that's how it's done so um yeah so we want to do is say okay for some i or x in this case you want to check that the size of the range is so we say size of range is exactly uh 2 raised to the x and initial position of range is that's above to raise the x offset by sum k times 2 raised to the x plus one and you can check that um and that should give you that's the condition that we're gonna check here so we'll say the range is exact so say the range is exactly the size of the range is 2 raised to the x means to say that um uh if you say m minus n plus one that's the size of the range is exactly equal to two rays to the x that's a bit wise operation you can do to compute powers uh powers of two quickly so if x is zero this is just two raises zero is a one um and oh not minus ten and if you do uh you know whatever x is right that's two raised to the x and then you say and the starting position m is equal to now we actually have to do a modular arithmetic here so m we want to say is equal to m we'll say m modulo 1 x is that has got to be equal to um and it's actually x plus one that's what we found before and that's going to be equal to um one raised to the x and i think that's it i think that's what we want let's see if that works check them files wrong answer nice um oh that probably that could be it i don't know um let's do something here x see if we ever get true okay that never returns true all right great um trying to figure out which one is failing so expected should you should have something to the first one um so something should be true here x so what i want do it this way we'll do uh check one do check two this could be it could be the parentheses that i'm using also i could just be writing inscribing this incorrectly somehow check two zero interesting oh so actually the first bit is the one that's the first check is not happening so in order to get four you need zero one which is x is two when x is two this is two squared is four and minus n plus one has got to be equal to four um yeah that's what that's the algorithm that was so we found over here and this is from five to seven right so from five to seven oh it could actually be i'm wrong about that it actually could be i did this wrong yeah it could be it has to be less than or equal to has to be a subset of this range so it doesn't actually have to start at this range it just has to be a subset of this range which means it just has to be included in these two bounds um let me think about that how do we include that in this bound on the bounds well you can oh that's very interesting huh oh well you can take modular arithmetic use modular arithmetic to okay use modular arithmetic to bring both of these bounds down to the base which is four and seven in this case and then you just have to see that your the values so you take your values m and n use module modular use modular arithmetic and then check that they're included in this range that's pretty neat okay and do a range check is um it's just well a is less than or equal to b right so it just has to be um looks like it's 2 raised to the x you could take a and b modulo and b just has to be less than x plus 1. um so you take a and b modulo 2 raised to the x that's interesting i mean that's still that's not bad at all but that's definitely different from what i had it's a good thing we ran the test cases uh we'll do int i can actually even do uh m i don't know like m mod or something i'm not really sure what i want to call it m modulo oh no you i don't know yeah okay all right m mod and then i think you do the same thing on both of these i think you do and mod these are is that right it's actually x plus one both cases that modular part was x plus one and then you say if m mod is less than or equal to a which is or no one x and you probably could speed things up a bit just say yeah that's kind of okay let's do uh let's do this um uh how do we do this ah i know what to do we go that's what we want at the end we'll update the position in the next position i could do it this way and now we can say now this position is two raised to the zero initially so we actually want to do um we'll move with position over one more in both of these cases let's just say p1 position plus one then now we can say position less than or equal to m mod and n mod is less than position p1 then we don't even need to we can just use position there you go something like this it's too large oh um i did that wrong too wrong answer shucks hmm it's taking a lot longer than it than i probably should i think it's gone over time on this one here um very close though um position is one uh position p1 is so this then this is two one and two and we would say uh mod modular one modulo oh no excuse me modulo 2 for the first bit which is fine right it's either the first bit is zero one and as long as no this is wrong this doesn't make sense no it's got to be well they are con no they gotta be continue they're continuous but they have to be um no it doesn't work like this i think you also need i think you need both conditions that m minus n plus 1 is less than or equal to the size which is position i think you still run into some problems but um the initial position being a one uh so you've got to have a is less than or equal to square a is greater than equal to 1 and b is less than 2. after you take these things modulo two that's the fur for the first bit yeah and then the second bit and the third bit the thing is we got a one here for these two for let's say five and seven somehow we got a one for five and seven i don't want to check y we should have gotten a zero because this was three seven minus five is two um oh it's a plus one or minus one three less than or equal to position which is one so this should be false for the zeroth position um how did we get five is one zero one that's definitely not right uh how did that happen um i don't know how are you missing something here i'll say this is taking a lot longer than i thought it would what is going on there message retracted oh um i can't see your message um this should be am i going crazy here negative one oh that might be why i completely forgot oh that would make sense and yeah m is smaller than and kind of silly now um cannot be represented type in one um what let's just be that oh huh what is going on oh you do run into a problem here don't you uh you don't need to say for the last bit i could use longs for these i guess actually no what is the oh my test case oh look at that wow you could just do that calculation once i guess position has to be updated too long then this is kind of interesting that's not really what i want though um wow this interest this problem got definitely got more interesting um you know you can do actually forget that uh there we go that'll work less than or equal to position minus one there we go i need more test cases now just do random numbers i guess um uh all right how do we do oh um and have value what oh all right that's kind of somewhat convincing we can just go for it i think there's i probably missed some edge cases somewhere along the line there's a good chance good job did you get banned on twitch thank you how's it going yuki uh welcome back hello yuki are you uh wait i think i know who you are ah you are uh i'm pretty sure you were the fellow who you dodged me on um discord when i wanted to talk to you i'm pretty sure it's you what's up man welcome back nodding a band on twitch i just uh i just left because of um uh mister um you are way too good at remembering thanks brother i am a software engineer all i do all day long is remember things read things and remember things all right never mind i'm not gonna i'm not good never mind nevermind forget i said that i forget i said that let me go with that post posting no reason to boast nothing about anything that's good in me is from god and nothing to boast about but um i'm glad you came back glad to see you again no i didn't get banned i uh the deal is i um the content that i make is way better on youtube because people can come back and watch the videos and i decided to be better to if i'm going to do these problems one by one to actually like kind of cut the video i demand camille streams what are camille streeps is that uh i don't know uh camille is a champion in league of legends so i'm wondering if you're asking me if i should that i should play league of legends excuse me um league yeah you play league dude i thought you get you one trick trend i did yeah i um i uh it's gonna give me it's gonna give away a hint who i'm pretty sure i know who you are and i said i was i wasn't gonna out you publicly but i thought you only played fortnite man i didn't know you played league unless i'm wrong about your identity um but that's interesting you have an interest in league but yeah one trick trend that's true i did i had one trick to diamond um right camille is a league champion i uh i don't really play camille she's fun a fun champion but um what's going to say about camille uh i just don't play her yeah i can only play trinimir with the league i kind of can't play video games for a while i have uh look at this i kind of have like other let's say other priorities something like that just put it that way just say vaguely of other priorities not vaguely i mean i can go into detail but just at the moment i want to actually want to finish this video um nevermind linkedin go through you get if it's like a youtube video you can give me um you can give me uh like a watch like uh one of these things like this part this piece the stuff the suffix um let me all right let's go for it i probably missed some edge case and i'm gonna be sad about it but let's go for it yeah oh shucks not an edge case but just a case oh i could cry i get so sad and i cry but i'm sad um i should have tested more stuff yeah because this is kind of wonky this approach this is like there's definitely room for error here it's a little bit hacked not hacked but it's not complete i knew there was like a i knew there was something that i probably missed uh i'll put two expected zero all right three and four so three and four should be um yeah so these should be zero so the first bit it's range is two which is less than or equal to um two raised to the well less than equal no that should be a zero um and then here the range is two which is less than or equal to two however three modulo um is this is zero one index two squared yeah the position is one it would be four three modulo four is three and four modular four is zero so four modulo four it's gonna be less than zero no it's got to be less than i think that's actually one more oh wow oh no kidding oh no yeah see actually because you're taking modulo you need to have this needs to be less than really no kidding is that you have to add that in there too i think this might be wrong i probably missed some cases still yeah i think what has to happen is these values can't oh no so i brought the values down by stripping away the offset however the offset has to be the same meaning these values still have to be one still has to be larger than the other after you strip away the offsets oh gosh still wrong come on man um i'm not as good as i should be i think i have the right idea i just kind of missed a few pieces to it now why is this one wrong output uh am i just missing one bit is that it oh no yeah i thought about that yeah i thought maybe i would be missing the last bit no come on man you could do this i think this works let's try this it's just to get it to work properly no left shift of negative value ah i think we did a long no oh man i'll reach out in a second i did some something kind of foolish here let's see if it works that's kind of sad uh i had the right idea i just implemented it wrong oh no yeah when you're finagling with ranges it gets can be kind of funky no i need to get rid of this long here um what i can do is uh um yeah okay this is what we're gonna do we're gonna take x we're gonna say position is equal to x we're not going to use position there at all that way we don't need to does that still work left shift of negative value i think we got a long position here yeah because this becomes filled um oh boy no it's just the opg the rank one on eu west nice thanks yeah we got there i goofed but rank one on the us oh because he's a trainer player now or is it camille player i don't remember who it is i don't know it changes from month to month rank one go rank one is uh platinum one no uh leaderboards right um this is like what wow janna 400 jada games is that a joke are you kidding me i love playing jonah by the way john is awesome what does he play um support it looks like support i don't know yeah support are you is that a joke are you serious you're kidding me rank one challenger is a janna jenna one trick that's ridiculous that's so funny wow oh no kidding uh that's hysterical yeah um i want to make some comments about like jesus coming to the earth as a servant right because the support's basically like a slave uh i want to draw some parallel there not to com not to i don't know i don't even know what the parallel i'm trying to make here um let's just say god calls you to serve calls you to be a servant god calls you to be a servant um that's funny though that's amazing wow one yeah i like jonah i like playing john she's fun she's good it's good sport probably my favorite sport probably one that i play the most i could learn from this guy man i can learn from this guy is this you is that what you're gonna tell me is that you bible study um yeah quick note on the bible uh all right i should end this stream here i actually i want to get food um what i want to do is i don't want to use longs at all i don't want to use long so i want to try to use finagle this i can only use ins for this whole thing what you can do is um hmm basically skip the last bit that's what you want to do so we can go all the way back that's what we had before let's go back now yeah the 31st position the 30 the 30th so this should work still no or it'll be wrong but it won't cause a runtime exception okay now we're going to do the last bit um set position no uh what do we say hints and mod equals so we don't have to do position plus one because that's just the entire range like there's no reason for this anymore so we can do um if n minus m less than or equal to now position at this point we want to increment one more time we don't actually need to perform these this result here and this isn't necessary either we do still want these potentially uh this doesn't matter anymore either because th this bit is the entire range i want to say um basically if m n and m are less than or equal to i don't think you need to do this check anymore either because 2 to the 31st minus 1 is um it's like accent um just thinking how do i get the max integer really this is the max integer i'm just thinking what am i missing here the only thing you need to do uh shucks the last bit they cover the entire range at that point so they just need to be i think you only need to check that n is less than or equal to um i want to say position or excuse me it's less the position is less than or equal to n m is a smaller m yeah m then you say red or equals 31 i want to say something like that does that work oh no okay huh oh whoops no um uh is that right what is this value it took me so much time to do this too to get this oh wait what oh the only problem yeah okay interesting that's not really an issue then huh or even just right shift again oh okay it's so confusing because i got all this the shenanigans going on with this these different well what i wanted to do is bring the run time down now i don't know if this is still correct it might be oh it is there we go that's faster that was the whole point of that it seemed like a lot of uh a lot of extra effort just to get the run time down so we're pretty fast um this took forever though this like as an interview question i think it took like possibly an hour on this it took a long time um i kind of would get nailed to the wall if i had to do this in an interview it's not that much faster just using integers but um yeah i think in an interview i would just use longs and do the same logic that way everything fits in the buffers what is the basic idea you would take um m and n strip off the range so that way the values are sort of shrunk down i guess and then you just want to make sure that one is still smaller than the other because you could actually have the two values be in two different ranges so to speak and then they kind of cross each other and you also want the size of the range actually no it's not that they would cross each other it's just the size of the range guarant you check this range check guarantees that you're not like yeah two different values in two different pieces parts and then also you need to make sure that you're not looking at values that cross each other when you lop off the offset because that actually means that they're not within even though the range is the right size they're not sort of in the zone that you want to be in it's kind of confusing to say but basically there's a few cases where like you could have you know you could have like values here where this one is in the range but this one's not and then you need to make sure that when you remove the offset so in this case this goes to zero and this stays at three um that this is still less than that otherwise that's an indication that you're like on a boundary or something you know you don't want to be on a boundary you need to be firmly within so if you're firmly in the range then when you remove the offset you'll always be the smaller one will always still be less than the larger um and then that'll guarantee you're in a particular range and then um to guarantee that you're not like between ranges then you want to use the range check so yeah it's kind of pretty interesting question um really good question i really like this question i really might have made a mess of this though i mucked it up pretty badly i definitely could have um what i do wrong here yeah i missed the range check i had wrong because well i did a couple things right so i could have just used longs to begin with and i wouldn't have run into that i ran into an issue with like um basically a buffer over no buffer overflow but like not you couldn't fit all the data that i was working with in an integer because uh you know this is how i did it um so i needed to use larger values larger i guess call them buffers larger widths larger integer widths and then um that was this one and then the first one was i just forgot really forgot didn't think of you know what happens when you take things modulo when you lap off the offsets it is possible to have the values flip in their position if you're not really in the range that you're looking for and then we do this range check you actually make a mistake like it's not yeah it's not necessarily the case that m modulo x is less than or equal to n modulo x anymore but given this problem you actually have you can you that's uh you must have that in order to that will be true if you're if and only if you're in the range if you're out of the range it could it'll be not true actually it's actually an if and only if you're in that in the range it's guaranteed that you're going to be still less than but if you're outside of that range then it's um if you're outside of that range and also within a single sort of block um then it's guaranteed that actually you're gonna end up with these positions flipped right so if one is outside and the other's inside and your own you're guaranteed not to be going over into another one beyond then it's then if you then yeah when you take modulo they're going to be the other one's going to be uh on the other side on the wrong side that's pretty interesting that's definitely really interesting to think about how that works is some finagling with modular arithmetic here yeah that's a good question i like this question a lot i def i definitely could have caught that though if i thought about it some more i don't know it's like modular arithmetic can be yeah it can be a little bit it's a little bit much but anyway okay so thank you all for watching hanging out saying hello and the stream here uh i'm gonna get myself some good work thank you thanks i'm gonna get some food uh probably come back in like an hour and then do another problem of the stream so take care thanks again | Bitwise AND of Numbers Range | bitwise-and-of-numbers-range | Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1` | null | Bit Manipulation | Medium | null |
148 | Okay so let's start possible what is life you have life d head of a linked list return d list after sorting it you have sorted it in ascending order ok so Every you can see it date is life you one four you one three give you have sorted in one you three four okay so let's start with example so this example in the worst how date is but you have not apply this because same you have B think of something else date this butter give it so what you can think of simply look at this we can apply mast note in this we can apply mustard apple in this what does it mean we guys you should have two things in this in mast shot First report of Mast sorting and Mast shot in tu friends, if you did not like it then I will tell you step by step ok so let's start with an example what you can think of simply see this is our link given below Gai to first fool but I bill do in that we have to find the first half of the bill and will sort the second half, give them the bill do just imaging of just you, I have told you in the video that you rape in that also. But you can see her but first of all they need you find the middle of N linked list ok every you can see it date I have used n partition every by finding d middle of d linked list so in linked list what you can think of partition but they always make 2 painter date it slow and fast painter first of which you Have you close this values in D head find us you close this values in D head find us you close this values in D head find us slow and fast and where to put hair position and what do I have to do what is the meaning of hydrogen four meaning initial d initial note of a linked list scholar head okay because head point This is what the formula does, we will hack someone on the first position. Okay, so what happened when we got the head, so what did we do. To find out the middle, we simply have to find out the slow and fast point. See this. Our linked list is, we have taken slow corn, fast and slow, we will run one question in one step and for fast, we will run it in two steps. Okay, so I have added slow again here and fast will run on two points, meaning it will run in two steps like this. Condition here, where our fast will be, it will point to the tap, it will be the position of time slow, date is 22 D note of a new link list, meaning I have written here when our then D slow bill indicate D head of D new link list then This is what has to be done that whenever we tell people where will the slow and fast go, one will start its fast by 2, where will the fast point from where will it reach and the other will indicate the slow painter, then head now new link list. So I'll give you a look here what I got here is na slow point this candy cut its new so I'll do my breakdown here and what I got one of it is de indicated d head of d new necklace so I have Distributed me linked list in tu parts, devar is on and second part, first part is four and you and second part is one and three, okay, so what will be our two linked list, as much as we have understood, so what have I taken out middle Got it out, now what I have to do is to sort the first half and you have to sort the second. Give I have you mast d both d link list and getting okay so after that what will I do. Simply you can think of this is 42. Paste went up a little bit, four is four, one is three, what is our link, so I partitioned it from here, okay, what I did was, I found its head, what will be the flow because of this, what is indicating look and indicating is D head of. So this is what we told indicating D head D new link after date time variable. What is our previous point which will be till the point which is what we told that our first linked list is on time but we have to indicate the date and time of this. Kya tha hamara abhi hai tu pe tu kya hai hamari which is for the first link, the last one is indicating the last line note, so that point pe nach null should point to null so I have created a variable on what you team. Okay, look, the earlier link is not in this, that too will have to be indicated as null on the story, because what is a link list, it is always null, so the thoughts are the same, we have used D10 painter, so represent the previous note of a first link. Okay, so this is what I have done here, so four you say I have to do it and 13 has come, I have not taken it, after that what I have simply done is let me shorten our link list. Okay, so what has happened is our link list is done. After that, after that, what can you see, what I did, what was our second step, what I am getting, yes simply, two four came, after that, I started on 13, one three is sorted, one three only comes after that. What do I have to do, I have to watch these two, so I will march inside, one, two, three, four, this is what should come for us, the output will come, okay, so what will I do, simply, I have shot both of them first and marched. So let me show you the code, what I did, okay, first of all, what I saw is that if our hair painter points to what null and the next null of head, then we will return head, what does it mean, head = ll, it means only our what does it mean, head = ll, it means only our what does it mean, head = ll, it means only our Slow Painter is present next to head if it is null what does it mean we have only which one we have fast slow and fast both point to null if it points to null what does it mean we have to return head What does head mean only ours Only one note is present, okay, then we will make a representation from it. Okay, then what is the meaning of and? If any one of these conditions happens, then we will get it hacked. Date they do not have other meaning painter our If there is no note nearby, otherwise we will simply hit it. Okay, what is there after that, I have made three number variables, 10 low and fast, slow and fast, I told you that it will find on the head, the time variable is pointed at the beginning of tap because look. In the beginning we have to find out, we have to sign out the last element, then we will keep the initial as mail because later we have to go and find out, what did I do, we will have to remove the middle, otherwise it is correct, then what is I, see the fast point. Na Next key, see, what is our condition that slow painter is five points, there should not be taps of both, here fast is not equal, you are not and next is not equal, here you also had to write nautical and fast's next. Equal is null if next note is equal if this condition also happens from what then what I did is initially put on flow variable and slow is increased by one less big five is increased by two less okay I have done both then what I did when it is null Will see, bring this, if when will it come out of the value, when will our fast one also reach, then the one who will be this slow painter, then what did we tell him that what is our slow painter, then note means D first note of second link list is fine. This was told because see what we are doing here instead of what is here, look at where our fast point is, where the tap is reaching, see what is our flow, what is the painter telling, first note of second link left, this is what we wanted to tell. What will happen at this time, what will be the stem, what will be its first value, if it is told then it is the first link list, its null value means that it will end less, so what I have done is that what will be the stem, what will be the next of the stem, it will be told to null, meaning look at this, let's go. Here is our step by step process and where it will end. What did you tell us? Our net of 10 is fine, we will tap it next, now stem, what did I do, have you been sort of both of them, which is the link list that we have. -Two lists have come, we do not have to sort them, neither -Two lists have come, we do not have to sort them, neither -Two lists have come, we do not have to sort them, neither mine nor mine. In the beginning, we have told the value till every point, so this is our first link list, what will be its head, it will be the head, but what will be the head of the second link? What is the meaning of our slow variable flow? Look, I told you that this is a link list, we have another link like this, so the starting one will have the same head, which means oil pastel, which was in the beginning, will remain the same. But what will be the head of this linked list, which is our slow painter, right, this is the head of D second linked list, so I got this returned, okay, so this is where I got this returned, after that what did I return? Is my list meaning my function was I have done it yesterday in this l1 and l2 of five passed our list so what I have done here so sorting of both D Mercedes okay so what I have done first of which I have read d lift on F = first of which I have read d lift on F = first of which I have read d lift on F = Na and Fati = Null, what does it mean, the final Na and Fati = Null, what does it mean, the final Na and Fati = Null, what does it mean, the final head is null, I have nullified the final oil, I have created a variable in the starting node, okay, what did I do after that, white head one, note it equal, tu na. And head tu it note equal tu na what are you telling that what we say means us they have you have de link list till it is not finished the caste is telling him that the head one is what is the point while not null It becomes date, it has not yet traveled the first link list, it has not yet traveled in the second list, this condition is telling head one, what is the meaning of indicating de no elements have they edited tu de Mercedes, what is the meaning of our which is the leakage. There is no note or element in it that has been marched to you yet. We have not added to it, so I have put a simple condition that if the value of head one is greater than the value of head two, then what will we do in the beginning? There is a head and the final starting in the oil, see if I simply tell you, see our link list, what is the motive of the link list, see what is the motor of the link list, date, way, you have returned, link list in ascending order means one, two, three. Four such, we have to notify it and what was our starting 4 2 and 1 3. Okay, so what should we do in the comparison, these two will be smaller by com, they will come first in our link list, so this is what I have written in it, look at both. The value of the head which will come to both of us separately, which we have distributed from me, we will not keep the one for whom it is the creator, we will keep this one in the head and whom will we keep in the oil, which is the small value of ours, we will keep it. This is what I have done in the head and oil which is the final head and oil, what is the value kept in it which was our small one yesterday A, okay initially they have point it out you are the head of the final, we will keep it in the beginning only because we have to What to show in the link list? If we have to show the smallest value of ours, then I have placed the oil on the final head here at the beginning, okay, I have pointed it ahead, why have you pointed it because that is our If it is a small value, then our second note will come that I have pointed ahead, similarly, I have checked what is in SS, if the value of head is greater, then what will we do, what value will we put in f2, which is ours? The new value that will come for our fe and fati, which thing will come in it which will be the smaller value, so similarly I have done here that whichever of these values will come in the smaller value, now yes, which value will come in the values will come in the smaller value, now yes, which value will come in the values will come in the smaller value, now yes, which value will come in the smaller value, head tu's value is greater. Look, its opposite will be in S, which of our values will come in the head? The in S, which of our values will come in the head? The in S, which of our values will come in the head? The value of the head is greater than the headband. What does it mean? If it is the headband, then what should we do in both of them. We have to calculate the value of the head one. We will make the headphone bigger in the future. Whatever value we have to do ourselves, we will do it next because that is what we told that after this, which note will add ours, okay, IF add one, this note is equal, you are not equal, what is the meaning of this, check both notes. After the previous condition has happened again but the head, you are still not null and what is ours, both the Lincolns, who are there are some elements now that we have children, so what will we do, where are both the heads, you are the value, right from this. If it is greater then which one holds the value for us, it holds the same value for us, now which one is smaller, look at the smaller headband, have you torn, how much value has been given to us, head one has gone and head one will point further, similarly, what is there in S? This will be our headband, here the value of head one is greater than head tu, it means the value of head tu, what will we keep, we will put and keep increasing the points of our F and will make head next. Okay, then what to do in the last. IF head one is not equal tu n head tu is not equal tu n what does it mean head one is not shaken what does it mean head one has some element dat they need tu and now just to do there are children okay similar But head, there are still some elements in it which we have not traveled here, so what will we do, it is simply acting in its next, okay, will this value come in the next, then it will be the best and F, what value will come in it which is ours? It will be small, like this we will keep doing flowers and in the next we will put the value and in the last you will get the return done to FC. Why should we return this truth because how will we run the link, all small, then bigger and yes, what value will come? We are starting from a small place, so that's what we invested in, so that in the end, we got so much effort returned, okay, I told you in a very easy way, now what I wrote here, we cities become big and people come in because We know the time of the cool shot, what is the city, big bus, n log in and face complexity, big of one, what is the meaning of bigf one, because it is not used, other extra space, we did not do it, no such face is doing it. Here we will have to store the values. Okay, we have not done anything, so what will be the space complexity, it will be big and one A. Okay, so this is our very simple code, I told you can see it, so I am Bill, people must have understood. Thank you | Sort List | sort-list | Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)? | null | Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort | Medium | 21,75,147,1992 |
658 | okay so lead code practice time so in this video there are two goals the first goal is to see how to solve this problem and then you're going to do some coding work and the second one is to see how you should behave during a real interview so let's get started the in the real interview the first step is always try to understand the question ask some clarification questions in case you have anything unclear and at the same time think about some ash cases at the very beginning to see what you should do especially in the next step so let's take a look find k closest elements so given a sorted integer array two integers k and x return the k closest integers to x in the array so the result should also be sorted in the other all right so let's see so a an integer a is closer to x than an integer b if the absolute value of a minus x is smaller than absolute value of b minus x or if they are equal and a smaller than b so integer is closer to b okay so if the absolute value the absolute difference is the same then we choose the smaller one okay so let's see example so for example one uh we have arr as one two three four five k as equal four x c go to three then we have uh one two three four i see so the reason it's not two three four five is because we choose the smaller thing over the ladder thing okay so let's see some constraints so the k is between one to the length of the array which means the input array is never going to be empty so we don't need to think about as that edge case um okay and the array is always in so it's always in as any other sorted um so the array the number within the array and the x could be between minus 10k to 10k all right so i think i pretty much understand the problem i don't really think there is um some special ash case we need to really think about so let's step into the next part let's find the solution so how to solve this problem um so i would say uh we need to see so if because this array is sorted yes any other so if the x we are looking for is smaller than the smallest element within the array you just get the first k elements otherwise if it is larger than the largest element within the array then you're going to return the last k elements so if otherwise if x is in the middle then we need to call binary search we need to use binary search to find the corresponding number within the array so if the binary search if x doesn't within the array we just return the closest number to x so it's like first of all we do binary search uh for array within x and it's going to return a index and then we will go we are going to use this index to try to find the k closest element so what are we going to do so we are going to have we are going to search within the range of index uh minus k to index plus k so within this range uh we can find the closest categories number and how are we going to find the k closest numbers so we are going to keep use a two pointer approach so let's say uh i am trying to find one two three four five six seven so let's say we have those numbers and we are trying to find the three uh four closest numbers uh comparing to four so we are go so we are trying to uh let's say let's just say we are going to find uh three closest numbers to four so at the very beginning we do binary search and we find the index so the this is the index pointing to four and we try to extend um on the left side we try to extend the three so this one is starting from here this is the left pointer and similarly we have the uh the right pointer so this is the right pointer so how are we going to choose uh how are we going to move the left hand pointer and red pointer so first of all we compare the absolute diff with the index with um if the absolute difference of the left number uh the la the number pointed by the left pointer if that one is smaller then we try to move the right pointer otherwise we try to move the left pointer but if the absolute difference is the same then we are going to move our right pointer towards the left side so in this case the definitely the same so we're just going to move our red pointer to the left by one um and uh similarly um one and just follow the procedure i talked about before so if the diff absolute dave uh we try to move the pointer with uh larger absolute dave so this time the left window has larger absolutely so we are going to move the left pointer to the right one so the condition we stop moving the left and right pointer is uh the number uh within the left and right pointer uh is equal to k so that's the condition we stop moving the pointers and then uh then the numbers within the left and right pointer would be the numbers we are going to return finally so having said that um this is about the general approach the runtime is going to be locked and so binary search is going to be so n is the number of is how many numbers within the input array so log in for the binary search uh and then we are going to you're going to do uh kind of like a scan um two numbers so i would say it is log n plus k so it is o log n plus k so that's the total runtime so let's do some coding work after you're done communicating with your interviewer about the approach and you get an agreement do certain runtime analysis based analysis then it's time for you to do some coding work so for coding i'll be careful about the speed uh correctness and the readability so let's give it a shot so as i just said um if ar are zero so if x is smaller than uh is smaller than or equal to the smallest elements then you're just going to return so you're going to get the first elements um let's define a helper function so this one it is going to return a list of the integers uh get let's say get sub array so we are going to pass in the array start index and end index so list of the integer let's say new link list um i see zero sorry smart start i smaller than plus i so um all right dot add a r i then finally we're going to return right all right so here we are going to call the sub array turn sub array we are from 0 to k minus 1. otherwise if right so it's not otherwise um if x is larger or equal to ar uh okay it's a r dot less uh minus one so if it is larger than the largest one then you're going to return guess of a r this is a r then the last one is ar dot ls uh minus one so how what is the start index so this would be uh are the lens minus okay all right so yeah so that's the two different cases otherwise x is within the smallest and the largest so first of all are going to call the we are going to do bandit search so i think there is some binary search api um i think it's collections binary search whatever binary sir okay java 8 it's all right so um okay binary search so this is a binary search api already implemented so let's see what it is going to return to us um here so it is going to so search the specific list for the specific object um it's sorting natural order and what is going to return so the index of the search key if it is contained in the list otherwise we are going to return minus the insertion point minus one so insertion point is defined as a point at which the key would be inserted into the list okay i see so we're going to call the binary search um collections dot binary search on top of this ar so it is list i'm not sure so it's it says it is not it's not applied on top of it's only applied on top of the list instead of array um so how okay so for geek binary search all right so it only applies to binary search java 8 let's say array um is there any binary search on top of it so yes so we do have some banner search it's called dot binary search for a key so let's see this so if we combine the research it is going okay so it's the same so we are going to call arrays dot binary search the array for the corresponding number so if the index is smaller than zero that means it doesn't exist then it means it doesn't exist uh in the input array so we are going to change it in to be this would be so it is going to return minus index sorry minus the insertion point to be minus one so you're just going to be minus index of plus one i think uh yeah so i actually could just have it like this the insertion point is defined the point at which the key would be inserted into the array so the index of the first element in the range greater than the key okay so it is minus okay minus the insertion point minus one so it could be uh minus okay uh okay minus if i minus the index it is going to be um minus x is going to be positive in the insertion point positive one so actually it should be uh minus one minus uh zero minus yeah it should be like this minus 1 minus index all right so we have the index of the insertion point or the index of the corresponding number so we are going to try to extend it so first of all the left pointer would be mass dot max zero uh and also this is index minus k e yes so if it is minus k how many numbers are there so index to index minus k there are actually k plus one numbers okay it's i think it's just fine so mass dot min equal to index plus this one should be min in between the index plus k to array.lens minus one all right so you're going to uh and also let's define the final thing you're going to know so we don't need to define it here so we are going to move our left and right pointers so well the right minus left plus 1 is larger than k what we are going to do is we are going to move the stuff so if um all right so i will say in abs l is equal to mass dot abs this is uh array left minus x and let's see abs right um it is going to be right minus this one all right so if um absl is larger than abs so if it is this one so if it's absol is smaller than abs are then we are going to try to minus the right if it is equal then you're also going to minus right otherwise we are going to plus left and finally we just need to return uh get sub ar uh arr and the left and right so that's pretty much about the code um after we are done with coding it's time for us to do some certain testing so for testing we care um first of all it's about sanity check uh go through a simple example checking the logic and explaining how this piece of code is gonna work and also you're going to increase some test increase the tax coverage by introducing different test cases uh after that so let's see let's take an example one i have one two three four five and ks4 access three so at the very beginning uh we compare with the smallest one and the largest one so none of them are true uh so we are going to get into this part so binary search is going to return index as 2 so left and the right so left would be um 2 minus 4 max between two minus between zero and minus two so it is going left is going to be zero and similarly right is going to be zero as well uh so we are going to try to move left and right pointers so we see all right so the absolute value between one and three is two absolute value between three and five is two but uh although it's the same uh we are going to choose to move the right pointer because uh of this f branch so we move so my left pointer is here right point uh right pointer is here left point there is here uh and then we see that the right minus left plus one is already equal to k so you just break this uh well while loop um so and finally we are just going to return uh the four numbers i think we are mostly good uh let's give it a shot okay so it's good uh let's do a submission all right so it seems like everything is good so i would say uh regarding the task case setup definitely set up something that is going to touch this if branch and set up another test case that is going to touch this if branch and also set up a test case like example one which the input rate contains the number x and also i would say another uh test case let's say if the input is one two three five six so you're going to search before which doesn't exist in the array so i would say that's pretty much about all the test cases i can think of that can give us good enough tax courage so that's it for uh this uh coding question uh if you have any question about this puzzle or about the solution or whatever feel free to leave some comments below and thanks for your time watching i'll see you next time please subscribe to this channel have a good night bye | Find K Closest Elements | find-k-closest-elements | Given a **sorted** integer array `arr`, two integers `k` and `x`, return the `k` closest integers to `x` in the array. The result should also be sorted in ascending order.
An integer `a` is closer to `x` than an integer `b` if:
* `|a - x| < |b - x|`, or
* `|a - x| == |b - x|` and `a < b`
**Example 1:**
**Input:** arr = \[1,2,3,4,5\], k = 4, x = 3
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** arr = \[1,2,3,4,5\], k = 4, x = -1
**Output:** \[1,2,3,4\]
**Constraints:**
* `1 <= k <= arr.length`
* `1 <= arr.length <= 104`
* `arr` is sorted in **ascending** order.
* `-104 <= arr[i], x <= 104` | null | Array,Two Pointers,Binary Search,Sorting,Heap (Priority Queue) | Medium | 374,375,719 |
40 | hello friends today the softer combination some to profit the first seed a statement given a connection of candidate to numbers candidates and their target number target find all unique combinations in candidates whether candles numbers sums to target each number in tenders may only be used once in the combination note on numbers including target two will be positive integers the solution set must not contain duplicate combinations so this problem has a slight difference between the previous question which we are given a Candice out the numbers indicators are duplicate but in this problem we are given Candice there may have the duplicates but we can only use that on element once let us see this example we can use the first one and the second one and the six to get is eight but we cannot change the position like here we first use this one then use this one and then use six to get it because basically they are the same we tune we cannot have a duplicate without a list so an obvious solution to avoid the duplicitous first assaulted candidate when we made the first one we just search for if there are some number there are some up to the target but when we meet to the second to one we just skip because if this one will be used when we check other numbers we can find other result but if this one we are not used to will just give it we will not have any problem so that's the sum solve this product we will offer to use their result this you array this and the way sir first her sought these candidates and we will call this a help function we pass the result and our new already she is a temporary list and the candidates also their target and those are index which is zero at first panel general tells this result let's implement this help function first a we will pass on this result list and then we will pass their temporary list there should be their candidates their targets and there's our index which indicate the place we are here in the Kendall's the best case should be the same if their target less oil cuisine 0 this is the best case and if that targeting even is 0 it should be wrong result list we just add we were pastor tempera Lisa to it and then we just return this is the for loop I shall start from the Indians are less than the candidates dollars I plus we tried to add as a current Canada's I include the list then we will recursion to the recursion since result temporary in the candidates turkey to shoot the minus the current candy dates I and the you should notice that the next time we start from the I plus 1 not I because we can only use that element once so we should a star from the next element and the wish it should be ID now the index and then we unchoose this element we just to remove the last element index minus one so how do we skip her the same result so if the I squared index and there are Canada's I you know it's eco tutor candidates I must one we just continue we just give it and as if as I mentioned before we are not miss ending result okay thank you for watching see you next time | Combination Sum II | combination-sum-ii | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.
**Example 1:**
**Input:** candidates = \[10,1,2,7,6,1,5\], target = 8
**Output:**
\[
\[1,1,6\],
\[1,2,5\],
\[1,7\],
\[2,6\]
\]
**Example 2:**
**Input:** candidates = \[2,5,2,1,2\], target = 5
**Output:**
\[
\[1,2,2\],
\[5\]
\]
**Constraints:**
* `1 <= candidates.length <= 100`
* `1 <= candidates[i] <= 50`
* `1 <= target <= 30` | null | Array,Backtracking | Medium | 39 |
217 | hey guys welcome to lead programmer today let's look at the problem contains duplicate so this problem is fairly simple we return true if any number appears at least twice in the array else we return false that is the every element in the array is distinct so as we can see here there is no element that repeats hence we return false and here we see that one element one repeats so we return true here multiple elements repeat multiple times still we return true now one brute force solution to this would be okay fix one number and search for that number in the rest of the array and we can do that for each and every number and keep track of it and then based on that return true or false so that approach is kind of inefficient and probably your time complexity would be n square and space complexity is also not going to be great now think of a better way we want to see how many times an element occurs so how many times does one occur how many times this do occur how many times does three occur this kind of suggests something we see okay one occurs two times in the first example two occurs uh one time and three occurs one time as well so this seems like a table of key value pairs you have your answer the most optimal approach for this question would be to use a hash map and as we go through each and every element we can see how many times has that particular element occurred or if it has occurred at all so if it has occurred multiple times we know that we want to return true and if it's unique if all the elements are unique then we return false so to do that let's just call a hashmap frequency and probably give a better name and then we want to go through each and every element in our nums array so we do that like so and we want to see if that element exists in the keys of the frequency hashmap we do that by checking if i occurs in the keys now what does this suggest just checked if i already exists in our hash map if it already exists in our hash map that means this is the this is at least the second occurrence of that element right if it already exists in our hash map that means we have already inserted it into our hash map so in order to get a better idea here we will have an else condition if the element is not present then you would simply add it to the hashmap like so and set its frequency to one right and in the second iteration if that i value occurs again then it already exists and we know that it's the second occurrence and if and according to the requirement if any value appears at least two times then we are guaranteed to return true so in this case we can simply write return true because if any value appears at least twice so we can just break the execution at that point return true and if nothing works out at the end we don't return true by line 12 we know that we have to return false and this is the way this question would be solved so i hope this makes sense subscribe for more videos like it share it see you soon | 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 |
389 | hey everybody welcome back and today we'll be doing another lead code 3920 subsequence this is an easy one given two strings as Sentry return true if s is the subsequence of tree t or false otherwise so that's it so let's scroll it down first of all we will be just comparing the lens if the lens of both of these strings is equal to zero and length of T is also going to be 0 we will just return true and if the length let me just copy it will be using two pointers method in this solution so if the length of p is not equal to 0 we are going to return pause but if the length of T is not equal to 0 but the length of 3 is equal to 0 but the length of s is not equal to 0 we will be returning false in that case so now we have our time it is a it is time to make our pointer so p and now TP is for pointer p and while SP is less than the length of s and DP is less than the length of a t string then what we'll be doing we will be finding a point where if they both are equal if SP is equal to TP what we'll be doing is just incrementing our SP pointer by 1 and we are going to increment our TP pointer anyways like if something happens or not so after returning it we will just if our TP pass P pointer is at the length of our s is at the end of our string then we know that we have traversed the whole string so if it is equal then it will return true otherwise it will return false and that's it if you have any kind of questions you can ask them in the comments and that's it see ya | Find the Difference | find-the-difference | You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters. | null | Hash Table,String,Bit Manipulation,Sorting | Easy | 136 |
33 | hello and welcome back to the cracking fan youtube channel today we're going to be solving lead code problem 33 search in rotated sorted array before we read the question prompt just want to kindly ask you guys to subscribe it really helps the channel grow so please do that all right there is an integer array nums sorted in ascending order with distinct values prior to being passed to your function nums is possibly rotated at an unknown pivot index k where k is um less than or equal to one and less than line the length of our nums array uh basically what this means is that our array is kind of shifted by k to the right and it may overflow and basically just end up where you started depending on the length of k so for example if we have this array 0 1 2 4 5 6 7 it might be rotated three times and basically end up you know one four three seven zero one two so uh sorry it would be rotated at the pivot index three but it doesn't really matter it's essentially just rotating it a few times so given the array nums after the possible rotation and an integer target return the index of that target if it's in nums or minus one if it's not in nums and you must write an algorithm with big o of log n runtime complexity there's two examples here kind of stupid to look at them because the question is pretty straightforward but anyway if this is our array and target is zero then target is here which is index four and uh if this is our array and target is three obviously there is no three in this array so we return minus one so what we wanna do for this problem given the constraint of a log and runtime complexity we know that we need to use a binary search here and the reason that we want to do this is because the array was initially sorted in ascending order right and even though we have this pivot what that means is that at some point it's going to be split such that the array is no longer increasing but everything to the left of that pivot point is sorted and everything to the right of that pivot point is sorted so if we look at this array everything after the seven is sorted in increasing order and everything to the left of it is also sorted so that means from the four to the seven is sorted and then zero to the end is sorted so we can actually use this to set up our binary search we have to be a little bit careful because we have to be mindful of that somewhere in here we could potentially have a split and that will you know we'll have to take care of that during our binary search but other than that it's going to be a standard binary search now i want to get rid of a lot of this text here because it doesn't really much room to actually go through the problem so in a second i'm going to actually wipe away all of this question prompt an example and we'll just walk through the question with just one of the basic test cases and we'll think about how we can actually set up the binary search to take into account that we actually have these rotations and see how we're going to find our target if it's in our array all right let me get rid of all this text and i'll see you with a blank canvas so we have our basic example here now let's think about how to actually set up our binary search so with any binary search we need to set up our left and our right pointers so the left pointer here is going to be set to zero and the right pointer is going to be the length of our nums minus one so we're going to say len of nums minus one which in this case this length is what one two three four five six seven so this is going to be six right okay so we are searching for a value here so because we could potentially return from inside the binary search let's set up our while loop with while left less than or equal to right and if this breaks then we can simply return -1 because that means that we return -1 because that means that we return -1 because that means that we haven't found it but we'll get to that in a second so what we want to do is we want to figure out our midpoint so we always know that our midpoint is going to be left plus right um integer divided by 2. then what we want to do is we want to get our midpoint value and what we want to do is go through our edge cases sorry not our edge cases our three cases here so the first case is that the mid vowel actually equals to the target in which case we have found our target obviously so we're done so all we need to do here is just return the uh midpoint index because that's the what we're looking for right we're looking for the index so that's the easy case the second case is that it doesn't equal to the target so we need to actually be clever now let's say that we have our numbers here and we'll rewrite them for clarity so 4 five six seven zero one two let's say that um our left is this four here our right is this two and our midpoint what is it going to be it's going to be this seven here now what we want to do is we want to basically figure out what part of our array is sorted because remember we have that break point and we can see that it's here uh between the seven and the zero where basically the array the pivot happened right so what we want to do is we want to check okay is my array sorted uh from the left of the midpoint and the way that we're going to check this is if that is true then what's going to happen is the value at the left so nums of l if nums of l is actually um less than or equal to the nums at mid then that means that this part of the array must still be sorted so that tells us something important so if this part is still sorted then what we want to do is we want to actually check whether or not our value that we're searching for is in that range so what's going to happen is if our value is actually in this range uh then we need to move our right and our left pointer up accordingly so what's gonna happen here is we're gonna say okay do we you know if our value is in this range here then we need to either move the left up or the right down so what we can do is we can say if nums of l if the nums at the left is actually less than or equal to the target and this is less than the mid vowel so that means that our target is contained between the left and the mid vowel indices the values between them then at this point our right needs to move down so in this case the right is going to become mid minus one and the reason it's mid minus one is because we've already established that the mid doesn't equal to our target so we can now rule it out as our mid so the right becomes uh mid minus one otherwise if this doesn't hold true then that means that we need to actually move our left pointer up because we need to now search in this part of the array so we're going to say otherwise left is going to be mid plus one okay so that's that case where basically this part of the array is sorted but what about the other case where maybe this part isn't sorted but this part is in this case we're going to do the exact same thing except we're going to have to change our check here so in this case in case number three where basically the right side of the array so basically from the mid to the right a pointer is actually the sorted part we're going to say if the mid vowel is actually less than the target and remember it can't be equal to the target because we've already established that the midpoint doesn't equal to the target so if the mid vowel is less than the target which is less than or equal to nums of right then what that means is that our we basically need to move our left pointer up to basically search that part of the array so we're going to say left is going to be mid plus 1 otherwise we want to move our right to be mid minus one so that is basically our three cases here and if it seems confusing don't worry about it when we go to the actual code editor we will go through this type it out line by line it should be a lot clearer and one thing i didn't mention is that if we don't find it within this while loop then we just want to return -1 because it's not in the actual array -1 because it's not in the actual array -1 because it's not in the actual array so with all that said let's actually go to the code editor and type out all of these cases and make it a lot clearer i apologize i am writing with a mouse i don't have an ipad and one of those fancy apple pencils i'm still using my mouse until the channel gets a bit bigger so if anyone wants to donate one of those i will love you forever but until now you guys will have to suffer through my uh writing with mouse anyway let's go to the code editor and not waste any more time we're back in the code editor let's type this up so the first thing that we want to do is actually set up our binary search so we're going to say uh left equals to 0 and right is going to be equal to the length of nums minus 1. now what we want to do is set up our while loop so we're going to say while left less than or equal to right we now need to calculate the midpoint index so that's going to be left plus right divide by 2 and the midpoint value is going to equal to nums of mid obviously and now let's actually check whether or not our midpoint value equals the target because if it does we're done so we're going to say if mid val equals to the target then we can simply return the index that we found that midpoint value at which is our mid variable otherwise we now need to basically move our left and right pointers up accordingly so in the first case if the mid vowel is actually greater than the uh nums of a left what this means is that from left to the midpoint our array is sorted so we want to check whether or not our target is in that sorted part if it is then we need to move our left and right accordingly if it's not then what we want to do is we want to search the other part of the array which will be the sorted part so what we want to do is we want to check if nums of l is actually less than or equal to the target and less than the mid value then what we want to do is we want to move that right down because the right is too far so we need to search from basically the left pointer to mid minus one so we're gonna say right equals mid minus one otherwise what we wanna do is we wanna search from and move left equals to mid plus one all right otherwise if this isn't true then we want to search the right part of the array and then we again we need to check whether or not um you know our value is in within a range otherwise we would need to move our left and our right accordingly so we're going to say if the mid vowel is actually less than the target oops target which is less than our nums of right then we want to basically search that from the midpoint on so we're going to say mid plus 1 otherwise we're going to say right equals mid minus 1 because we want to search the left part of the array so if we find our target within this while loop great we're going to return otherwise when the while loop breaks that means that the value is actually not in the array so as the problem tells us to we want to return -1 to indicate us to we want to return -1 to indicate us to we want to return -1 to indicate that it doesn't exist let me just run this make sure i didn't make any syntax mistakes and it looks fine submit it and we are good to go accepted so what is the time and space complexity for our algorithm here well we know that for the time complexity we're performing a binary search and binary searches are going to have a complexity of big o of log n so that is our time complexity and for the space complexity here the only variables we have are these two integer storing variables left and right and that is going to be a constant space allocation so time complexity is going to be big o of log n and our space complexity is going to be big o of one so that is how you solve search in rotated sorted array this question is really similar to find the minimum in a rotated sorted array basically you can kind of use the same mental model to solve both of them obviously you're doing two different things in each of the questions but the way that you'll approach the problem is very similar and the binary search is basically the same so i hope you enjoyed this solution video if you did please consider leaving a like and a comment it really helps me with the youtube algorithm and helps the channel grow if you want to see more content like this please subscribe to the channel i've made a lot of videos and i plan on making a whole lot more so please subscribe so you don't miss future uploads and otherwise thank you so much for taking the time to watch this video have a great rest of your day bye | Search in Rotated Sorted Array | search-in-rotated-sorted-array | There is an integer array `nums` sorted in ascending order (with **distinct** values).
Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.
Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 0
**Output:** 4
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 3
**Output:** -1
**Example 3:**
**Input:** nums = \[1\], target = 0
**Output:** -1
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* All values of `nums` are **unique**.
* `nums` is an ascending array that is possibly rotated.
* `-104 <= target <= 104` | null | Array,Binary Search | Medium | 81,153,2273 |
39 | looking at lead code number 39 it's called combination sum this is a series of three different problem problems that deal with combinations combination sums one two and three now if you have not done combination some three or two i highly suggest going over those videos before you try to do this one it's just gonna make a lot more sense if you go through those previous two videos before you attempt this one but you're welcome to attempt this one right off the gate if you feel you're close to it you just need you know those um dots to connect okay so we're gonna also use a backtracking template to solve this problem it's the same template i've been using to solve every problem in this playlist it's a very powerful template that allows you to solve pretty much any problems dealing with permutations subsets or combinations okay so let's jump into this um we are given an array of distinct integers candidates and we have a target integer target and we want to return all a list of all unique combinations of candidates where the chosen numbers sum to the target and we can return the combinations in any order and the thing with this one is that the same number may be chosen from candidates in an unlimited number of times two combinations are unique if the frequency of at least one of the chosen numbers is different and it's guaranteed that the number of unique combinations that the sum that sum up the target is less than 150 combinations for the given input so we can see here two three six seven the target is seven we're having two three and seven and then here we have eight and we're going to have four twos so we can have duplicates that's the constraint on this particular problem okay so how do we go through this so let's go over the recursion tree and then we'll go over the template and how we can apply a template make some slight modifications and solve this and uh before we do that we'll just conceptually go over what's going on in the template like what's going on in the code underneath the hood so we're gonna start with the slate okay it'll be an empty array and what we're gonna do is we're gonna start here at i and then we'll have a j variable here hang on i'm just going to go ahead and make this so i can grab it okay we're going to have a j variable here okay and what we want to do is we want to go down this tree and we want to add and remove the jth variable as we scan down the tree okay so let's just kind of go over this step by step so here in the slate on our first level of the tree we're going to start at i and we're going to start at j and we're going to put in 2 then we're going to increment j here uh and we're gonna put in three on the slate we're gonna then go ahead and increment j and we're not dealing with the recursion yet we're just looking at what's happening at this first level we're gonna uh put in six here okay and then we're going to increment j here to seven and we're gonna push uh the seven onto the slate all right now that's just what's happening at every level now what's happening when we make our recursive call let's say we're talking about this two here right what do we want to put in our recursive call as we build out the rest of the tree so normally in the other combinations what we did was we went ahead and incremented j and put j plus one into our recursive call and built the tree out from there in this case what we want to do because we're dealing with repeats we want to just go ahead and put in j into the recursive call okay so what's that going to look like that means when we get to this 2 we're going to get 2 and then 2 because we're going to start at where j is we're going to get 2 and 3 we're going to get 2 and 6 and we're going to get 2 and 7. right now let's look at what's happening at this uh level here we'll go back one level and look at what's happening um at that three we can see here that if we uh if we increment j right okay we're here and we pass j into the recursive call what are we going to get we're going to get 3 6 and 3 7. and so you can see that we're going to handle these duplicates if we pass in j plus 1 we're going to get 3 6 and 3 7 and if we pass in i okay we'll get it but then what we're going to get is we're going to get 3 2 3 6 and 3 7. the problem with that is that we get repeats let me just make that a little bit clearer that if we put in i on our recursive call then what it'll look like is we'll get 3 2 3 6 and 3 7. and the issue with this is that we're going to get repeats right 3 2 and 2 3 are going to be essentially the same because we're looking at the target sum and so that's why what we want to pass into our recursive depth first search recursive helper is we want to pass in j we don't want to increment j we just want to pass in j and that way we handle any of these duplicates okay and then what do we want to do and we have three cases we have our back tracking case we have our base case and then we have our recursive case this is what we're doing in the recursive case what about our backtracking case well we're just going to subtract from target on every recursive call so if the target is ever less than zero meaning that if the sum of this is ever greater than target then we just backtrack okay we just prune it right there so we'll never even go down this tree because there's nothing in this tree that's going to equal the target we've already gone over the target right and our second case is what if well what if the target uh is equal to zero so we have the target right so in this case let's see here we have six seven five so if we come here uh let's see where would we actually hit our target um well we could even just do uh let's say our target was eight i'll just do this to make it simple and we go all the way down here 2 then we can say that okay we finally hit our base case at that leaf level and then we can push that into our result okay so that's the idea behind it i'm not going super in depth on this tree because i highly recommend checking out the other videos in the playlist it goes over the tree construction so i don't want to spend too much time on this one but if you go over combination sum two and three uh it will go a little bit more in depth on how this tree is constructed now let's just quickly talk about time and space complexity here um the thing is that because we're dealing with duplicates this is very hard to calculate what the time and space complexity is with this because we're dealing with duplicates and this tree can get really big overall so typically when we're dealing with these combination problems we're looking at o of 2 to the n times n on time and o of 2 to the n times n on space okay but in this particular case it's going to be something quite different and you can go to the solution here on lead code to try to garner what exactly is the time and space complexity here we're going to have n number of candidates t is the target value and m is the minimum value so it's gonna look something like this n to the t divided by m plus one okay and our space complexity is going to look something similar as well it's really hard to derive that through looking at the tree so if you get this in an interview i would just explain that it's a hard thing to really kind of arrive to but typically you're looking at with combinations or subset problems you're looking at time and space complexity that looks something similar to this okay let's jump into the code and walk through this step by step we'll go ahead and build out our template and then we'll just we'll go ahead and walk through how it's working underneath the hood so first thing we want to do is we want to create our global result okay and this is going to be just an empty array we want to sort our candidates okay that's another thing we want to do okay i'm just using a javascript sorting method here okay and now we want to create our depth first search recursive helper okay so i'll do depth first search and then i'll do candidates target and then slate okay so now with this we have three components to this we have our back tracking case we have our base case and we have our depth first search recursive case okay that's our basic template and so what do we want to do on our back tracking case we just want to say if target is less than zero we just want to return because there's nothing else down the rest of that recursive tree that's going to add up to our target because we're over it right like we've gone over that limit so if the com if the sum of all the numbers in our slate is greater than the target then we can just return right there we don't need to go any further and the reason it's less than zero here on the target is that we're subtracting whatever the value is in our slate on each recursive call from the target so if it ever goes below that then we know that the sum of whatever's in our slate is actually over the target in our base case here we want to say if target equals zero that means that whatever the sum of our slate values at that point it equals a target okay then we just want to push into our global result and we're going to make a copy a scan of the slate we don't want to actually use the slate we want to make a copy of it because we're using the same slate array throughout the entire tree so we need to make a copy of it i'll just use the slice method here okay and then we'll return out of that and now we're dealing with our depth first search recursive case right so we're going to be looping through so we can do 4 let j equals i j is less than candidates dot length and j plus okay so now what do we want to check here okay we want to push in whatever's at j onto the slate and then we want to pass that into our recursive call okay so we want to say slate dot push candidates of j okay and now in our debt first search recursive call we want to just pass in j we don't want to increment j we just want to pass in j that way we're going to get the duplicates right on every recursive call we're going to get whatever's currently there so that way we can handle if it's 2 and that's how we're getting it that's how we're getting to our target we're going to consider all the duplicate values the sum of all the duplicate values or the sum of any one value duplicate number of times however many times so this can be five twos three twos whatever okay so here we're going to pass in our candidates and then we're going to subtract from our target whatever's at candidates of j and then we're going to pass in our slate and then we want to pop this off our slate when this comes back okay so that's the basic code for our recursive helper now all we have to do is just to call our depth first search helper so we're going to set i to 0 pass in candidate we'll have our target and then our slate will just be an empty array and then we'll return our global result okay so that's it that's the code it's not too bad i think the main thing here is to understand why we're passing in j and how that is going to consider multiple uh instances of that value if they add up to target which is what this question is asking the same number may be chosen from candidates an unlimited number of times okay so this accounts for that let's go ahead and run that and we're good okay let's run it again see if we can get better time here we go so i you know every time we run this it's so funny sometimes it'll be 20 sometimes it'll be 91 percent so you just never know i guess it's really what's happening on the back end that determines um the efficiency of this but you can see that it is pretty fast we are getting pretty good performance on this okay so that is lead code number 39. um listen if you are still confused on these this is not something that's easy to just get like right off the gate it takes a little bit of time so but i highly recommend investing the time to learn this template and it's right here in the solution right like you know i went over pretty much all these questions right here and it was in a thread in leap code that went over all these and it's just using this same template and you can see that these types of questions are asked a lot i mean they're frequently asked right like facebook airbnb amazon microsoft they're all asking this or some variation of it there's another one called phone number and then mnemonics you know combination for phone numbers and it's just the same exact thing you can just plug and play this template and just solve it in like five minutes so highly recommend getting familiar with this template and then also really understanding what's happening like it's creating a recursion tree like how is that working that way if there's some constraint on here like unlimited number of times or duplicates or no duplicates you can figure that out in the recursive case or the backtarking case you can make slight variations to this template and account for any of those constraints that the question may ask okay so that is lead code 39 combination some i hope you enjoyed it and i will see everyone on the next one | Combination Sum | combination-sum | Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40` | null | Array,Backtracking | Medium | 17,40,77,216,254,377 |
1,594 | hi everyone it's albert here today let's solve the contest question maximum non-negative product in the maximum non-negative product in the maximum non-negative product in the matrix the question statement so given a matrix grid and initially we are standing at the top left corner and each step we are only allowed to move right or down in the matrix and among all possible paths starting from the top left corner and ending in the bottom right corner we have to find the path with the maximum non-negative product with the maximum non-negative product with the maximum non-negative product and the product of a path is defined as the product of all integers in the grid visited along the path so for example one there's no any path that will get a non-negative any path that will get a non-negative any path that will get a non-negative product so in this case we would just return a negative one and for example two there's a path which is bolded on the grid here that will get the maximum product eight so for example two we will return eight and if you have been following my videos you will notice that this question is very similar to a question we have solved before which is a 1567 maximum length of subarray with positive product and the algorithm we will use is also dynamic programming and the foundation to solve this question is 152 maximum product subray and the very classic pp question the 62 unique pass in the data structure we will use our two dp matrix which is dpmax and dpmin and they stands for the maximum and minimum prefix product up to the current sale now let's look at the code okay and there's basically uh three parts of the code the first part is to initialize the dp matrix dpmax and dpmin and your size is the same as the input grid and we will set uh dpmax 0 and dbmin00 to grid 0. and next is to initialize the first row and column of both dpmax and dpmin and their values is basically the prefix product along the row and the column and the last part is the dp transition so for dbmax the value of every cell it can be the maximum amount for four values which is grid rc times the left cell of dpmax or the top cell of db max or grid rc times the left cell of dpmin and the top of top sales dpman and we will see later why we need to include dpmin into the calculation for dbmax later and for dpmin this will be the minimum among these four values and the last cell of dpmax which is the maximum product of all paths will be the answer so now let's try to visualize this process okay and here we'll be looking at example two and i have a dp max and dp min matrix on the screen here so uh the first row and column they're basically the prefix product along the row and column so which is uh 1 negative 2 and 1 3. and negative 2 and 1 3. now let's start to update the inner cells so the first value in grid is negative 2 and because for in each step we're only allowed to move right or move down so in dp max and dbmin the values will be updated either from top or from left so the product from the top cell is a four which is a negative two times negative two and the product from the left is negative two times one which is negative two and for dpmax we'll put the maximum value among these four possible values so which is four and dp min we'll put negative two here okay and moving to the next value which is one so the product from the top cell is uh negative two in dpmax and from that is four for dpmin it is negative 2 from top cell and negative 2 from left cell so the value in dpmax will be 4 it will be negative 2 in dp min and here comes the interesting part so the value in grid is negative 2. so in dpmax the product from the top cell is negative 16 from the left cell is negative 12. and in dbmin the product from the top cell is 8 from left is negative 12. so the maximum amount is four values is eight so we will put eight in dp max and the minimum is negative 16 so it's negative 16 in dp min so you can see that in this case the value in dbmax is actually updated from the product in dpmin so that is the main reason we also have to keep a dpmin matrix alone all path okay and finally is the last cell its value is one so following the same process we will get a 8 in dpmax and this will be the answer finally let's review so the key algorithm to solve this question is dynamic programming and make sure to review the questions 1567 and also the foundation questions 152 and 62. and the key data structures we use in these questions are 2dp matrix dpmax and dpmin and the main purpose of dpmin is to keep the most negative product along the way because the most negative product might become the maximum positive product later on and time and space complexity for this solution are both big of m times n because we have to dupl uh the whole matrix and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one | Maximum Non Negative Product in a Matrix | maximum-non-negative-product-in-a-matrix | You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix.
Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path.
Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`.
Notice that the modulo is performed after getting the maximum product.
**Example 1:**
**Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\]
**Output:** -1
**Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
**Example 2:**
**Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\]
**Output:** 8
**Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8).
**Example 3:**
**Input:** grid = \[\[1,3\],\[0,-4\]\]
**Output:** 0
**Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0).
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 15`
* `-4 <= grid[i][j] <= 4` | null | null | Medium | null |
853 | Hello Everyone Welcome Back To That Kareena Player Discuss Get Another Very Interesting Problem And List Code Which Is Quite Not Practical Locator Problem Solve This Problem Has Been Given And Cars That Point To The Same Destination Owen Rodhe And All Movie In The Same Direction To WhatsApp Particular Target Na Dheer And Starting From Target Subscribe 109 Give The Position Of Subscribe subscribe And subscribe The Amazing Subscribe Hai Aadha Adhikar Bhi Might Just Collide Noida Discs Have Ever Done It Is The Mercury Is Car Ko * Arton Wwe Mercury Is Car Ko * Arton Wwe Mercury Is Car Ko * Arton Wwe Smackdown More subscribe to the Page 1009 Subscribe to the channel And and in the morning here see the target in this example has been set up to 12th I am represented as in tire thing in the phone number 90 212 and a win-win proposition and speeds of all the a win-win proposition and speeds of all the a win-win proposition and speeds of all the And Subscribe Our He Represented By A B C D Respectively And According To Give A Good Number 90 Seervi And You Will Not Withdraw Its Time A Different This Car Be Id 1St Time In This Innovative Anomaly 2012 Is Loot Ke Election 2012 Subscription 151 Starting from the subscribe And subscribe The Amazing spider-man The Amazing spider-man The Amazing spider-man 2 f a plate solved 100 for a day that the distance between the target and the position of the planet in the subject is to basically - 06 to the speed of the invention to basically - 06 to the speed of the invention to basically - 06 to the speed of the invention to B I come from here will look into its too late to time the will take away into the distance and divide speed twist you want to listen incomplete is the great gatsby that has not been appointed a distance between that and the center of tis before this page - And center of tis before this page - And center of tis before this page - And support for and speed for the juice and fennel and bread 100 on the time it is divided by four video1 Similarly for acid distance between CNN more and speeds up the use of the phone improves time it will take This article divided by 12212 seconds in nine Defaulter Distance Between Districts Indian Target Fix Total - 5 Indian Target Fix Total - 5 Indian Target Fix Total - 5 Meanwhile Equal To 7 The Speed Of The Car Race Meanwhile Equal To 7 The Speed Of The Car Race Meanwhile Equal To 7 The Speed Of The Car Race Which Arm Spinner Sarkar Forward Is Vansh To Sudhar Time In World That 721 Me Request To 70 Of That 9f Look At It Doodh Le Distance Between Media and Entertainment Value - Service Nine and Entertainment Value - Service Nine and Entertainment Value - Service Nine and Speed Breaker Three Take the Time Taken When Speed Breaker Three Take the Time Taken When Speed Breaker Three Take the Time Taken When Two 9 Video then subscribe to the Page if you liked The Video then subscribe Jhaal Speed Slow Work R then subscribe Jhaal Speed Slow Work R then subscribe Jhaal Speed Slow Work R Dr0 The Time Table 2012 The Time Taken by the Floor Car Solve Video Start Writing From the Car Subscribe Button to the Number of Units and What is the Timing of Tarzan The Final Destination Subscribe The Channel Please subscribe and subscribe करे एक पठ Benefits after doing subscribe करे एक पठ Benefits after doing subscribe करे एक पठ Benefits after doing great work Schedule 0.2 Check Out The Time great work Schedule 0.2 Check Out The Time great work Schedule 0.2 Check Out The Time Taken By Being Drowned In Time Taken By Subscribe To The Time Of The Little One Officials Indicted Subscribe And Subscribe Foot Faith Caribbean Acquitted By Positivist The Final Destination 9.00 Subscribe To A Nobleman To Check For This Notice Against To The Final Target Between Sexually Subservient Belongs To Subscribe 9 Tags Page 10 subscribe to subscribe 9959 Number Subscribe To That Bureaucrat Is Important Him To Consider And This Problem Is Difficult To Represent Particular State Of 400 Akar Kandy Basically Being Represented By This Particular Variables Wave Fighters From The Subscribe The Channel Subscribe To Of The Time Complexity Of Water Poison Pieces Cut The First Step Is To Calculate The Time Job Skin To Of The Final Target Take Off Time Complexity And Subscribe The Channel Distance From Mother In Law And Order No Also Tune in Again OW Accounts for Terrorists During States of Intense Prayer for the Final Times Complexity of This Problem Grew Too Large for This Is the Time Subscribe to 200 Basically What You Want to Where Is the First President of 1253 Edison More Guest Subscribe and Notification TimesJobs That Subscribe Mintoo and 900 Unauthorized subscribe The Amazing Distance from the A Aa Intro First Epistle Thing in the World Tour Travels Producer Liye Between Two Take Money Plant Account subscribe The Channel Please subscribe and subscribe thanks for watching this video plz subscribe channel | Car Fleet | most-profit-assigning-work | There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away.
You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour).
A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).
A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.
If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.
Return _the **number of car fleets** that will arrive at the destination_.
**Example 1:**
**Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\]
**Output:** 3
**Explanation:**
The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.
The car starting at 0 does not catch up to any other car, so it is a fleet by itself.
The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
Note that no other cars meet these fleets before the destination, so the answer is 3.
**Example 2:**
**Input:** target = 10, position = \[3\], speed = \[3\]
**Output:** 1
**Explanation:** There is only one car, hence there is only one fleet.
**Example 3:**
**Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\]
**Output:** 1
**Explanation:**
The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.
Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
**Constraints:**
* `n == position.length == speed.length`
* `1 <= n <= 105`
* `0 < target <= 106`
* `0 <= position[i] < target`
* All the values of `position` are **unique**.
* `0 < speed[i] <= 106` | null | Array,Two Pointers,Binary Search,Greedy,Sorting | Medium | 2180 |
907 | hello everyone today we are going to solve sum of sub-array minimums problem solve sum of sub-array minimums problem solve sum of sub-array minimums problem so in this problem we are given an array and we have to find all these sub arrays and after finding all the sub array we have to find the minimum of all the sub arrays so the minimum of this array will be 3 this array will be 1 this array will be 2 this array will be 4 for minimum of this array will be 1 it will be 1 2 1 and it will be also 1 so now after finding minimum of all the sub array we have to sum them so what we have to do we have to find this all sub array is minimum and then we have to return its sum so here it's sum is 17 now how we can solve this problem so the first problem the first solution that comes into your mind will be the brute force approach in brute force approach what is what you will do you will simply make uh simply find the all sub arrays how you can find the whole sub arrays in one square and how you can find the minimum you can buy traversing it will become off and cube so this will be your time complexity for finding all the sub arrays and then finding all the minimum but you can improve it by just finding the minimum as soon as you finding the sub array so it will be reduced to off and scale when you find minimum while creating this so let's see while creating this summaries so let's see the code for the same so what we will do we will start from our we start iterating over this loop so how we can do for this i can start my end i equals to zero so i less than length of this so i less than and i plus then what i can do i can initialize my minimum or what will be the minimum i can initialize with this if i have to check all these i available sliding with this minimum equals to this array i and then what i can take my sum equals to here i am taking my sum that is 0 now again now after this i will iterate from this i will i state here so for and let's say my j equals to i j less than n j plus and what i will do i will check if this will be my minimum in my sub array or not so what will the sub array with the starting three social value will be three uh three one first will be three then three one then we have a three two then we have a three four three one two and three one two four so this will be the sub array and in this sub array here my minimum will be three here my minimum will be one and i have to sum all of this so what i will do if my minimum is greater than my array j in that case what i will do in that case i will change my minimum i will change my minimums to array j and in this loop what i will do finally i will sum up all the minimum i will sum the minimum so if i iterate here so you can see and finally i will return my minimum so let's have a try run just to understand this so i start from three i will first of all my minimum will be three so this is my thumb one will become three now in three one my minimum will be minimum will change to one minimum change to one so it will be four in three one two minimum is one so it will five three one four minimum is one so it will become six now i will start from i now from one to four and one minus minimum will be one so i will this then one two minimum will be one for one four one two four minimum will be one so both of them i will make it eight from one then two and four so it will become about six seven eight now for two my minimum will be first two and then two four it will be two so it will become uh here it was nine and two four it will become 30 and then for finally 4 my minimum will be 4 so it will become 17 so if you can clearly see my answer will be 79 i will return this and the time code exit you can see here the time complexity because i am checking minimum while you know finding the sub arrays so my minimum time complexity will become of n square and space complexity because we are not using any extra space so very space complexity will be of one now let's see how we can utilize this off and scale stu of n so now let's think about the optimum solution how we can improve from o and scales to often so if what will these two contribute to my final answer what is my final answer will be sum of all minimum all sub errors minimum so if i have two if this is the minimum in a sub arrays let's say i have some sub arrays which minimum has its minimum will be two so there may be i am assuming there are sub arrays such that its minimum is two there are bits of arrays such that is minimum is nine and there are certain i somehow i find how many sub arrays which minimum are these so after finding this i can just simply submit summation um if there are a sub arrays which have minimum 2 so in the final answer what will be my what will be the contribution of 2 continuation of 2 will be 2 into a okay and contribution of 9 will be 9 into b so i can summation my minimum into number of sub arrays in which it is minimum so now my question is how i can find in so now the question is how i can find this number of subarrays in which x is this assume this is x this x is minimum how i can find so let's see before moving to this solution you first have to know what is next greater element right what is next greater left problem if you do not understand that i would recommend you to watch that video first then comes to this so what i will do here if i am let's say if i am at 3 so i will find what is the next smallest element in its left so the next smallest element is here and the next smallest element at the right is 1 so what i can say in this array the sub array of sub array will give my minimum three let's see if i have nine eight seven three so what will be the minimum will be three if i have a nine eight seven three four so what will be minimum three nine eight seven three four six what will be minimum three if i take eight seven three if i take seven three four so how many sub array will be possible here so if you see um let's say this is my m let's say this is my length m and this is my length n this is my length and it is so how many elements will be there m plus n minus 1 okay so how many sub arrays will be possible the sub arrays will be m into n minus 1 i am into n minus 1 plus 1 that will be this so there will be this must array whose minimum will be three no there are this much so that is possible in this region but if you see clearly if i have added this if i have this so here will be minimum 3 no so i have to delete all the sub arrays all these sub arrays in this region and all the sub arrays in this region where 3 is not included so how many sub arrays will be there if this is m then this will be m minus 1 so n minus 1 into sub arrays of this will be there will be m minus 1 into m divided by 2 and how many sub arrays will be there is n into n minus 1 divided by 2 so after solving this equation if you solve this equation you will get your answer as m into n you can solve it and it will give you m into n and what is this amp this m is the distance from its next greater element next smaller element in its left and n is the next smaller element in smaller element it's right so what we have to do is so i have found how many sub arrays this is how many sub arrays we have in which this three will be its minimum now if i have to find the next thing i have to find that what will this three contribute to my final answer so three will contribute so my final answer so if these are there are let's say what is this i'm here so this is one two three four and here one two three so m is my here m is my four and n is three so this will be twelve okay and in the final answer there will be twelve per array 12 sub arrays whose minimum is 3 that means 12 into 3 36 this 36 will be added to my answer strategies will be added to my answers if i find for all this then my answer will be plus equal plus equals to for all this element let's say array i have to find a smaller element let's say i can say nash is smaller element it needs left for i and next is smaller element it is right for i and i will submit this from i equals to 0 to 10 and this will be my answer now the final thing is now let's see here if i have this array um 3 1 2 so what will the it's next smaller element of this two there will be no dashed smaller element in its right so in that case what i will do i will make my next smaller is array size minus i this i it minus one and if for one there is no next smaller element in its left so in that case what will be it will be i index will be i so the length will be i you can see and here length will be array size minus i minus 1 so i hope you understand both of the problems next a smaller element in left nest smaller element in right now if you know this then the final thing after finding this and this we have to implement this solution and we will get our answer yes so now let's check the code for the same so here what we are doing is first of all we finding our length and then we are creating left which will create find next smaller element in its left and right it will calculate the next smaller element in its right then what we will do is we are using stack for finding these two we have already see how to find this using stack so we are just doing this finding nash a smaller element in left and then finding nice smaller element in its right after that what we are doing is we are just adding our result into left of i into right eye and we are taking more because our answer can be greater than 10 k over 9 plus 7 so in that case what we are doing is we are taking more and if you so i hope you understand both position if you if both solution helps you do not forget to hit the like and subscribe button thanks for watching | Sum of Subarray Minimums | koko-eating-bananas | Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104` | null | Array,Binary Search | Medium | 788,1335,2188 |
1,383 | hey what's up guys this is Jim here and so this time let's take a look at another lead code problem number 1383 maximum performance of a team okay so you're given like an engineer's number from 1 to N and the two arrays speed and efficiency and write and you need to and then another one k is the number of a team you need to find a team with the number team with person number of equals to K whose performance is maximum so how do we calculate the performance equals to the total speed of all the numbers of other peoples in the team plus the minimum of all team members efficiency right for example here if you have a k equal to 2 here which means we need to form a team which have 2 people and so we pick the engineer 5 and to whose speed the sum of speed is 15 but the performance is the minimum of all team members and in this case is 60 and in this case it's total speed is 17 times the minimum of the efficiency which is 4 right so for this kind of problem right how can we come up with the solution right I think at the beginning I was trying to use like you know I think it's uh it's kind of clear that we need to use some greedy algorithm here right because at the beginning I was thinking of can I just the every time right I always pick the best option because of offer for the greedy algorithm the key the idea of greedy as the greedy algorithm is the every time we always pick the best options at the moment right so I was thinking can I always pick the best right at the moment let's say if we can so in that case we only need to do with K times right so I took first time we pick the best workers then and then the second one is the we picked once we remove this worker from this our eraser can I try to pick the next best workers right but then it seems like it didn't work right because the latter because the efficiency right although the performance the speed can be suck can be summarized but the efficiency is not guaranteed because the efficiency it's bounded to them to the minimum value right so basically what it means is that so even though we picked the first one we started so it's a bad answer but the latter one the people who joined him later may downgrade the previously result right so that for that reason we cannot just every time we peak like at the best answers and we only pick at the K times that won't work all right so if that won't work so how about some other ways so to solve this problem right so and common the common thought is if we don't know right how to if we don't know like which one is the correct one then we try all the possibilities right you know I actually this problem is very similar as it the other one I think there's a like another 800 something 857 I think a similar one if you need to calculate a minimum cost to hire a worker right on that problem you're also given like two arrays I think the first one is that like the wager is second one is that the performance is something like that and you need to calculate what's the minimum cost of hiring a worker right so similar concept here we have a case number here right basically we try all the possibilities but how do we try it right we have to try it from with the sequence right so the sequence is we sort the efficiency from highest to lowest and then we'll be using for a priority queue to track the case numbers of speed because at one time we can only have case people in the team right and we want to track the highest of three speed at the moment and actually sorting by this efficiency here since the our final result will be bound at the minimum efficiency right since we're looping the efficiency from the highest to the lowest this is also kind of like greedy concert P right basically at each time we always try to see okay with the current highest efficiency can we get a better result right basically that's the idea of this problem and then let's try to code it right so first we're going to define like a mod for our final result right that's the ten to the power of nine right to the power of nine plus seven right and then let's have an answer here and let's do a current speed right harness speed total speed how about that total speed to zero right so what do we do an also a priority queue so yeah that we need a priority queue - no - Froy already queue to keep queue - no - Froy already queue to keep queue - no - Froy already queue to keep track of the our current speed according to past the speed fastest the speed yeah and for efficiency and speed right in sleep let's sort this these people with their efficiency right tip efficiency right vision C and speed sort it and let's do a reverse equals to true right because we want to do a greedy algorithm here right every time we always pick the highest efficiency and we'll see with the hop is the current highest efficiency what's the maximum speed we can get right and then we will try to see if with that combination if we can get a better result right then the priority Q dots heap Q Todd Heap push right we push the corn speed to that right and then we do a what with we will class speed right and then if the lens if the length of the priority queue is greater than K right so that means with the current speed let's say there are more than case people in the group which is the discard the solute the worst work the worst worker right so we just discard the it was hip-hop right and to the total speed hip-hop right and to the total speed hip-hop right and to the total speed right we discard the slow the slowest speed from the priority queue right it will heap kill Todd Heap pop right and then our TQ r TQ that's that right so because once we after we abandon this one but there will be like we also need to remove it from this current speed right so that we all have like this current total speed for the current for only 4k people right and then in the end we just simply a trap up update this thing right if which I race is bigger right if this one is bigger or the current total speed right x times the current efficiency right in the end just return answer mod this mod right yeah I think that should work all right Oh let's see I think I yeah I think I made a mistake here so 10 to the 9 yeah cool so this approach works right let's take a look so see why this thing works right and let's say you know this sorting by deficiency can kind of make sense right because we want to try we always greedily try the best efficiency at the moment right meanwhile we're also maintaining like a priority queue for the top 3 speed right and let's say here let's say we add like let's see do we have a this the current what courage the K plus is a k plus 1 right workers so after we after adding this worker to the hip queue right and it will be a will be removing the smallest and then we'll be using that thing to do another check right so let's assuming let's assume the one we just added is the worst work worker what does it mean it means that the speed is like it's the is the smallest it's a slowest speed right in that case so after we approach this speed to the hip queue and then basically will pump the same speed out I basically this current total speed will not be changed let's say the current whines has the lowest slowest speed right and then the in this case it won't get a won't affect our final result right because then it means that the previous employee can give us like a better result right because the previous employee will have like a higher efficiency but with those three employees will have a also have a higher total speed right that's why we do a max to compare with the previously result right and with the current one in this case even though you know this thing is not accurate I think so in this case the current employee is the basically the efficiency is the current employees efficiency but the current total speed is still using the previously previous speed for the four different for the previous workers so this thing is not like a very accurate result right because the current total speed and the current efficiency doesn't match it doesn't match each other because the total speed was made of previously was made of previous like workers but while the efficiency is from the current worker right so this is place a little bit confusing here but it won't affect our final result because in this case this thing will never give us a higher a better result right because this thing doesn't change right but the efficiency is lower at this moment so this thing will always small be smaller than a previously answer so that's why this theme this formula will work it can guarantee us it won't have any unexpected a higher result right see because we are sorting by the efficiency okay and I think that's pretty much everything for this problem you know basically with first we use a greedy algorithm here basically we sort the workers based on the efficiency because the final performance is bound by the minimum efficiency here that's why we sort by the efficiency anyways with a process the workers from the highest efficiency to the lowest one and then we which use a priority queue to store the to store to maintain the top three sorry the top case speed right and then in the end we just simply track if the if this combination can give us a higher result right this is the key point basically we try all the possible workers basically we try all the efficiencies and then we just maintain the top speed here and then we do this over and over until we process all the other with the workers okay cool guys I hope you guys enjoyed like to enjoyed watching the videos and try to memorize this kind of like template you contemplate the world like idea were like or solutions you know next time we see this kind of issues we're like you have two arrays right and then and you have two factors basically two factors in two arrays which will contribute to our to the final results right and the very common way is that we sort by something you know because in this case we cannot sort by two things at the same time because it's a if HTC is bounded of is minimum value so that's why we have the sword only by the efficiency and then which loop through everything and while maintaining the top speed cool guys I think that's it for this problem I'll be seeing you soon thank you guys bye | Maximum Performance of a Team | number-of-single-divisor-triplets | You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108` | The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values. | Math | Medium | 2301 |
1,044 | hey-ho there today sleep coding hey-ho there today sleep coding hey-ho there today sleep coding challenge question it's called longest the duplicated a substring so the definition for substring is that time it's a continuous chunk of characters inside the string so it's a window inside the string duplicated window is basically the same window appeared at the two different positions at least the two different positions in that's inside the string so this question is asking us to find the duplicated windows and among the longest such window we want to just randomly return one obviously spawn so this is enough question let's look at an example the input string is banana so let's just look at the window size in the increasing order let's look at the window size one the duplicator window we have will be a and n a appears three times and appear two times it's easy to look at that window size two we will have two window that appears more than one times with the first one is e and the second one is na we can easily verify that with the input string the lens three ones are there are only one choice now which is a ma which is starting at so the ene is either 1 2 3 or 3 to 5 you know peer twice so it's a it's duplicated for lens equal to 4 there is no such window we can just quickly enumerate over the other lens for windows to see that we have behaving a that's 0 to 4 0 to 3 and 8 and 18 that's 1 to 4 and the last one is in a which is front index 2 to index Phi there is no duplicate here so lens for from lands for and on we don't have duplicated substrings so I guess it's easy to see that if we have a lens 3 duplicated window this guarantee that we'll have duplicate in last two and last one because we geezers took two windows of a na and just slice that to be one smaller just take the first two its guarantee that we all have that duplicated among those two different windows so if we have a function that's called FL so the thing that it will return as a boolean can do we have duplicated a substring of sighs I hope so when we map this function to the range from 1 to the total string size subtracted by 1 the function call result will be true until the longest excuse me until the longest step and after that will be false possible force so this is telling us we can apply binary search to find the longest Lance so here F L is to just going to demonstrate that a little bit from five you can do this yourself to verify it's not because for four it's not possible then for five there's no way it's going to be possible I think you can easily verify that so it's just going to note down the first thing we noticed by looking at the example we can apply binary search to find the longest the largest the window size so that's the first thing we can do the second thing is how we actually do this duplication check so this example we can see that we visit we just kind of have a sliding window inside the string for fix the size and just move that window towards right one at a time one character at a time for each time when we move the window to a new position we hash that the content of the window into a hash set so if we find the key is already in there that means we have a duplicate the time complexity for this naive approach is going to be n multiplied by L the size of the string multiplied by the length of the window because for every window if we just naively hash that into the hash that first it takes a lot of L time the window size time to grab all those characters then we have to compute a hash out of it every single time that's order of L as well so the total runtime for doing this comparison at this duplication check is order of n multiplied by L so combine this with the binary search it will be M L log of n so that's the total run time complexity for a binary search on top of this naive duplicate window detection so things that the window size can grow quite large and we want run this is something we need to run for every binary search call so we want to have this to be as quick as possible one thing we can notice that if we load the window over the previous window is baaa the next window is a nd the only thing that's changing is the exiting character and the entering character so we want to do some updates just don't those primarily just going to be on the character we emitted and the character be introduced so one thing we can do is to apply the rolling hash method so how it works is actually quite simple quite similar to how binary to decimal number conversion works so let's say that I have a program that has three different switches and so it's on and off so the state of the program can be all off so convert that into if we use three different variables to code this state it will be 1 0 1 and there's some other time you might be off long and on so you will be 0 1 one thing that we can compare whether this to state whether there's 2 in our string context they would be whether this two window are the same we can do this single position at a time kind of a checking that's essentially what they hatch the whole thing hatched the whole string every single time for everything the window using the naive hash works as its processing that position by position but the other thing that we can do is to for my on and off switch question it's a binary number that's a binary number so we can just convert that into a decimal so this number in decimal will be 4 plus 1 which is 5 and this number this state of the three different of switches is going to be two plus one is three so instead of the comparing this two things to windows one position at a time if we just represent this as integer number that's more integer number but the only thing that we need to do is to compare their decimal number of values so that means the hash and checking with the set can be more efficient if we can somehow represent every window as a as an integer as a decimal integer so for in our case every position here we have 26 different characters it will be a 26 you know 26 and Neri digit number to decimal conversion we can still do that it's just instead of multiplying every position to the 2 to the power of a hi we multiplied that position by the 26 to the power of RT for every eyes position inside of the string here we will map a 2-0 be to 1 z to 25 cents like that and 2-0 be to 1 z to 25 cents like that and 2-0 be to 1 z to 25 cents like that and looking at the position of our position just multiply that integer number to the power 2026 power of location we can convert the window into the decimal so it's basically polynomials so that makes the hashing and the look at burns faster but that use that representation though also helped us to do the moving window faster so let's just illustrate how that works so for BA the first window it will be something like B was going to be mapped to let's say that I'm not sure what number is and a is 0 B is 1 and let's just call it 22 I'm not sure so the convert listed by a decimal you will be one x 26 to the zero power plus 0 multiplied 26 to the power of 1 plus we got a is 22 x 26 to the power of 2 add another 0 x 26 to the power 3 so that's the that's if we convert in this whole window to decimal what if we roll us towards right by 1 it will become a and D and so we notice that we have to basically Bank read the power here for every single one of those except the very first one shall be gone so we delete this because the B is no longer there and we introducing a new one that's just that is 22 x 26 to the power of 3 so we divide the whole thing by 26 a subtractor we yeah we do we subtract the exiting number to the correct power divide the whole thing by 26 and add the new entry number multiplied by the corrector or power so doing essentially kind of a three operations get rid of one by subtracting the numbers multiplied by the power and divide the whole thing the second step to downgrade everyone to shifting perform a shift and introducing a new one so three operations that give us the chef of the window so instead of doing M multiplied by L the window this duplication sliding window duplication check was rolling hash will be M multiplied by certain constant instead of L so that saves time and I guess another thing to note is that the power can be you know when the lens goes larger we are multiplied by 26 to the very large lens subtract by one type of power the number grows larger and larger so that's why we want to introduce a modular big number modular everyone when we do this window calculation so that's pretty much it we're going to reduce the runtime to n log n some constant multiplied by n log n the continuously the time we need to update the window logins from binary search and is from the rolling hash duplication detection so that's pretty much how we summarize the how to approach this problem the detail in the implementation makes this question bump to a higher level the big idea behind is this so like medium level but the runtime check for this question is just rare tight so let's cut this thing yeah we would do a rolling hash which takes a lens and try to detect do we have a duplication with this window size you cannot start with a hash number zero and just compute the first window and then we are going to Inc a full loop remove that window over to the very end to the duplication check for character in well one thing we can do is to spice things up is to first to create the character to their integer number kind of mapping and either look it up every time which can be slower or just convert the whole string input into a array of integer where each position is the integer representation for the character inside the string let's just call this D it's going to be the convert that the lowercase letters to a their alphabet ordering so with this we can just do B up to the first window and we're gonna do is to multiply this by some power which is 46 the vocabulary size plus the newcomer so the mask is a slightly different compared to the example here the example the lower position the right position the writer to the more to the right the higher the power gets raised but here for in the actual code I have the leftmost to be the highest power it's not really a big deal differences just I think when I multiply the leftmost chunk the mass is a little bit easier so we're gonna modest by a big modular number every time we do a calculation there's two to the 22 so with this we basically have down our first window now I'm just going to put that into a set that's the very first hash we have so let's do a little comment the initial window there's a sliding window from the previous windows ending point you know we want to update a window so we're gonna do is to subtract that left the most the previous Latinist which is our subtract by the window size that thing has to be multiplied by let's just call this PP which is P to the power of L because it's the left the most one how long the size of the window that position the integer number at that position has been raised to the P to the power of L and we are doing module everywhere so that's why for that there so we have to raise the integer number of opposition to that correct the power because it's exiting so we subtract about and adding the new one and doing another modular as well so this is updating the window and then we check if this new hash is English set if this thing I said that means the current window we're looking at there is a duplicate or of a prior one so we can return the starting position for this window which is going to be our subtracted by L plus one the reason for class one is that we are getting rid of the Carter disposition so the new starting position is this one otherwise we will just add this new hash new window hash to the same in the end if we don't find any duplication we can just return none or force something like that indicating that there is no duplication so this rolling hash function will give us direction to apply binary search we're going to try the lens window size lines from one to M minus one that's the low abundant upper bond actually we are finding where we want to find that the largest window size such that we still have a duplication which is equivalent saying that we want to find that the smallest window size where we couldn't find any duplication and in the latter one we just returned the number we find a sub socket by one so for that reason the I'm gonna go going to use that the it's going to be essentially the that's it couldn't so I'm doing this first I get the middle point then I want to see if I can find it to placate if I can I will increase my lower bound to be n plus one so I want to find the first position but I couldn't find duplicate so after this while loop L minus one is the largest window size duplicated or window size so we can just run this window size so this rolling half one more time to get the starting position for the duplicated window in its second occurrence inside the string in the end we will return s from the start position to start plus L minus one that's the window size how - minus one that's the window size how - minus one that's the window size how - plane is the large longest the window size yeah let's just quickly check do I have problems yep so that's the code let's see if it works no what do we have I forgot a column no still no I'm returning out this empty string what's the problem I see I think I forgot to multiply off the power here so let's just comment a little bit about that they updating over here so this is a shift shifted towards right towards left this x p it's basically shifting every position towards left by one because the left the more towards left it is the higher the power of P the digit that has been raised to so we have we shifted the window towards left by one we have to multiply every one by P and we are getting rid of the mid to the oh the left and this is adding the new right and we do a modular to control that to have the number relative small so let's see if it works now we have a am a yes yeah so it's a it's accepted so this is take the code for this problem really conceptually it's not too difficult to understand this rolling hash it's just the sort of like we have a vocabulary size number system and we want to convert that into decimal to control the size of the decimal number we do modular every place when we do the calculations for the window update it's looking like this we shift a position towards left we do a shift further for all the characters would get rid of the old one and we add the new one yeah so that's sad that's this question today it so it's pretty I would say that July or June this month province is more difficult than the prior two months I hope it's not the end of it I feel that if they difficulty just keep going like this the two remaining weeks can be quite challenging and a lot of people are going to drop out so yeah so that's the question today | Longest Duplicate Substring | find-common-characters | Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `" "`.
**Example 1:**
**Input:** s = "banana"
**Output:** "ana"
**Example 2:**
**Input:** s = "abcd"
**Output:** ""
**Constraints:**
* `2 <= s.length <= 3 * 104`
* `s` consists of lowercase English letters. | null | Array,Hash Table,String | Easy | 350 |
1,306 | That Today Also Volume Jump Game 3 Strengthen List Problem Number 130 Hole C The Problem Statement [ Problem Statement [ Problem Statement Suryavanshi Host Negative in Tears and Were Given at Index for Example Let's Check the Are Nominated Winters This is Last Updated on The Sweets Zero 12345 Setting Text Five key and where lost to jump and you here left and right of the current index and here step is the value of two I invented dictionary for example is we can only one step subscribe must and crime how two steps to the right and Tubelight Me Note Jump Intermediate Sirdadhar Positive Pati Then Like Share And Share That Till Now One Position But 10th Ka Note Jaunpur Two Position Suv Cars Is The Meaning Of The Name Of The State And Subscribe The Channel Veer I am now 202 This is the Are Android Lecture Distance Between Madurai And Again From Her Not To Love Everyone Welcome Back Veer To Hai Tu And Free Both Places Late Se Bhi Jump 320 Come Across Three To One Slips From Trivandrum 1234 Welcome to Subscribe Button to the Solution Vocabulary This Problem Related to Different Notes Subscribe 1080 Starting Index Previous Video in Graph Problems Robert Pattinson and Tourist Destinations subscribe and subscribe the Channel subscribe A Nip Rakoff History Notes with Ozone Series Back To And You Have Already Explained Thursday Middu Come Here You Are Not Keeping The Faith And Subscribe Days Will Return Forms A And Soaked Out Of Every Temple Run Is So Let's See How They Can Solve It So Let's Midnight Studio Code Where Function Can Reed the beaver external Id starting index is elected the Indian's producer bullion of the same size patience and it's speed of the net is set which will be empty initially in accordance with insulting and issues which is extended into its students' eyes in extended into its students' eyes in extended into its students' eyes in more land complaint by 2025 For giving water world tour is that semen is so is such gin boosted and that a this index is mode on equal to medium size thing relative this dream and 800 return for that here meeting definition and gas pimple for writing this as well s In Which They Are Currently Busy 09 That If Destinations Return Is True Otherwise What We Will Do Is Note Country How Must Date Means Is 90 Coming Year For The First Time So Absolutely Market Visited Ne Suicide Note Insult That Which Index Sm1 And What Is 90 Index Presently no veer vid oo hain next step vintage here to the chief that i plus chief become system and planets tip can we i - sai pa tip can we i - sai pa tip can we i - sai pa ko switch off this problem aadheen chunnu ine zor injustice hai next step diverse practice plus this and this - this information Which can also on i this and this - this information Which can also on i this and this - this information Which can also on i sun turnon in cambridge hai it is plus s and that can reach a that apps - s is this point se left guava apps - s is this point se left guava apps - s is this point se left guava unknown to playlist 1000 simple see what is the time complexity subscribe visit all the value of time Complexity of that common man in this video is very small but I can be up to that in when you visit every node so space and time both are linear in this case in all it's right record producer the Sun will keep Everest set mode on Unwanted set MP3 to initially 37 inch note service tax is that this is such jewelery twisted every state against women need to search and western force and co start is 0 and to starting and money is equal to hua do hai true birth return for its a That this and the other Dr Varist ki destination in return true the Buddha boy is visible the market witch state forest ki and move to the next step and false impression love oo kar do hua ki Star Plus air tight hai and ki and lets Only Networks Happened 220 Pure Silk Chapter Saliva Two 90 Votes For The First Class To Hang Out Submit Nau End Solution Accepted I Myself Positive Ones To Destroy | Jump Game III | minimum-absolute-difference | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[4,2,3,0,3,1,2\], start = 5
**Output:** true
**Explanation:**
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3
**Example 2:**
**Input:** arr = \[4,2,3,0,3,1,2\], start = 0
**Output:** true
**Explanation:**
One possible way to reach at index 3 with value 0 is:
index 0 -> index 4 -> index 1 -> index 3
**Example 3:**
**Input:** arr = \[3,0,2,1,2\], start = 2
**Output:** false
**Explanation:** There is no way to reach at index 1 with value 0.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `0 <= arr[i] < arr.length`
* `0 <= start < arr.length`
a, b are from arr a < b b - a equals to the minimum absolute difference of any two elements in arr | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. | Array,Sorting | Easy | 2248 |
1,345 | hey everybody this is larry this is me going over day 27 of the december league daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about this farm ask me questions and usually myself and explain these lives so if it goes a little slow just go fast forward through it because i like to go through my thought process not just the solution okay so today's problem is jump game four uh given an array uh first index of the array okay so you could go okay so i'm just trying to look at the variation so this is i plus one i minus one and then uh you get like a free travel to whatever um okay and where do you start the first index and the last okay so that seems okay uh let me look at the constraints uh constraints of five times ten to the fourth um should be okay so my immediate thought is just breakfast search um because basically jeff you can think about it as a graph problem where um you know uh or i think about kind of in a weird way like a um like a bus problem or something like that because uh well you could go left you could go right i think that's straightforward the only other thing to kind of notice is that you can go from a number to another number or another index with the same number so that makes it easier as well the only thing that i have to make sure and have concerns about is try to make sure that we don't um we're just trying to figure out how to uh represent how to figure out how to uh represent the edges in a good way because if i would to do it very naively right you know like here for example we put all the seven to connect all the seven in terms of edges but then you might you know this becomes uh you know in a worst case scenario in a degenerate case you know let's say they're all ones or something like that then it becomes n squared in a weird way right so you have to be really careful about how to do it um and i think to the way that i would think about it is maybe just that um once you use up a number you can't like if you're taking the bus you don't you can't take it again um i think the reason why that is the case is because um because if you take the same bus i say the same bus but if you use the same number to travel right if you take it again later that means that the first time you should have got off at a later uh i keep on saying bustline because of the bus number or whatever but yeah that means you should have gone to an index that's closer so with that in mind i think that's enough for it to be breakfast searchable because now that means that each number will be only assessed constant number of times and that means that this algorithm is going to be linear um okay let's start encoding oh i see sharp one uh because during the contest i had to write something in c sharp to make it faster earlier today i didn't do that well in that contest i did win another contest earlier though so maybe it averages out a little bit um but yeah okay so anyway back to main topic uh python let's go uh so let's just say well let's pre-process them all together well let's pre-process them all together well let's pre-process them all together so now i'm gonna keep on calling them buses because i just think about them as bus lines for some reason uh it might not make sense to you so use your own variable names that are more reasonable but okay so and as you go to length of all um and then now for so now let's just say you know scene i just quite basically the numbers that you use and don't you know use anymore uh the bus lines if you want to call it that and then also just um something that maps uh the bus line to all the bus stops if you want to go at that so it's hot so then now for x is in a way of oh let's go index x and enumerate array stops of x append index right okay so then that's basically all we have to do to start up the first search um so the first search let's start with the queue collections.deck collections.deck collections.deck we want to append we have to do the minimum of moves okay i just forgot whether it was boolean or something like that but that's fine um yeah and then let's also keep track of the distance for each thing i don't actually strictly think this is necessary but i'm going to do it this way um yeah it goes to let's just say infinity times n where infinity is just some big number right and now we can set the first element as zero because this is where we start we uh we appen um we append index zero right and that's good enough for us i think um yeah okay i just thinking through whether i need anything more but yeah so while length is equal to q uh you know current is equal to q dot pop left so basically the we're processing this number uh if current is equal to n minus one then we return d of current um which is where we store the distance and then now we go left and the right so for um let's just say i go i usually call it uh next but next is obviously a keyword so as i use something like that which is kind of awkward looking um but anyway in uh let's see current minus one chrome plus one yeah and then now we just have to check that it is next you know inside the array if it's inside the way then that's um let's also check that and uh d of the current plus one is less than d of nxt that means that this way will let us go there faster so we're doing breakfast search so you could also have just use like it's very binary right once you relax it should be the quickest way to get there but once if this is the case well we set this to you go to current plus one and we also want to append this to the thing um and then we do the same thing for maybe another way to write it is okay so candidates is equal to current minus plus one gram plus one right uh so in order to not duplicate the code too much uh we can also put all the stops in there so that means if let's see our way of current is the current bus number i keep going in buses so uh so if this is not in scene then that means that we haven't taken this bus yet as we said so we want to add this to the buses we've seen and then we also want to add all the bus stops uh in it right so the candidates um do stop sub current i think this should be enough uh and then if it's impossible we return negative one or someone huh is it always possible oh it's always possible because you could always go plus one minus one okay duh uh so let's give it a go oh wrong answer though that maybe that's the story of my evening very tired i should have slept more that's my excuse i'm sticking to it but so how it is wrong will allow me to kind of figure out why it is wrong hopefully uh this is good one let's see let's print it out real quick i just did not really expect this but uh so yeah zero goes to zero so okay so the candidates looked like it is not really working let's see that's a little bit weird did i mess this up let's put out all the stuff in general because that doesn't make sense because for each number in our way we just yeah this is this looks more what i expect but oh i am because current is the index but the actual thing is a race of current uh okay me is being dumb after all um all right knew or something silly but uh i need more sleep it's a little bit late it's 3 30. that's my excuse and i'm sticking to it and i didn't sleep that much yesterday because of the contests uh but yeah okay cool uh yeah so uh yeah uh there's no impossible because you can always just go i plus one so at the worst case it's gonna be off n uh but yeah in terms of complexity this is gonna be linear time because for each node uh for each index for each bus stop um you're going to only process it once and the only two ways you can uh you know like with this loop it only even happens like uh like two or three times right because you can either reach a note from the left or no from the right or took a bus to get there so for the most part like this only happens once for each node and so like everything is linear time um and n is for n is equal to five times ten to four that's a great idea uh in terms of space it's going to be linear as well because we have user q and also this uh distant array thing don't i guess technically you could have stored it on the cube but it's the same thing as you can imagine and it's a dictionary to kind of help us out a little bit uh just for easier mapping but yeah uh let me know what you think about this problem uh i'm a little tired so i don't know how to explain stuff but uh i'll see you tomorrow hope you have a great you know rest of the weekend bye | Jump Game IV | perform-string-shifts | Given an array of integers `arr`, you are initially positioned at the first index of the array.
In one step you can jump from index `i` to index:
* `i + 1` where: `i + 1 < arr.length`.
* `i - 1` where: `i - 1 >= 0`.
* `j` where: `arr[i] == arr[j]` and `i != j`.
Return _the minimum number of steps_ to reach the **last index** of the array.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[100,-23,-23,404,100,23,23,23,3,404\]
**Output:** 3
**Explanation:** You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
**Example 2:**
**Input:** arr = \[7\]
**Output:** 0
**Explanation:** Start index is the last index. You do not need to jump.
**Example 3:**
**Input:** arr = \[7,6,9,6,9,6,9,7\]
**Output:** 1
**Explanation:** You can jump directly from index 0 to index 7 which is last index of the array.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `-108 <= arr[i] <= 108` | Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once. | Array,Math,String | Easy | null |
581 | hey what's up guys uh this is jung here so today uh let's take a look at today's daily challenge problem number 581 shortest unsorted on a continuous summary so this one is a very interesting problem so basically you're given like an integer array of nums here and you need to find one continuous sub array that you only sort this sub array in ascending orders and after that you will have the whole array be assorted you know sending order you need to return the shortest sub array in this case right so for example we have this kind of right here you know two so the answer is this so we need to sort from this one to here basically after sorting this sub array here you know we'll have like a sorted array in total that's why the answer is 5 in this case and in example two here right so since it's already sorted obviously we don't need to do any sorting that's why it is zero okay and then this one is also one right so with this one here is we also need to do a zero cool so um yeah and here's the constraints right so there actually there are many uh ways to solve this problem but i think today i'll just introduce like two very common solutions so basically i think the very urban uh one very easy solution is that we sort these numbers basically you know so for example if we have like this kind of two four uh 2 6 4 8 10 9 15 right so if we sort this array so we'll get basically two four uh 6 8 9 10 and 15 right yeah so and we just need to compare basically we just need to find the lower bound basically the mo the leftmost number who is not who is uh is not in the right position and then the right most not a number who is not in the right position so in this case we can see the leftmost one is four right and then the rightmost one is ten and we just need to find the distance between those two indices in this case is five right that's how we get the five right i think it kind of makes sense right so basically as long as we can find the left most uh misplaced numbers and then the right most misplaced numbers so the things the arrays in writing between those two indexes are the sub array we need to sort and obviously this kind of time complexity is unlocked right because we need to sort this array uh we that's when we need unlock n and then we need to loop through the uh the array to find the left most unmatched number and the rightmost match number okay oh by the way so to find this uh left most and right most unmatched indexes i think we can just loop through the uh the entire array and we compare the numbers one by one as long as the number is different and then we update both the minimum and the maximum indexes right that's how we maintain that cool so i mean that's basically the first uh first solution and can we improve that basically can we get rid of the sortings here so the answer is yes so with the similar like idea here right uh if we can find the left most uh basically the mismatched and number and the right most mismatched number without sorting that would be ideal right that'll be a of n time complexity um yeah so how can we find that right i mean basically we cannot sort we cannot rely on this sorted array here anymore right so we have so we only have this one here so how can we find that you know if you know we know the uh i think to find the right most one it's pretty obvious right i think we just loop through the entire array here you know every time when we see like uh the current i uh indexes the current uh number is smaller than the previous one right and then we know this one is isn't it's a wrong it's mismatched right then we just update the uh basically i have a left and on the right and we can just update this right and until uh once we have processed the entire array here you know what's left in this uh stores in this right uh pointer will be the uh the right most uh mismatched number here but there's like a coin some like another some scenarios we also need to consider in this case you know we have uh six four eight right so how about this one what if we have this one 643 in this case right so if that's the case let's say you if we have two consecutive uh numbers right uh that's who's smaller than the previous one so assuming we don't have anything on the on this side so in this case i mean the right most mismatched number is actually uh it could be in this case it is three right and we cannot simply compare uh the current one with the previous one and to verizon condition to check if this current one is a mismatched one because there could be another scenario let's say we have 644 right so in this case the uh basically still the right most uh mismatched number is this one okay but if we compare if we only comparing the current one with the previous one in this case they are the same right so if they're the same we cannot tell if this one is a mismatch or the mismatched one or not which means that we have to store uh the this the first number uh so that you know every time when we have like enough as long as the car number is smaller than the very beginning one then the start number here so we always need to update the uh basically the right pointer here and until we have see a different one basically you know now we have since four is smaller than six right that's why you know so the r will be here at the beginning right and then we move to here so this 4 is also smaller than 6 that's why the r will be moved to here so we'll keep updating r here until we have seen a bigger number which is a number which is bigger than 6. let's say we have we is bigger than 6. let's say we have six in this case right but we have eight in this case so now the uh the right is will be pointing to here since the eight is greater than six and then the basically i'm going to have a current maximum so the current maximum from 6 will be become to 8 in this case right so now it's 6 and then we have 10 right so now we have 10. so 10 is greater than 8 that's why you know we are going to update this one from 8 to 10. now we have 9 right so nice smaller than the current max that's why the uh we're going to update this r to here so now the r this is r here okay and then we have 5 15 here right so the 15 is it's greater than 10 right that's why we're gonna we will not update r so after this one as you guys can see here so the uh the right most uh mismatched number will be this r here which is nine and that's how we can just use this current maintain like a current max variables to update these are uh the right most uh unmatched indexes here so how about the left one right so to get the left most one it's actually it's quite similar as it as the as this uh the right most one the only difference is that we have to traverse from the end to the beginning and als instead of a current max here we need to maintain like current minimum in this case because you know actually similar like what we're trying to see find like a ascending others from left to right so when we try to find the left most mismatched numbers here we're trying to maintain like a decreasing order from right to left right and then we use a similar logic right to track these things but instead this time like i said we need we have to maintain like a current min minimum right so for example i'll give you another example here maybe i can help you understand that the second scenario here second loop here so let's say we have 1 3 4 five two so this is a this is like shorter one right so if we do a left to right process uh loop here you know based on our based on this rule here you know we'll have like the right most uh index pointing to here right that's going to be the right most uh pointer so but by looking at this kind of array by simply through our eyes here you know we know that you know the left pointer the left most uh mismatched pointer should be here but how can we do it right so like i said we also need to maintain like a current minimum from right to left from the end to the beginning which means that you know we're always trying to maintain like the decreasing order whenever we see a number which is greater than the current minimum we know that okay we need to update this left so in this case you know at the beginning the current minimum will need equals to 2 right so now the next one is 5. so since 5 is greater than 2 right so we update we will update this one update this 5 with l right so basically this l will become to this uh to this index where zero one two three will become to index three here okay and the four is also greater than two right so that's why the index from two will become from to three will become to two that's this index right and then three is also greater than two that's why the index will be one but now we are at one so one is smaller one is not greater than two which means that you know we can reset this current minimum to one right yeah similarly like what we did for the current max and with this kind of two for loops here we can easily find the left most and the rightmost index we want to do at the sort and in the end we simply do a right minus left plus one right because this is like the length cool so that's pretty much the uh the basic idea here you know so to the implementation it's actually it's pretty uh short indeed after we have after figuring out that pattern here so like i said so for the we're going to have the current max so at the beginning it's going to be a num zero right and then for the right uh pointer we start from uh i'll assign it to zero so for i in range of 1 to n right so if the num's i right is smaller than the current max then we're gonna we're going to update the right pointer with current i right else also updates current max right because we have find a better a basically we have find the uh like a bigger value right than the current max so which means that we are outside of that uh unsorted uh range right because as long as the current one is small it's still smaller than as long as the num's eye smaller than the current max here basically th this if means that we're still in that range of unsorted array here right which means we have two six four three right so as long as the current one is smaller still smaller than the current max we know we're still in the range of the unsorted uh range that's why we just need to keep updating it until we have seen a bigger one that's when we uh kind of start updates current max okay so similarly for the left boundary right we need to do a ma current minimum with the num start starting with uh minus one right since we're going to loop through from the end so similarly l is going to be zero for i in range of n minus two right minus one so now we need to check if the current number's i is greater than the current minimum which means that we are in that a range of unsorted array from right to left as a descending order right and then we need to update the left equals i here else similarly we update the current minimum with the current numbers right and in the end we can simply return the l minus left plus 1. if l does is that's not equal to r right else zero because for example in this case right in this case that both l and r there will be a zero r equal to zero in this case if we do this one instead of zero we'll get one that's why we do this check here okay so if i run the code here accept it yeah so past so as you guys can see this one is pretty fast because this is clearly a two uh loop here and it's going to be a o of n time complexity right comparing to the uh to the sorting one so this one is it's better yeah and it's pretty uh clear right we just need to do a two loop here and yeah the basic idea here you know we just need to find the left most and right most mismatched uh misplaced number and that's it i think i would stop here and thank you for watching this video guys and stay tuned see you guys soon bye | Shortest Unsorted Continuous Subarray | shortest-unsorted-continuous-subarray | Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
Return _the shortest such subarray and output its length_.
**Example 1:**
**Input:** nums = \[2,6,4,8,10,9,15\]
**Output:** 5
**Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** 0
**Example 3:**
**Input:** nums = \[1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
**Follow up:** Can you solve it in `O(n)` time complexity? | null | Array,Two Pointers,Stack,Greedy,Sorting,Monotonic Stack | Medium | null |
7 | so this is my little section called the reverse integer okay so this problem is simple someone gives you a 33 bit sine integer suppose one two three then you just reverse three to one reverse each digit minus one to three you just return minus three to one and if input is one to zero then you just return to one okay so the key point is that uh also there is a condition that we only deal with the integer which in this region if your integer is outside this region then we just return zero okay so we i initialize the empty string and if x your input integer x is larger than zero then i change x into string and i reverse the whole string so if you get one two three then you give me one two three and i will give you three to one then for uh for each element in the string then i just calculate it concrete uh why don't uh why use this okay so it looks stupid that uh actually i guess we i don't mean this i just need l equal to j okay so if integer l is larger than zero is larger than this then or less than this then written zero otherwise i read return integer okay and for let's j we just use minus x and if x is negative then we do the same thing then all is just straightforward or straightforward and uh we return the minus return minus okay so let me try okay yeah so it's very uh let me see i guess i don't need this i just leave l equal to j okay so straightforward and very fast okay so this is very easy just straight for computation nothing special on string method okay and i will see you guys in the next video and by the way be sure to subscribe to my channel | Reverse Integer | reverse-integer | Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1` | null | Math | Medium | 8,190,2238 |
187 | I will come back today we are going to solve list problem 197 repeated dna sequence aa default start looking details of the problem and its implementation is one to medium buried create list code of voting solution videos edison videos to help people in preparing for java j2ee Interview journey preparing for J2 interviews and after preparing for coding for the interview stand established for you I have come back playlist if playlist explained with examples jewelers discussion for frequent last interview questions and how to answer day 100 please look at the earliest and Subscribe to our channel Your subscription to the channel will be really thankful for please do shop so let's look into the details of the problem DNA sequence composed of a series of nucleotides every event with ac quantity for example they have advanced this is or DNA sequence 100 Went Strolling DNA It Is Useful To Identify Repeated Sequence Acid DNA Suryavansh Gas That Represents DNA Sequence Return All The Train Letter Long Sequence Subscribe Upkarmo Dhan Once In DNA Molecule You May Return The Answer In Any Order OK Should Have Universal And String Of DNA Test And Have to identify which repetitions of DNA sequence of ten letters long basically proud soul basically this is one of the famous problem this problem yes-yes pay Google problem this problem yes-yes pay Google problem this problem yes-yes pay Google Indore Interview 100 please make sure you understand this problem so let's look into the Details for example one official explain how to solve this problem that common so this is the inputstream of the DNA sequence given one to us and have to front of repeated DNA sequence put this software into rupees where going to buckle this DNA sequence in length 20 Talendsprint So they can come where cutting this time link train will put the string into her state one right for example in its first see which first time latest ring road that is you can see this 5mm DCO this is the time later this point to solve will not And they will put into the one which has you read to head toe and rule shooting The Channel and subscribe the world will like this and from this a new Delhi right so Dushman you can see this one is the second one exam And Eggs Subscribe And DNA Sequence Similarly I Will Keep Like Not Put All The Time Not Length Spring Tide In Flower Has Set One So As You Can See A Very Rich Like You Have Riched Enter This Point Shiva Will Like To Thank You Can See This Is The Time Length DNA Data 60 Clear Starting From This Point Till This Pond At All The Izhaar All 23 More Strings Of DNA Test 0characters Sharif World War Comment This Point Solid Se Show This Is DNA Sequence Daily Point 340 Letters Sequence Noida SEC 10 Sequence Waver That They Are trying to put this sequence intrastate one now it's going to fight with God is already a sequence president year reduce first password because you can not false duplicate values in bihar state 102 is will duplicate values in bihar state 102 is will duplicate values in bihar state 102 is will capture death and were pushed into his date of birth objective increase DNA Sequence That You Have Found Some Evidence Dhawan The Time Put Into Her To Record Yashwant Bones But When They Are Trying To Put In Is Straight One Right Similar Reduce Highlight One That Sudheesh ODI Highlights Are Becoming In The Plate Highlighted For Years To C And Exit Member The One that already frontier heard co at this point enemies with Android Satish and when the it's getting repeated so when we are trying to put the second time in the back with affordable cost first time to put something in set when it's already present will give you For Solving Capacity Repeated Again Will Capture Date And They Will Put Into Power Acid To So Obligation Will Know You Know Like This Are The Repeated DNA Sequence Show English News Only Have To Take Sours Capture Of Indore Head To Head And Will Just Park Your Love Will Just Like You For Example Is Just Not The Solution Implementation Suggestion 800R This Is The Pretty Much Sexual Road New Year So The Avoid Create A List Of Spring Cold Result In This Just Simply Amazed That They Are Going To Return Rajput Update Software Expected To Return From The function for this would want to change the language of the string events for scientific plead and equal to tenth din hui do not have any DNA sequence side herded DNA sequence 15A sequence in this train basically should just returned lists of results in that case din hui Have prevented two heads one to end this is the length of the string and wear repeat like you yr looking from 021 - 10.02 can - you are you yr looking from 021 - 10.02 can - you are you yr looking from 021 - 10.02 can - you are doing and now they are getting possible DNA sequence now screen brightness i2i plus 1200 in the beginning and zero 210 One to 11221 Laga lut gayo possible DNA sequence and would try to this system of the best wishes Comment out so well try to add possible death sequence * if cost is straight possible death sequence * if cost is straight possible death sequence * if cost is straight line they never in this fact what will be added possible DNA sequencing the second State called s to write positive bond between cities on repeating basically and the adventures se result dot and hold to make it will take all the elements from CO2 and will have enough power list and we are going to returned at least show that is the professional courier Going to take show this is the first sequence practice given to us so let's post run this app has one and mixer it is working for India so as you can see we are getting a correct result care a place where you all have the best examples rather have given Share And What Should And Coat Acid Passes So Both Cases Harpal Singh Sodhi Vijay Submit Our Solution Year 20000 Is 98% Faster And Three Per Cent In The 20000 Is 98% Faster And Three Per Cent In The 20000 Is 98% Faster And Three Per Cent In The Manifested In The Memory Of Trousers Pretty Good So Aam Andar Time Complexity Side And T20 Cricket Improve Its A Me or 2 F 3 - Tats basically enemy will be F 3 - Tats basically enemy will be F 3 - Tats basically enemy will be order of in basically this going through almost like all district and state minister will consider all types of order of invention below the time complexity and sunrise pair time complexity for the solution is going to B order of Android cigarette is time complexity and space complexity you can see that you have prevented or at least of beans as well as you have created to set side saw a to maximum united you can see like it will hold maximum how much like train repeated Sequence One Repeated Sequence Will Get All The Time Created So With To * Doctor Of In Right Maximum * Doctor Of In Right Maximum * Doctor Of In Right Maximum Solidarity With Space Complexity Saundh Solution 100 Days When You Can Solve Repeated DNA Sequence Using The Help Of Two Has States Will Just Go Through The String And Wood Cutter String Like Always Kept The Substance Of Tanks Tractors That And They Will Put Them Into His Native With Great Son Of Bus Already Existing Between Head To Be Positive Getting Irritated And Saturn Will Convert This Into To-Do And Saturn Will Convert This Into To-Do And Saturn Will Convert This Into To-Do List Ander Research Labs Problem Is The Important Problem Yes-Yes Google Think Important Problem Yes-Yes Google Think Important Problem Yes-Yes Google Think Tata And Tried To Practice This Problem That Aam Aisa Units Mention In Open Creator List Solution List Of Toilet Cold Play List Has Over At Problem Solve Explain With Example And Also Check Out The Job Interview Playlist Judge Materials And Preparation For Java J2EE Interview Sir Tube Inverter Frequently Asked Questions And How To Answer Them All As Well As Different Contexts In Java And Innovative Design Patterns On Scientific Research Institute And Don't Forget To Subscribe To My Channel I Will Really Appreciate You Like The Videos Please Like And Subscribe Dating Reality Ayush Dashrath Android | Repeated DNA Sequences | repeated-dna-sequences | The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`.
* For example, `"ACGAATTCCG "` is a **DNA sequence**.
When studying **DNA**, it is useful to identify repeated sequences within the DNA.
Given a string `s` that represents a **DNA sequence**, return all the **`10`\-letter-long** sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in **any order**.
**Example 1:**
**Input:** s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
**Output:** \["AAAAACCCCC","CCCCCAAAAA"\]
**Example 2:**
**Input:** s = "AAAAAAAAAAAAA"
**Output:** \["AAAAAAAAAA"\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'A'`, `'C'`, `'G'`, or `'T'`. | null | Hash Table,String,Bit Manipulation,Sliding Window,Rolling Hash,Hash Function | Medium | null |
85 | hey guys how's everything going let's forget about the coronavirus and continue our trip to meet colt today let's take a look at number 85 maximal rectangle Oh before this video out I'd like to say something about this channel one day I received a feedback comment from some of our viewers said that I should do some editing for my video and he said if I made something up and that we should I should cut it out and that make that video more how to say easy to pull to view or something I think that is a very nice suggestion but I would not do that and as to my as my profile says this channel is not made from like super algorithm guru it's amazed by someone who wants to learn and want to try so there will be a lot of mistakes and in the video and that the solutions the video shows might not be the optimal solutions yet I think the process of thinking of the problems my process of the try would help much sometimes I searched on the internet and I find the best I'll say the standard solution to one problem but I can't I find it very hard to read because I don't know how that solution is generated and how the people think about how to solve it step-by-step so I will continue my it step-by-step so I will continue my it step-by-step so I will continue my style of this channel hope it helps but anyway I have thank him thank the guy who proposed to the editing thing and if you have an idea please let me know and just write your comment on below this video ok I'll continue my this 185 maximal rectangle were given a 2d binary matrix filled with 0 once you find the largest rectangle can Danny only once okay this one so for example we're giving this array we find all the ones so biggest one would be this largest one would be six the other ones like here where before this would be five three yeah this is three so that I think in the first I think came into my mind is that we need to find the time complexity of the brute force one right a good force one with em and array how would that be so each two points in this two-dimensional array would generate a two-dimensional array would generate a two-dimensional array would generate a rectangle let's say for this point even itself it would be a rectangle right so rectangle this will be a rectangle this would be rectangle so generally there will be m and - the combination of two will be m and - the combination of two will be m and - the combination of two out of from M times M right this possibility this is a rectangle but we can it twice right so two to two point and then like say 1 0 this will be a rectangle and we were starting with 0 it will be counted twice so I think there will be like to see to 2 so it is C 2 1 ok sorry 8 - 2 which one this C 2 1 ok sorry 8 - 2 which one this C 2 1 ok sorry 8 - 2 which one this should be 2 right so yeah so generally this should be the time comes time complexity as you see it's very big how big this is I'm not sure I don't remember it should be like the okay I'll skip this just to do the calculations must be very big so how can we improve so actually I didn't came up with a solution for this problem but um this problem is just right to number 85 wait a minute 85 84 largest rectangle in histogram and please if you're interested please search on my channel for a last video there will be at this detail this disc description there it's actually very long and we've made - actually very long and we've made - actually very long and we've made - we've made it to achieve this prop achieved the goal with linear time which is I think it's pretty good so if we compare these two problems we find that this actually this two problem is a very similar the maximal rectangle is March complicated it's complicated more complicated than the previous one but there's a pattern there so if we reduce this array down to one in one row right like this one you will be just number 84 largest rectangle in histogram so 80 not number 84 is a special for case for number 85 with only one roll now so how we handle if there are multiple rows here Wow the idea is very simple we free go up we free Luke look at this array row by row we found that for the first row yeah we carried a largest rectangle with a previous solution and then we get the top two row right and I find the largest rectangle and remember the top three rows yeah top four yeah and we can just do a row by row right so each like for the top three rows the out three ones here so if it's four three in the 2084 at like this the height of the bar would be the consecutive I think it's consecutive the ones yes and here one so here three two yeah for the top three rows it will be 3 1 3 2 4 number 84 right and a four top four rows it will be here obviously it's 4 and here because this is 0 we cannot afford create a bar from 0 so it should be 0 3 0 right and the 4 number 84 so the problem become obvious is that we can just account the ones from top row to the bottom row and we free meet some 0 we just reset it to 0 if it is 1 we continue we add it to the count right so we can say at the Bakey at the beginning it's all zeros and then the 1 0 so it's 1 0 and then for this world because it's 1 0 101 it's become 2 1 0 2 or 1 and then all 1 so 3 1 3 2 and then 1 so 4 0 3 well yeah so these so now we can just start with our solution the first one is copy the previous solution because it would be part of our solution in this new problem okay really and we need an intermediate array to keep track of the count of the ones to pass to the previous solution of largest rectangular area I'll say it would be like count okay so I win I would initialize it to all zero but how much how many zeros there will be it will be Mac matrix 0 map a map edge of 0 but this will be might be empty right so if matrix then is 0 I would say return 0 and the count would be measuring 0 and not we say it for each row of this matrix for each row index what we do for each row we will update the account array and pass it to this function right and there's a result okay max I'll see a result okay but how would we updated account hmm it's pretty simple for let I not IJ equal 0 J small that can this row J if row J equals 0 then can't J equals 0 the other case is what we want so this should be plus equals 1 yeah now the count for each row is updated and we can just pass it to this function right ok so Mac results equals math.max ok sorry equals math.max ok sorry equals math.max ok sorry Allah let me set the font size bigger 16 pixel okay thanks results what this would be count and finally we return the results so it should work yeah it worked and the time complexity because the previous solution would be linear time and we have this would be and this would be you should be in and this should be n so yeah it's n square submit hope it works yay and we are accepted and faster than 50% it's not bad and yeah it's not that 50% it's not bad and yeah it's not that 50% it's not bad and yeah it's not that good either but hmm I think you were doing great for this one because great not great but we so this problem in itself is very genius I think it leads us to how to say reduce this problem to a simple form and define find the solution there yeah then we can just to reuse the solutions we found and make these problems much simpler right why this is cool so okay hope it helps I don't know what is this to be called this should be divide and conquer hmm I don't know five count concrete to fight on conquer it's kind of but we're not using the recursion anyway so I'll stop at stop here hoping it helps and yeah don't forget to follow my channel subscribe my channel and see you next time bye | Maximal Rectangle | maximal-rectangle | Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return _its area_.
**Example 1:**
**Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\]
**Output:** 6
**Explanation:** The maximal rectangle is shown in the above picture.
**Example 2:**
**Input:** matrix = \[\[ "0 "\]\]
**Output:** 0
**Example 3:**
**Input:** matrix = \[\[ "1 "\]\]
**Output:** 1
**Constraints:**
* `rows == matrix.length`
* `cols == matrix[i].length`
* `1 <= row, cols <= 200`
* `matrix[i][j]` is `'0'` or `'1'`. | null | Array,Dynamic Programming,Stack,Matrix,Monotonic Stack | Hard | 84,221 |
864 | Hello everyone welcome to me channel course mike so today you have to understand the instruction patiently after that it will be solved from question to story point only ok and liquid number 864 the name of the question is shortest path tu get which kiss ok and me page is no also available On Facebook and Instagram I think you are already aware of this, okay, it has been asked by Google, let's understand what the question is by looking at the question, okay, the question is quite long, so I have tried to make it easy by breaking it into points. I have given you a macro named 'N'. If dot is written in it then it is an given you a macro named 'N'. If dot is written in it then it is an given you a macro named 'N'. If dot is written in it then it is an empty cell. If 'has' is written then it empty cell. If 'has' is written then it empty cell. If 'has' is written then it is a wall, that means you cannot go across it. Okay, now you can go to the direction from any life cell. Okay. If there is a Has, then you cannot go through it, you cannot go into the cell. Ed means starting point, this will be your starting point. OK and lower alphabets wherever they are, means that the key is your thing and the locks are theirs. They will be present in this TPRM, it is okay to pay attention, it is said in the question that you have to lift all the things, it does not matter that it is not necessary that you unlock all the locks, okay, now one thing is given here that If it is there then you cannot cross it in the cell and if you take any lock, you mean any infinite type of alphabet then you cannot cross it unless you have its correspondence with you, right if its You can cross it only when you have found the correspondent's key. Okay, and it has been given in the question that the exact meaning of the kisses will be either one or two, or three or two, or six kisses among the total. That means the total will be somewhere between one and six. Okay, now let's understand from the example, here it means this is going to be your starting point. If you have to collect all the kisses, then take one of your steps here. Sorry, take one of your steps here. Took it here from your friend, you have got one key, then after taking three steps, five and here there is a lock, but you have the spawning key, so you open it, dog, it is okay, it is not necessary that you have to unlock all the locks. Where it is definitely there, you can unlock this lock, but to unlock it, you need to have the Corresponding Key. Okay, now let us understand the action part of it, then you must have seen the clear cut that it was said in the question that all the keys can be done in minimum steps. If you want to collect and can't collect then reduce the return to minus one but if you want to do it in minimum sex then science has said minimum steps then your mother should have BF, you can find it out in the shortest lesson, right, you can find out all in the shortest number of steps. If this is okay, then let's see how we will move forward in this. You will do it, okay, why will it be yours and you started from here, where is it possible from here, where can you go from here now, you can go only here, from here you have What is the probability that you can go here and not here? If you have already done the visit then it is okay to keep marking them in the budget. This visit has been marked. Now look, when you come here, it is an obvious thing. Look where you are from zero comma. You can go, but right now one comma, you cannot go because you do not have the key yet, you do not have its corresponding key yet. Okay, so we will not put this right now in K. Okay, so where can you go from 0 to zero. Yes, you can go to 0 comma four. Now when you come here to zero comma four, you already have a key, but all these cell visitors are marked, so now how will you go back from here? Okay, how will you go back, but the answer lies in this. It is hidden that you will come back here again, you will just open it is done here and it is done here, your second key will also be found, your answer will stop here, then how many steps did you take, did one, two, three and came back five, six together. Eight No. Okay, so you will have to modify your normal BF a little that whenever you were marking visit mark s = that whenever you were marking visit mark s = that whenever you were marking visit mark s = true, you cannot just do comma, you will have to define it on some straight, remember what is the meaning of defining state. Do, when was the last time you came to this cell or came to this cell then you did not have a key right then when you came here and then when you went back here then you also have a key okay so If you are pressed on a cell then how many key states do you have, you will just have to store that too. Right, just like we set true in Wasted Easy Last, then now one more thing will have to be added that is the status of now, how will we store it. But we will discuss it separately, but this thing is clear that we have solved the problem that how will we solve this problem, now let us see how will we solve the status, how will we store our 3d resident, so now the question comes that How will we store its status? Okay, before coming to that, let me tell you one more thing that earlier we used to put only coordinator in K. From the comment, this time we will have to put one more thing that what is the value of brother, currently. Okay and what is the key value and how many steps are taken right now because look when I went here, then back here, then your You should know that when you have come to this sale, what is your current step account, then here I will also keep calculating the steps, how much is my step account when I have come here, it is ok till now it is clear, so see. First of all, what will we do, we will take out the account, how many kisses do we have, first take out the account, then we will do this count first and while we are counting, we will also mark what our starting point is going to be. There was no starting point A, so we will mark that too, this is going to be my starting point. Okay, so now remember in the question I said, what will happen in the worst way, we will have six kisses in ours, so why not. Let's sign it all from the bed, let's take mother. In our question, we had given three kisses, so one, two, three. Right now, I do n't have a single thing, so in the beginning, we will keep the value zero, okay, this is my binary, but what is the corresponding decimal value? It will be zero, okay, similarly, if we take mother, I have one key, then which one will be the key, it will be this, okay, we will make its value one, zero one, okay, the second key we have is B, okay so. It becomes two, okay, if the number is one, then what will be the decimal value, then it becomes 1247. Okay, if we look at the decimal value, then if whatever number is in my account, if it has that count, then what will be its value, then what will be its decimal value, power of 2. Count mines is one, see here also it is the same, when the number of keys was mine, then your power was 3 - 1, the number of keys was mine, your power was 3 - 1, the number of keys was mine, your power was 3 - 1, the number of keys was mine, your power was 2 - 1, the number of keys was mine, what was your power was 2 - 1, the number of keys was mine, what was your power was 2 - 1, the number of keys was mine, what was your power, what would become of me. What does the decimal value of the status of the current key become equal to? What does it mean? If I get all the keys then I will return all the steps that I have taken at this time. Time is right. Keep in mind that this will be my final step. Okay and you also know that in the beginning you do not have any key, so in the beginning now your decimal value will be zero, right because your power is zero minus one date this one minus one date this is zero okay and How am I representing my key 000, its value is zero, that means I have not got any key yet and how am I representing that if the value of zero becomes one, that means I have got the A key, okay if This value ever became one, meaning I have now and BB. Okay, it is clear till now, so if I say that the value of my set of keys is this, what will be its decimal value? 3 What does it mean that I also have A? Yes and BB is right, now a very important question comes that when I find N key, right now I don't have the key, right, so as soon as I get the key, how will I update my current key? Out of date D key status is fine. This is what is actually going to happen in the top part, after this the whole question will become very easy. Okay, so let's understand this also by breaking it down and see what was the current status. My zero comma zero decimal value was zero and now let's say you get someone's. It was assumed that you were selling BSF Tower. You got one key. So what did I say to B? Which key is this one corresponding to? This one is right, this one is the same one, this one is girls pondering, so I have to change it to one, my current key is Kansa. If you have to do one then see how you will do one, now it is an obvious thing, you do this if else dog 0 comma zero if else do dog zero one zero and if I am asking to do else then will A go to zero one zero I want this B's. Value is one, okay, so what will I do, I will take one, first of all, this is how one is represented in binary, I will shift it from one to left, okay, one will come here, meaning what am I saying, this is one. For this I hit left shift, okay, how many to one, I hit shift, okay, if I hit shift, then what will happen here? Okay, if I got A, then my current status was this, otherwise what would have happened if I got this, I would have to change it to one. I had to hit left shift from one to one, what will I do for one, I will not hit 0001, I will hit shift from zero, okay, if mother takes C, then the current status will be 000, one, I will hit shift from three, okay, peace with the current status, if my Current status is zero. I want that if I get A then its value should be zero one. If I get B then it should be 010. If I get C then it should be 1 0. Okay and each key should be presented only once. If you have then do not take tension that you will get it once more, there is nothing like that, you will get each one only once, it is okay mother, you have got the right of all three, so what will be your value in the end, it will become one, meaning you will have C is also there, B is also there, now it is okay, so what will we do and keep doing the operation, so what does this mean, you simply have to find out by how much you have to shift, so whatever your character is, character A can be B, can also be B. It may be C, it may be C, now don't do anything. Whatever is correct, if you minize it from A, then the value itself will be A. By how much do you have to shift one to perform another operation. If the value of A becomes A, then A - A is zero. A will go given the value of a becomes A, then A - A is zero. A will go given the value of a becomes A, then A - A is zero. A will go given the value of a then B - a1 A will go given the value of ha then B - a1 A will go given the value of ha then B - a1 A will go given the value of ha C If the value of ha is c then C - a2 A will C If the value of ha is c then C - a2 A will C If the value of ha is c then C - a2 A will go Okay so as soon as what was my current status zero if I take mother B got it okay If yes, then what will happen minus B? Sorry, my B is A. Let's take it. If then what will I do? If I do B minus A, then the value will be one. So what will I do? I will take one. I will shift it left once. What will happen if I do one? It will become zero. I will take this more than my current status, this is my current status, okay then zero one will go zero one, okay till here it is clear, so like this we will go out, we will update our status like this, okay status now, what is zero now? One zero similarly if we take Ma I got one more Ki Ma take C I got C Okay so it's an obvious thing I would like this to be one so I will shift this one twice for C so what will it become A 100 A will go right and what will I do, I will take more of this from this, I will take more of this, then what will A go, zero one zero of this and take zero one A is gone, see what it means that you have BB and also C till here If it is clear, then I taught you this so that when we update the key further, it will be updated like this, and you will need only binary value, because as I told you, we will enter the simple value of the status, right here? We will enter the decimal value of the status, here we will enter the decimal value, that is why we will convert it into decimal, it is okay, if it is clear till now, then you have understood the most important part that as soon as you get any key, then how can you check the status of your current key. You will update. Now the next part comes that as soon as you get a lock, you will have to check the status of the current lock. Whatever is yours, whether your key of this lock is present or not, then how will you check this. Let us see this example. Let's assume that you will go with the current mother. Your current status is 0.0. Your current status is 0.0. Your current status is 0.0. You have kept the tax. What does 010 mean that you have the B key? Now it is okay, it is the D one and let's take the mother. Now you have got the lock B. You have to check whether its corresponding key is present or not, otherwise it is B. What will you do? What is your character now, is it B or not? You do the same with it, mines it with capital A. Okay, so you just have to do this. We have to see how many times mother takes 010, how many times we have to shift it at the right time, then we have to take more from one, if it came equal to one, what does it mean that the beat was set, that means I had it, only then we can flood further. And then we will put it in 'K' on the right and we will And then we will put it in 'K' on the right and we will And then we will put it in 'K' on the right and we will put the steps in bigger 'K'. put the steps in bigger 'K'. put the steps in bigger 'K'. In the starting, there will be step zero, then we will move ahead by doing steps plus one. Okay, so to understand this question, we have started from the topmost point. Apart from this question is a simple BFS, okay, so the story points are going to be very simple, first of all what I said is that you should traverse the today matrix and count the number of keys and at this time you start. What is your point, that too you take note, take mother, I came in coma, take note, it is okay, what things will show in us, this came to me, which coordinator is it as well as the steps count. We will keep checking how many steps it took to reach here and the current status decimal value is ok, this will also have to be made noise, so what will we store in the starting point in K, I have started point as it is ok and from zero step, now more decimal value in So my current status is also going to be zero, right now it is zero with correspondence, so I have entered zero, okay, after that I said the website, how will it be when it came, I was relieved, earlier this time we will have to store the decimal value of the status also. Okay, so that means we will have to show these three things in 3D. Hey, it will be our normal address after this. If we write the concept code then it will be clear, but I can go in the direction. If you get the lock, if you get the lock, then first check this. Check that this one is not widgetized, its current status is fine and you have it already and if you take note of the date that you have just received then first check that it should not be self-started and open this lock. should not be self-started and open this lock. should not be self-started and open this lock. So, do you have the key ready or not and how do they check? I told you above, here is the status of the update. Sorry, you checked I have the D key and note, this one was given by Shikha, okay so that. We will fix the thing here and if we can open it, then we will open the lock and push it in and we will visit it. Okay, if we assume that you got the lower, then first check the details. This should not happen, you will have to do this every time, then as soon as you get the key, it is obvious that your new key status will be updated, I have taught you this here, when I find Rakhi, you are already updated, the status of the D key is fine. We will do the thing here and also check the new things that have been done, they should not be in the state, now if there is no website, then we will push it in K and mark it as visited, okay and apart from this, there can be a dot in the right dot. There is nothing to be done, if you come to know that your current status is not current status, it is equal to this, it means you have got all the things, we will write this according to the story points, so let's finish its code quickly. Let's do this and science, you will know that we can move only in the direction, so the directions are here, let's take this, we have been doing this every time, we used to take this equal, you used to take great, after this why do we have to take it, remember that in I want to make noise, so I will take the vector. Okay, what is the tax in this? What was that tax? First of all, what is the coordinate and the status of the current in decimal is clear till now. First of all, the story point is our starting point, okay starting. What is the point, my steps are and now the current decimal value is f if the value of great of i k is given if it is greater then equal tu a hua ok or great of i com k <= f1 is <= f1 is <= f1 is given question alphabet a b c di If if is the character in between the smallest means you got the key then in the count of key plus which dress sorry plus one here I am doing it because I have to check its decimal value okay and in the starting Set the value of all the keys to zero, okay, let's start after this and I told you that in the next moment, if the status of your current becomes equal to decimal, then we will do the return steps, this thing is clear about the current. Whatever status you have got, if it is equal to the final status decimal, then whatever are my steps, now I will return it, till now everything will be clear, right, after that we had to explore the tax directions, okay and that How did the directions come out? Auto and directions. Okay, Internet is the new eye. What will happen Okay, so let's reduce it now. Whatever character I have got the grid of the new three things. There is power if the great eye is there. If this is equal to my lock, then I will have to do something. Okay, here it will be equal to the dot, so what will we do in this, new underscore, okay, how many steps have we got, these steps have been found, now take one more step, then plus one, okay. And whatever is the symbol of Karan's status, it will remain the same because right now I don't have any key, so I have not generated a new key. How did this become so simple? Now let's handle the lock and key. Let's see. If my current character which is K is greater give equal to A and this which is <= F, equal to A and this which is <= F, equal to A and this which is <= F, what does it mean that it is a capital letter, means it is locked right till now it is clear, you remember, first of all, check this. It's okay Whatever my current band will do, it's okay if and after doing one, it became equal to my one, what does it mean that it was bitsat, I mean I have that present of that, have d that you are this. Corresponding lock, if I have it, then definitely what can I do, I can visit it, okay, so I am late after visiting, music current status, changed it to status one, visited it and why is it not time, I have not got it yet, that is why current On the status of the key, it is the same, till now it is clear, now let's come to me, okay, so what will happen in the key, I have shifted it from K to A, okay, till now it is clear, we have shifted it left, you have shifted it to the right, now just get the new status. We have to put a check in this IF status, I am copying and pasting it here, this time instead of new I news A and the new key status symbol will go here A, okay it should not be widgetized, here I will be in set, okay that's all. So correct it, let's submit it and see, it is quite good and there are quite a lot of question and need too, solve this question, there is any doubt, resident de commerce video, thank you. | 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 |
435 | in this problem we have to find the number of intervals that we remove in order to make them non overlapping so we are given a series of intervals so interval has a begin time and time so you can represent it as a pair and we have intervals like this some of them are overlapping some of them are non overlapping so let's say we have this example these four intervals then if we remove this one and one of these then it will become non-overlapping non-overlapping non-overlapping so here the count should be two so we have to just return this count what is the minimum number we need to remove so that these become non-overlapped and this has been asked non-overlapped and this has been asked non-overlapped and this has been asked quite a few times in facebook and amazon interviews so let's look at an example let's say the intervals given are this so let's draw them so we have 1 to 2 3 three two four and one two three so this is three this is four so we have four intervals and you will notice that these three are not overlapping so if start and end times are same we count that as non overlapping so these two can be same but it should not be less so these are non-overlapping and if we so these are non-overlapping and if we so these are non-overlapping and if we remove this still we will have a overlap if we remove this still we have this overlapping with these two if we remove this again this is overlapping but if you remove this then now these are non-overlapping and then now these are non-overlapping and then now these are non-overlapping and this is the minimum so with just one removal we got we made them non-overlapping so we made them non-overlapping so we made them non-overlapping so we will return one so what is the way to solve it uh one way is that here we cannot uh use some incremental solution for example we checked this and this it was non-overlapping we non-overlapping we non-overlapping we went to the next interval again non-overlapping but out of a sudden we non-overlapping but out of a sudden we non-overlapping but out of a sudden we got an interval which is starting before this so all our calculations are wrong and you can work with this also but it will require you to look into the future as future direction also and the past also so that's why what we do first we sort them so that there are no surprises like this so you can sort based on end points or start points both ways should work but let's say we start with start points and we sort them so what should be the sorted intervals so it will be one two one three two three and three four now these are sorted based on the restart time now what we will do uh there are multiple cases one case is so let's write on a separate page so one case is that no overlap so remember that we have already sorted so this kind of scenario will not occur it will be one to two one two three this could also have been before this we are only concerned with the start time then we have two to three and three to four so at least we are guaranteed about the start times now there are multiple scenarios one scenario you can see here let's see these two so there is no overlap here so we are we can now process them in order starting from this one so that we have a previous value and if we have no intervals or we have just one interval then we don't need to remove it so we can always start from i equal to 1 if this is i equal to 0 and then we compare it with previous if previous was removed then we will compare it with the one that we had included so we will keep track of last included interval so that we can compare with it if there is overlap or not and this is the current interval so one scenario is there is no overlap so we can include this one so last included we will update in this case to current index this can get removed based on overlaps in the future but this is a candidate for including so in this case we don't need to increment the removal count we will keep track of count whenever we remove any new interval so this was the good case where there was no inter no overlap and if this current node is not current interval is not overlapping with this then none of the future intervals can overlap with this since their start times will lie at least here or beyond that since we have already sorted that so in case of non-overlap so in case of non-overlap so in case of non-overlap we will not remove so this is non-overlap non-overlap non-overlap in this case simply last included equal to i so in this case remember that we are not actually generating the intervals non-overlapping generating the intervals non-overlapping generating the intervals non-overlapping intervals we are just keeping track of how many intervals we have removed so in this case we don't need to do anything just update it and this will be a scenario like this so earlier this was last included and this was i but when we compared that the end of this is less than start of this or less than equal to then last included is this and we are not concerned with this can now never be removed no matter what is the future interval so this is final so this is last included only last included is compared with the future intervals so this till this point everything is finalized and the other case is overlap in this case there are a few scenarios let's see one is like this and let's say the next one it can only start after this or from this so it ends before this or another scenario is that it started here only but ended before this so these two we will take it take a same case and another scenario is that there is partial overlap so in this case one of them is completely included in other the other scenario would be this one partial overlap or you can also think of this starts here but continues beyond it so now in this case what we should include this is the last included the upper one and the lower ones are i is the current we are iterating from one onwards so last included was initialized to 0 so these values are i is 1 2 3 and so on so main challenge lies in overlap case and this these are all i so in this case by removing this we are always better so if some interval is engulfing the other one completely then if we remove this and include this that would be always the better way uh since that will leave more space so if we remove the bigger one it's completely the interval of the second one is completely included in this so if we remove it we are always better so in this case simply remove this one so our removal count is incremented by one and also this will become the li last included and in this case also we will remove this one and this will become a lie so when in all these cases we have to increment the count by one as soon as we hit overlap we have to remove there is no way out the count will be incrementing incremented irrespective of the condition uh now we are just trying to figure out what should be the next last included interval so in both these cases this should be the last included in this case it will be the last included and we will remove this one and in this case this is the only tricky case where there is partial overlap so in this case we will include this one and remove this one since uh the end point of this is more than the end point of this and there will not be any interval before this which are overlapping since we have already covered that so we are sorting out overlaps so this scenario will not occur also so that means all the intervals before this are ending before this so we don't need to worry about that and any future interval so what can be the future intervals some may start from here some may start later some may even start very later so if these future intervals are overlapping with this one the li one last included one then that will definitely overlap with the current intervals also since it's ending after this one is ending after this and it's also starting after this so all the future intervals which are to the right of this there is a more chance of overlap with this one so whatever overlaps with this one the white one so let me draw in blue so whatever interval overlaps with the white one they will definitely overlap with the blue one and you can clearly see why it's ending after that and only case where some interval overlap with this and not with this is this scenario if they end before this but this kind of interval cannot occur after this since these are sorted based on start times so we are always better off in removing this one so we will remove this one the ith one and move to the next interval and last included is not updated but count is definitely incremented no matter what which one we remove so this is the solution this you can see we are following a greedy approach and what is the time complexity here we are sorting it so it will take n log n time and then in the sorted one we are just iterating once so another n so overall it's o of n log n this is the time and a space we will just use a few variables last included and count so it's of one so let's write the code for this if you understand this then the writing code is very simple for this one so there are a few examples in this case count is one in this case all three intervals are same so we need to remove everything except one so in this case we remove two and in the last one they are non-overlapping so the count is 0 non-overlapping so the count is 0 non-overlapping so the count is 0 and you don't have to worry about invalid scenarios so assume that the end will be at least more than or equal to the start one always bigger in fact so not even equal so if intervals not size is less than 2 that is either 0 or 1 then no removal required else we will solve it that is we will sort it you can also make them const since we will not be changing this let's make it so this is now sorted based on start times zero this vector has just two elements this pair first one is zero index second one is one next count equal to zero this is the count of remove nodes so removed interval so this is initially zero and then last included is zeroth interval and then we start from one so there are two scenarios overlap or no overlap so what is the condition for overlap intervals i that is current interval its start time is less than the end of last included interval end is one then there is overlap so this is the condition for overlap else if there is no overlap then last included equal to current in current index and we don't need to increment count here and then in this case irrespective of what we do we have to increment the count now let's take the two scenarios if intervals i1 so if its end is more if its end is less so the end of ith interval is less than end of last included interval so this is the last one and the current one no matter where it starts it can only start after this due to sorting and it ends before this so this is i this is last included so if it ends before this or even here till this point it does not matter equality you can take in any case these are non-overlapping cases so in these are non-overlapping cases so in these are non-overlapping cases so in this case we will remove this one so count is incremented by one and last included is i but if this is more than this then we land into this scenario we are always better off removing the ith one so in that case last included is not updated but count is definitely incremented so just for updating the last included we are adding this check is less than intervals so that's it and finally we will return count so this works let's take the better example which is this one and also this one and it works so let's submit and the solution is accepted and we are right here at the top so we are towards 95 of the accepted submissions and space should never be an issue here we are just holding a few variables one so let's write the same thing in java so if there are less than two intervals then no need to remove anything otherwise we will sort it based on start time so arrays dot sort and we will sort intervals and the custom comparator will be based on first one start time and this will sort it then we are initializing the removal count with 0 last included at 0 and then starting from the second interval that is i equal to 1 we are iterating so this is the case for overlap if the start of beginning of current interval is less than ending of the last included then there is overlap else it's no overlap so we make the current as last included and no increment in count in this case count is incrementing in this overlap case irrespective of what is the case and the case where the end of current is less than the end of last included we update the last included so this is the scenario where the ith node was ending here that is before this then we will remove this so this will no longer be last included but this will be the last included but if this is the scenario its current one is ending after this then we will not include this one and last included will remain same so this is what we are doing here and finally we will return the count and the java solution is also accepted and here also we are right at 99.9 percent at 99.9 percent at 99.9 percent finally we will do it in python 3. and just to repeat if the number of intervals is less than 2 we will return 0 otherwise we will sort the intervals and by default it will sort based on the first element only so we don't need to provide any custom comparator here count and last included are both zero and the python solution is also accepted | Non-overlapping Intervals | non-overlapping-intervals | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104` | null | Array,Dynamic Programming,Greedy,Sorting | Medium | 452 |
28 | foreign in a string so this is a very simple question we are given a string and a substring we will have to find the first occurrence of the substring in the string that's basically the question but it's given as a little complicated here let's get to read this question try it out to find a logic for this question in order to solve it and then use that logic and an algorithm to finally get coding in the lead code so let's get started so here we are given two strings a needle and an Haystack return the index of the first occurrence of the needle in Haystack or minus 1 if needle is not part of the haystack so this question is basically based on the concept of this idiom a needle in a haystack so essentially we are given a haystack and then a needle is present in the haystack as we know it is very difficult to find the needle in the haystack right it's really hard because the needle is very tiny and the haystack is very big consisting of lots of stuff coming back to the question we will be given a haystack like sad but sad it's the given string here that is our Haystack and needle is the sub substring that we want to find in this Haystack okay so here sad is the substring that we want to find whether it is present in the string or not okay we have to return the index but where it is present okay so with that let's get started so how do we do that we have the first three letters of the substring and let's compare it with the original string so here we have sat and the first three letters of plot Haystack are they equal as they are equal so in this example we got it enough first instance but in the other example that we have here we will return the index of 0 but if we have an example like this delete code so in this example we have code the first four letters of the substring score and the first four letters of the main string is lead so s Lead equal to code no then we move on to the next letter this e t c equal to code no it is not e t c o no t c o d no c o d e and c o d e now it's equal so we'll have these iterations and whenever it is equal to the substring that we have in that case we will return the index if not we'll continue proceeding and at last when we run out of the index or when the array is completed we'll say that we didn't find anything and we'll turn minus 1 if we didn't find anything okay so that's basically the concept here okay but we have a catch here should we check whether lead is equal to code we can see that the first letter itself is not same so there is no binding checking the other letters as well right so first let us get to the point where the first letter is same if we read such an element then we'll check the consecutive letters so this is used to optimize the square algorithm a bit so that we don't waste the iterations on checking for I know wrong access okay so here we have L and C are the same no e and z no T and Z no and finally we get C and C here so we start checking the other two letters o and O are same yes D and D are same as E and E are saying yes so in case if this D was replaced by a cook okay so lead cook in that case will have C and C would be same as o and O are same as o and D will not be same lead cook and the cook is not equal to code right so the letters don't match each other in that case we would say that is not the answer and you want as the next iteration if we find anything in the later part of the string we will return that in next if not we'll get a minus 1 as the answer so this is basically the logic will have a for Loop and then search for this substring in the mainstream okay so that's basically the idea so now let's get to lead code and solve this question so there are basically two implementation of this question the first implementation is gonna be just one line and this again implementation is going to be approximately 10 lines okay enjoy both and then you can reset for yourself which one do you want okay so return we have a function called index of so hey start Dot index of needle this is the exact same answer that we'd get with the 10 lines of code okay since that is a function already built into Java we can directly use it in order to find the answer but of course in interviews the unit accept this single line answer we would have to code the actual code of index of itself so whatever this function does you know we would have to code that logic in order to get selected so I'm just pointing it out that this exists as well okay so let's get started with the actual code so the actual code is gonna be like first let's iterate to the haystack so n TI is equal to 0 I is less than hey stuck dot length of and I plus now in this what are we gonna do is we are going to check whether the first letter of needle and the element in Haystack are same as we saw it doesn't make sense to compare all the four letters in our case with the four letters of haystack if the first letter doesn't match right so the first letter doesn't match obviously we are not going to get our answer then so there is no point in taking the other three letters matches with the hairstyle query a high stack string so the first condition that we are going to say is whether Haystack Dot k at of I is equal to needle Dot carat of zero in that case the first letter of needle and the Haystacks carrot I position would be the same in that case we can move on checking the next letters right if the next let us make consecutive letter the same as a substring and in the main string then you determine that specific index so for that we have to check the other letters right for need we for that we need another while loop so I am going to declare some Loop variables here so we have already used I so I am going to start using J and the J variable is for our needle so it starts from 0. and r k variable let us say is for our Haystack okay so these two variables are the loop variables we are going to write this while loop so the first condition is going to be that we do not want an array index out of one zero right so we must first check that whether J is less than needle dot length of and at the same time K should be less than a start dot length of so these two numbers must be less than the actual or the total length of it only then we'll be able to check the conditions if they are greater than or equal to in that case we'll get array interceptable then we don't want that so this is the first condition that we are going to have but not just this we also need to check whether the elements are equal only if they are equal we can move on to the next element and check whether those elements are equal so the next condition is going to be needle Dot carat of J should be equal to Haystack Dot carat of K if these two elements are equal in that case we would have the substring letter matches with the main strings letter so we'll increment the value of the loop variables I sorry J and K plus and we'll check whether we have completed the substring if in case we have completed the substring and all the letters matches with the main string we have found our answer right in that case J would be equal to needle dot length and if we reach that point in that case we have found our answer and hence we need to return the index which is I so we'll have lead code and then code here LL are not same EC or not same EC is not same DC is not same C and C is same so this condition is true now we come inside we have the J value is equal to 0 and K value is equal to 4 in this case okay now with the values as J and K will continue searching S C and C same yes next let us o and O say yes next iteration of while loop D and D same yes next iteration of Y Loop e and e same next iteration of while loop before that before going to the next iteration we will check whether J is equal to needle dot length our needle dot length is 4 and J it started out from 0 and it has cross 4 at a c o d e now its value would be 4 and hence we have completed the substance so this condition will be satisfied and will return the value of I which was 4 right and that is the starting point of the word code and that is our answer which is the first occurrence of the substring or the needle in the hex tag okay so in case if the element is not pressure we would have to return minus 1 that is written outside the for Loop here so let's run this code for any syntax error that we haven't left and if that's not the case then we'll submit the code and check for all the other rest cases that are given here and congratulations we have solved this question successfully so this is how you solve the question of the first index of the sorry find the index of the first occurrence in the given string okay such an easy question you can also do it in that one line or I guess it's about 10 minutes yeah so this is the solution to this question so wrap this video please drop a like and comment down below if you have any questions and don't forget to click the Subscribe button so see you next week in another episode of field code bye | Find the Index of the First Occurrence in a String | implement-strstr | Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`.
**Example 1:**
**Input:** haystack = "sadbutsad ", needle = "sad "
**Output:** 0
**Explanation:** "sad " occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
**Example 2:**
**Input:** haystack = "leetcode ", needle = "leeto "
**Output:** -1
**Explanation:** "leeto " did not occur in "leetcode ", so we return -1.
**Constraints:**
* `1 <= haystack.length, needle.length <= 104`
* `haystack` and `needle` consist of only lowercase English characters. | null | Two Pointers,String,String Matching | Easy | 214,459 |
17 | hello everyone I hope you are all doing well in the last video we used the recursion approach to solve the problem of leather combination and the phone numbers but the space complexity was of three to the power n so how we can reduce the space complexity and this word is by using the iterative approach so in this video I will show you how to solve this problem using the iterative method so let's get started let's say for example the output is 23. the first thing we're going to do is to create a dictionary called font that's going to have the numbers as the keys and the letter as a values then we're going to create a stack data structures and store the index and the current string at each iteration as a tuple starting with zero as index and an empty string then initialize an empty array called combination to be the out after that we're gonna start with rating over the letter inside the first digit and at each index of the stack we push a tuple contains an increment index and the let letter added to the current string so this is the stack that we'll have at the end of the iteration then we start pops the let's double from the stack and star again with rating throughout the second digits and add a tuple containing the index incremented by one also the current string which is C plus the current letter at each iteration after we reach the end of the iteration we will have a stack that have a tree combination of letter C and the letters of the second digits so we start again popping each Tuple from the stack and check if the index is equal to the length of the digit we push the current string to the combination array once we push all the combinations that have an index equal to the length of the digits we pop again from the stack the last Tuple that's gonna have the index one and the letter b and will repeat the same process another will have all the combination inside the combinations array and then empty stack and finally we'll return the output array combinations so let's jump are called in the solution the first thing if the input is empty will return an empty array then we create a dictionary font after that we created in a stack that's going to have an index 0 and an empty string as a tuple then we create a combination output array after that we start iterating over the stack and Pops the index and the current string from the stack check if the index is equal to the length of the digits at the current string to the combination array else iterate throughout the string of each phone number and at each iteration increase the index by 1 and add the letter to the current string and push them as Tuple to the stack finally return the combination array so for this time complexity is of 3 to the power n where n is the length of the input string of digits because the function generates all the combination by iterating throughout the font dictionary and appending each letter to the current string for the space complexity is often as the size of the stack grows linearly with the length of the input string | Letter Combinations of a Phone Number | letter-combinations-of-a-phone-number | Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** digits = "23 "
**Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\]
**Example 2:**
**Input:** digits = " "
**Output:** \[\]
**Example 3:**
**Input:** digits = "2 "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `0 <= digits.length <= 4`
* `digits[i]` is a digit in the range `['2', '9']`. | null | Hash Table,String,Backtracking | Medium | 22,39,401 |
367 | welcome guys so welcome to my lego section and uh be sure to subscribe to my channel before watching it okay so this paragraph is very easy called the valley perfect square so basically just ask about some positive numbers uh you can write it as perfect square okay i should have write and the computation is very easy we just check for one to and plus one uh so remember this x range is very important if you use range then you will get memory uh memory arrow because it's too large and then you take any number and score it and if you find the number they return to else then you just if you find if you keep going and you already find some number which is larger than your number then you just return fourths so okay so this is just simple loop let me try again okay so it's still success although it looks like not very good but still uh still work okay so and i hope you guys learned something and be sure to subscribe to my channel thanks | Valid Perfect Square | valid-perfect-square | Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_.
A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as `sqrt`.
**Example 1:**
**Input:** num = 16
**Output:** true
**Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer.
**Example 2:**
**Input:** num = 14
**Output:** false
**Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer.
**Constraints:**
* `1 <= num <= 231 - 1` | null | Math,Binary Search | Easy | 69,633 |
39 | hello everyone welcome back here is vanamsen and today we have a very fun on this combination time so we will be tackling this time uh in JavaScript so let's jump to our task so uh this is a medium level program and we are given an array of distinct integer and a Target integer and our task is to find all unique combination of this integer that sum up to the Target so the exciting part is that the same number can be used multiple times in different combinations so for example if we have a target of seven so we can achieve seven by just outputting 7 for our right of two three six seven or we can make a combination so two plus three is also seven so uh first uh how we can tackle this so first let's create our function so we have a combination some function that takes the list of candidates and the target value as arguments so we need to return results which will contain all unique combinations so let's think how we can do this so uh we will create a helper function named DFS to implement our depth first search algorithm and this will take four parameters num Target puff and results so uh yeah in DFS function we will check if the target is less than zero so if so we return immediately as we surpassed our Target value and next if the target is equal to zero so it means we have found a valid combination so we push the path into the result RI and return it so after these two base cases we will perform a loop over our num array recursively calling our DFS function so let's implement it so first let result all right candidate Target results and return result okay so DFS candidate Target results and now we need to implement our helper function so let's do this so it will be just function DFS num Target path result if Target Less Than Zero we are backtracking so return and if Target is zero we have some results so result push Puff and return and four I zero less than num length increment and we call DFS slice Target minus num I so current number and puff num I result and yeah so we have num Target path and result all good so yeah we can run our implementation to see if it's working for this base test case so yeah uh we have combination two three and seven both uh giving a target number of seven so all working a perfect and yeah so we Loop over our nums array recursively calling our DFS function with all four parameters so in the and this line is basically a key to our solution so we are recursively exploring all possible paths by subtracting the current number from the target so notice how we use num slice I and uh triple dose I so to create a new array for each function call so this ensure we don't alter our original array as well so it's really important and lastly inside our combination uh sum function we need to call the DFS function with appropriate parameter and to return the results so as a starting point so and there we have it so let's run it for unsynthesis cases as well to verify if it's working because and since this cases are sometimes really tricky but yeah our implementation works perfect and we beat 51 with respect to random so it's random efficient and 70 with respect to uh memory so yeah all good so perfect it's working as expected so that's wrap uh our coding session for today and if you like the video and found it helpful don't forget to hit the like button and subscribe to the channel for more coding problem solution and tutorials uh in JavaScript and until next time keep practicing happy coding | Combination Sum | combination-sum | Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40` | null | Array,Backtracking | Medium | 17,40,77,216,254,377 |
113 | lead code Challenge and this would be my approximately 900th video on lead code we have been solving lead code daily problems from approximately 2 years now and let's quickly walk through the question says you are given a binary tree and you are also given a Target sum value what do you need to return all the root to leavea path that sum up till the target value so here they provided us with an example I'll be walking you through this example as well as the algorithm to go about it why the presentation and so let's quickly hop on to it the same example that was specified in the question says we have a total Target sum of 22 so what I'm going to do I'm going to iterate in a BFS reversal kind of a fashion and I'll keep track of two three things over here the first one is the running sum as I'm traversing from the root to the leaves along with this I'll also keep track of the nodes that I have seen so far what I'm trying to say let's walk through the same example so let's start the iteration right now the running sum is zero and this is the new element that we are seeing with which is the root of the binary tree uh the value here is five so what I'm going to do I'm add I'm going to add five to this running sum and the total sum gets updated to five along with this I'll also keep track of the nodes that I have seen so far so let me just create an aray list and I'll add five onto it let's proceed ahead what I'm going to do next I'll iterate towards the left child in one branch and towards the right child in the other branch and I'll pass in these values to it so these two values gets passed on to the left child what is the running sum over here is five 5 + 4 running sum over here is five 5 + 4 running sum over here is five 5 + 4 gives you 9 so this gives you 9 this is still not equal to 22 along with this since the sum is not equal to 22 what I'm going to do I'll also add four to the running list value now the running List have two parameters five and four similarly I'll do the same thing for the right sub as well uh here the running sum was five + 8 gives the running sum was five + 8 gives the running sum was five + 8 gives you 13 and the running list gets updated to 5A 8 let's proceed ahead let's start the iteration considering this node as the root node and what we are going to do we'll move towards it left side you'll move towards its right side so let's move towards its left side 9 + 11 gives move towards its left side 9 + 11 gives move towards its left side 9 + 11 gives you 20 is still not equal to the U Target sum that we have 22 and what I'm going to do I'll add values onto my running uh list variables so 5 4 and 9 these are the three variables that got added let's proceed ahead I'm going to do the same thing over here as well so 13 + 13 gives you 26 is greater so 13 + 13 gives you 26 is greater so 13 + 13 gives you 26 is greater than 22 as a result of which uh this branch that we have seen so far 5813 is not a valid Branch as per the constraint specified in the question this Branch doesn't lead to the total sum of 22 that's the reason we are going to discard this up so this gets discarded let's walk through the rest part of the binary tree that we have so we moved towards the left Direction now we'll move towards the right direction and what do we have over here we have four so 13 + 4 gives you 17 and our four so 13 + 4 gives you 17 and our four so 13 + 4 gives you 17 and our running list gets updated to 5 8 4 let's do the same thing again and uh we have two nodes over here the first one is five let's pass in this entire value to the child node 5 + 17 entire value to the child node 5 + 17 entire value to the child node 5 + 17 gives you 22 so uh the total sum or the running sum gets updated to 22 along with this what variables do we have over here we have 5 8 we have four and followed by another five what do you see over here you see that the running sum has become equal to your target value as a result of which you have found out one possibility of answer and this possibility of answer is given by the running list that you have so 5 845 gets added to your answer list so this is one part of the answer it gets added over there uh and let's proceed to the other part of the tree is uh 1 so 17 + 1 gives part of the tree is uh 1 so 17 + 1 gives part of the tree is uh 1 so 17 + 1 gives you 18 is not equal to 22 we're going to discard this up let's move towards the other part of the tree that is left from over here we'll move in both the directions one towards left other one towards the right let's move toward the left Direction 20 + 7 gives you 27 the left Direction 20 + 7 gives you 27 the left Direction 20 + 7 gives you 27 the running list that we have is 54 97 so let's write that up 5 4 9 7 and as you can see the 27 is not equal to a Target value so we are going to discard the up let's do the same thing over here as well 20 + 2 gives you 22 the running sum well 20 + 2 gives you 22 the running sum well 20 + 2 gives you 22 the running sum is equal to your target value what is the running list 5492 so let's update it to 54 9 2 and this gives us the other possibility of answer so in total there are two possibilities of answer the first one is 5845 the other one is 5492 this is in sync with our expectation and we are exactly follow the same traversal as I've just talked here in the coding section as well uh so without further Ado let's quickly walk through it here I've created my list of list which will actually store my answer result so this inner list is for storing one possibility of answer and outer list is for storing all possibilities of answer I've created a DFS method let's see what all parameters are part of the DFS method the root of the binary tree running sum as I talked in the presentation my answer uh that will actually answer list that will actually store my answer is followed by the running list that I talked in the BBT as well and my target some value so let's walk through it uh we have done plenty of questions on similar lines in the past and I'm pretty sure the subscribers of coding newed would be able to solve this question by themselves uh the first check that I have written is if root is null return back otherwise what do you update your total running sum or total current sum you add running sum plus root. Val onto it and you add it to your running list you add the current node onto your running list in case you have reached the uh terminal state that means the leaf node and your target sum is equal to the total running sum what do you found out one possibility of answer and you add the current list onto your answer list with and once you done with this you simply return back you don't proceed ahead otherwise what do you I trate in a DFS fashion and uh you walk through the right side first you can go for the left side either so these two can be swapped uh you update your total running sum with running sum plus root value and you pass in ANS you pass in the running list and you pass in the Target similarly for the left child as well so let's update it also instead of this you can pass in total current sum here as well because it means the same the time complexity of this approach is order of n because you're iterating over each and every node only once with this let's wrap up today's session I hope you enjoyed it also if you're interested in solving more questions of the tree Series where you can go you can find it on coding decoded SD division sheet so go and check out the Tre list and if you more need more revision this is the right place for you'll see those questions as well that are highly important from interview's perspective those are marked with double ASC sign so if you have a very important interview lined up these are the questions that are must to also in case you stu get stuck with any of the question the YouTube solution is stated as well uh in this column so uh you don't have to look out for any solutions over the net everything is listed over here with this let's wrap up the session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel your subscription truly means a lot to me thanks for watching it have a great day ahead and I'll see you tomorrow with another fresh question but till then goodbye | Path Sum II | path-sum-ii | Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_.
A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** \[\[5,4,11,2\],\[5,8,4,5\]\]
**Explanation:** There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** \[\]
**Example 3:**
**Input:** root = \[1,2\], targetSum = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000` | null | Backtracking,Tree,Depth-First Search,Binary Tree | Medium | 112,257,437,666,2217 |
11 | So friends, our container with most water today will not reduce the pen writing on the copy because there is not much need. Let me explain the question a little, so what I am trying to say is that you have all these pillars, it is okay and you have to add water. Meaning, if you pour water, where will it fill the maximum amount of water, where it is visible, only a small amount of water will fill here, but I had to find the maximum, so what is the maximum, here two things are metric, first of the height of this pillar, meaning the one in the middle of it. How many pillars are there, van tu three four five six seven gap are there and what is the height of the minimum one because the water will fall below the maximum here, hence the height of the minimum one is also 7 77 which is 49. If I took eight then it would not be 64 from 8. There is a little bit below, so how much is there? It is 1 2 3 4 5 centimeter. Okay, I am telling centimeter just in case. Here the unit will be called unit and 85 which is 40 is steel < 49. The maximum which was there was 49. Now we steel < 49. The maximum which was there was 49. Now we steel < 49. The maximum which was there was 49. Now we can do two cases in this. In the first case, I tell the brute force technique that if I take a man, we hold it, this is our left and we move ahead, right, consider this, then consider this as maximum. Keep updating it and force everyone's root by doing maximum, that is, hold all the pillars, okay, and in our case, we will have to do it individually with all the pillars, our answer is that man in zero starting height. From where to where will we take it, okay what to do now Length * Here the minimum has to be seen that who is smaller from the left and right because if we look at the bigger one then the water will spread, whatever our answer will be, it will be the maximum one, okay It's simple, is n't it? Area means we will return it from here, please return it, sir, just submit it and see, this is our small code, here the time limit increases, if we do this using the fruit technique, then what can we do? Any good technique? We can find it, let me tell you how, we will not do it like this, then move forward, what we do, we grab two from each corner, go it, then this will become our left which is our left most and our right. Now what will we do, if we look at the one on the left and the one on the right, we will move our smaller one forward and then keep finding our maximum area, okay then the height will depend on the one whose height is more, it will remain the same, see its height in this step. The height of both is equal, if it becomes bigger then we will reduce it from here, then by doing this, both will shrink. Okay, and we will go from left and right to left to right and then we would have made it a comment out. What did we do and took the answer as zero? Which was already taken, our left is zero's right, our left side is our area, then look at Y2 again, our area will remain the same and the answer will be our maximum. Look, whichever height is less, it is lying on the right. What should I do? If both are equal, if you move someone forward, what should I do? | Container With Most Water | container-with-most-water | You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104` | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | Array,Two Pointers,Greedy | Medium | 42 |
284 | hello everyone welcome to day 25th of april elite code challenge and i hope all of you are having a great time my name is sanchez i am working as a software developer for adobe and today i present day 667 of daily lead good question the problem that we have in today's peaking iterator again it's a design level question and it looks like a design week on lead code from past one week we have been seeing design questions only here in this question we need to define peaking iterator class that has four methods in it one is a constructor the one the other one is the next method followed by has next method and the last one is a peak method for all those who have been associated with the channel might know that we have already solved this question in the month of february 2021. i have clearly explained the algorithm in a step-by-step fashion and trust me you step-by-step fashion and trust me you step-by-step fashion and trust me you guys are gonna love this video up i'm attaching it's linked in the description below so do check that out and i genuinely hope you thoroughly enjoyed it up i have also quoted live for you guys so in case you are interested in looking at the coding section this is a video for you the comment says it all with this let's wrap up today's session i'm attaching its link in the description below so do check that out and in case you find it worth watching please don't forget to like share and subscribe to the channel i'll see you tomorrow with another fresh question but till then good bye your friend your mint or your catalyst in this journey of yours signing off sanchez take care | Peeking Iterator | peeking-iterator | Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
Implement the `PeekingIterator` class:
* `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`.
* `int next()` Returns the next element in the array and moves the pointer to the next element.
* `boolean hasNext()` Returns `true` if there are still elements in the array.
* `int peek()` Returns the next element in the array **without** moving the pointer.
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
**Example 1:**
**Input**
\[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 2, 2, 3, false\]
**Explanation**
PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\]
peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\].
peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\].
peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\]
peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\]
peekingIterator.hasNext(); // return False
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
* All the calls to `next` and `peek` are valid.
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
**Follow up:** How would you extend your design to be generic and work with all types, not just integer? | Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code. | Array,Design,Iterator | Medium | 173,251,281 |
920 | most didn't chart so this is a hard problem 920 number of music plays and less musical plays music playlist your music player contains and different songs and she wants to listen to L not necessary different songs during your trip you create a pointer so that every song is played at least once a song can only be played again if k other songs have been played we turned a number of possible pointless as the answer can be very large return 8 by 10 to the 9 plus 7 okay what is where as a constraints everything is less than a hundred okay every song has plenty of these ones that's fine this one can be played again if K on the songs up and play so okay so far and you ghost we ended that's just three factorial that's right six - you have factorial that's right six - you have factorial that's right six - you have two songs BAM hmm okay I mean it's a comet or Explorer problem and it's probably some sort of dynamic program we don't have to think about it everything is a hundred so what are the subproblems okay the subproblems is hmm okay I get part of it but when I have to figure out how to make sure we play our songs which maybe it's not as hard as songs but when this sub questions are okay maybe and I think I have some vague ideas in my head I just have to figure out how to articulate it in a precise way and I think there I mean you know I think that I always - with dynamic programming is I always - with dynamic programming is I always - with dynamic programming is just kind of white out to be current so you have alpha and K and this may not be exhaustive but uh but for example that means you stuff and songs where now L minus 1 because you played the first song in the first one and or L minus K actually well I guess K is just okay plus and minus one and then you start from maybe even see no well minus 1 to L minus 1 because 1 song was played and then K and then you kind of is that it what are the other ways you know cuz you have to play every song so it just has to can only count on when they get one and then this is negative 1 because L minus 1 because well there's an L minus 1 oh just L could maybe cook either way I was a widget thing L minus 1 because you play just currents saw in you oh you played the current number song and then it was done with anyway so they put this in more kind of visible I mean I think I'm not explaining this well but let's say you have three songs to be well that's it that's two songs of three lengths and K as you go to zero so this is like Camus or something like that but yeah this represents to me is so you're still playing so yeah so this means you have song let's say you have two songs have a song a and some B and you have a link to a none of it is filled yet and what this represents to me is it's equal the first slide yeah the first song is a and you have two more slots free and then you recurse on that plus 1 minus 1 k so this may be 1 so I gotta sleep what this means to me is okay we put so this is a where we can still put in additional a so at the bottom with length 2 here because you're forced to put at least one a but now you're done with a so you put a anywhere but then there may be an overlap so maybe right to do something like to make sure we don't double count but where do you put so this actually maybe just out of time because that 1 plus a sub problem of that this represents me F of this place because there's L ways to put it and then put you're done with a forever in this case but in this case you just ever yeah you just put in the front skipping K letters you know I guess in both case you're putting a in front so you would have to subtract something no vessel in this case in theory but subtract to overlap risk to overlap in this case oh how do you describe a I guess it's just everything with Matteo and we're getting but that's just F of - so maybe this but that's just F of - so maybe this but that's just F of - so maybe this just cancels out am i convinced that's works no I did the same well no so they definitely do not cancel because this is f of a somewhere where the second parameter you will is done with a and this is can still have a right okay so and overlap it in this case and these two so what we have to put it is this minus this or like what is the set difference between these two sets well such differences it's just two characters where none of them are or where neither where with no way right because if there's no way then it so actually now that I think about it as a result this is strictly a subset of dis where does that difference is just this so actually in that case and it's just this - or you want to simplify that this - or you want to simplify that this - or you want to simplify that maybe something like that it's not the answer and the base case of course is that your web we put in or the song so and as he goes during L is zero then we're good and that returns one possibility and then we just kind of build that dynamic programming from that also one thing you can do about memory is noting that you only go minus one so BAM that got to worry about that for now I'm just going to okay I will try to code often and in this case it should be roughly should be an square right there's no loop to anything so and we each we visit each sound like once something but not but come in the end is a Honda should be our kind maybe I'm cute let's take a look don't put actually they find us mmm I guess negative once why me this can't even take a possibility though yeah don't we're doing bad stuff bit okay was a ten to the ninth so that's also a little weird but in that we actually should use longest intermediates just in case we over form accident and K is always a constant okay so and I'm gonna get this one just because I'm gonna move something okay I mean this is trivial to type and I'm just trying to make sure I consider overflows and stuff like that because this is kind of actually a little bit weird mmm-hmm because I voted a weird cuz I mmm-hmm because I voted a weird cuz I mmm-hmm because I voted a weird cuz I expect them maybe we live with more communication but maybe not maybe oh my god well this one it real quick just for base cases oh I forgot actually put in their base cases so we write off so and or some length 10 otherwise I don't pursue then that's not a valid pointless I mean where did I mess up oh I guess just up Oh minus K minus 1 s could be negative okay those other cylinders case because in this case it always said okay maybe not actually then what does this actually read again well actually what will be one when Tao is your zero I think maybe I'm up a little bit hmm cuz this case say we skip X letters but we still need to count to us okay so there's a mud bit of something here so it's something like just this component but this actually x how to throw out the K that's inside so top n minus 1 is it just K yeah I guess so okay and okay something like that actually hmm but basically that's just a number of sequence so in this case we which is rich in numerator stuff that's in the middle for skipping other well put in this case actually there's just empty so it should be you go to one but if we have K is like 2 and we skipped two letters then that's what we would do okay kind of hand waving a little bit about that the lesbians like that okay well Elise is now returning well it's not crashing anymore oh cool but when this night have them in a different order yes that's right now if like this no game in this but maybe not time because we still have song you forced to play than this well still walk wait maybe slightly less Wow well I say just see was all the way that's a little tricky can we not get and this part should not be - hmm you and this part should not be - hmm you and this part should not be - hmm you wanna put for the first one it is just three factorial so like the surprise should be zero most of the time and this is still generates - something - so it's is still generates - something - so it's is still generates - something - so it's K okay it's 1 0 so this returns one hour in hours because I feel about it what we assume it's right first nope okay so at least that's undercounting not over counting now that so this should be C which is true this is one which is also fine - its - you is one which is also fine - its - you is one which is also fine - its - you know ok that's true is one two and two one mmm that's also true don't we use okay so we got two of the components are correct but we're not I did as a multiplication or something missing so two or three what does that mean that means - its first okay don't we print the - its first okay don't we print the - its first okay don't we print the first Patrol mr. 302 this will just always be one this case is zero this is just one times two or two so two plus one yeah don't tell me cuz I'm multiplying it I will be quick I just get as well no prob happy that my intuition is still white because to me so now it's one that over Tula this is one right there should be two right - Tori this is one - so this should - Tori this is one - so this should - Tori this is one - so this should be too - it's gonna be four even though I know that's still well but hmm okay it's the backwards I can think about this recurrences a okay what is this we it's going to it worry you go to so we choose the first letter is 1 because we have to well that's the point of this just three of them which just gives us into a another service treat her well one two and one two it is a night when ahead it's one because you just have one night of love so it's just gonna be both twos so yeah so just represents one to know I guess it oh yeah 2 1 2 and then 2 or 2 1 you have some crazy operation hmm seems ok and the mod so it's confusing but uh ok theory that part ok oops but that you also do it now for this part three to twenty so that's one great so you have one data with tweed I just one remaining song with what no songs in between so that's just 0 - 1 x - 2 yeah between so that's just 0 - 1 x - 2 yeah between so that's just 0 - 1 x - 2 yeah which is you go to what does he go to get going to this what does it mean actually to me instead two letters would love so that could be it's not even true this means putting the one to everyone in the front with two letters F of 1/2 in the front with two letters F of 1/2 in the front with two letters F of 1/2 is that ugly it's two to two numbers to that so it's just ok they cannot be the same so just like one two there should be only be two which I show I think that myself I'm still missing something even if my form is right I also don't know why it's give me three instead of five but maybe there's some order of operation thing well maybe because it's hmm this is so what does this mean when this is soon oh there's nothing in space okay I think maybe there's two definitions here and I'm trying to put them into one frame it's no length but it's daddy's love it has to fun hot put in between I don't think this is the right function probably why you ever know your bike had gotten it why do that when you still walk but so does this actually should be just as a constraint I don't know I guess this is the unbound version of it so that you're not forced to have n is 0 because n could be yeah because you're forcing the pound version to the rest of it maybe there's a really awkward way I'm putting it there's nothing like a bit early we're not forced to wait for cashiers let's put this as one point now but well no it's got a little quick okay maybe not because what I'm thinking is data inferior you want this function to be unbounded and in that case and like you to put any song and anything in between I wonder there is uh that's okay but then you have well what that means is that it's and - yeah well and - one to that it's and - yeah well and - one to that it's and - yeah well and - one to the K which is fine I guess no but let's try not yeah - let me name no but let's try not yeah - let me name no but let's try not yeah - let me name it you only care in a case there's just return n to the K wait okay I'm just going to a laser just request but the bad stuff ok so this is 5 which is correctly incorrect so I'm missing the case where one of the two spent 2 1 2 is here two-one-one so I'm not modeling two-one-one so I'm not modeling two-one-one so I'm not modeling two-one-one correctly because I always two-one-one correctly because I always two-one-one correctly because I always assume that we play the first time beginning that's okay is it okay and there's a lot of double counting that's what I worry about I was pretending in order just pretty another way still easy way to Sounders maybe there is an easy way easier way to solve this and I'm just doing it a dumb way in that okay yeah I think another way I can think about solving this because I think we have been doing is a no-mess inna is we have been doing is a no-mess inna is we have been doing is a no-mess inna is that like a pre-calculated table in that like a pre-calculated table in that like a pre-calculated table in which well let's say with a link and then we could do an L and L length playlist then we can recalculate we go calculate the number of ways we can choose basically I'll choose one I'll choose to add a diet I'll choose I in such that each of the numbers are K apart or something yeah each other and then after that we could run another dynamic programming problem I think I mean in which you're just kind of for each other and that's just you just kind of recommend it along the way I think that's what I'm gonna do okay cool I'll do it that way and both of these are two dynamic programming problems okay how does erase this I could leave why'd you later have to have formulated maybe I'll put in a learning notepad just in case I need to copy paste later actually okay how do we do it okay so for this problem for now I'm trying to figure out this one this is a problem where the number of ways so we want to pre calculate the table that the number of ways that you can choose I songs you know choose I songs where they're K away from each other okay actually attending better with you too but okay because I would just go back to your phone and figure it out as I go okay mmm I guess I shouldn't have today okay so basically how do I solve this let's say we have this magic function that lets us use or put yeah let us use I of I songs on the list so okay so actually a lot of this may just be still because of nature of how it goes - now gaming is hard I just took a break - for now okay so now we're using well we need just to be at least one because we need to have this song somewhere so with tons of this number and then we - our - I and of this number and then we - our - I and of this number and then we - our - I and mr. K and we times just by a second function that let us know the number of possibilities of our songs and I okay I think that's right I think there's some stuff around modding because I'm just gonna get big so I hate that okay yeah could be one statement but okay this should already be my about to smart it again just and also have to cast us too long otherwise you make it over for okay so I didn't put in the base case yet but I could think about in a bit well I guess this action needs to know K you know it doesn't use it basically okay so how do you calculate this it's just like given the beginning the idea Oh what is its not TP oh did you go to came just maybe well actually no mmm you're kind of a maybe not Oh that's right you couldn't print the next stitch it and devil very Sokka I buy this and in the base case if n equals egos I don't otherwise well just cannot go negative because I use only out okay here just a base case here well yeah if Lily and I've have and so soon and it's number songs to everyone yeah otherwise I guess me negative no not this one anyway - not yeah okay also cannot be negative well that's a little disheartening oh but uh well that's what I didn't mmm I have too much stuff so at the Cass still should return something but uh okay hmm whap oh what a lot of coal billion barely been better okay it was about disco first well that's different look oh long wonder that matters hmm matters here at leas Oh baby that doesn't seem right Oh let's just let me come oh man using typical weird notations been doing c-sharp lately okay given that just to c-sharp lately okay given that just to c-sharp lately okay given that just to lengthen one mm-hmm lengthen one mm-hmm lengthen one mm-hmm probably okay so one two mmm where's dr. case how many times returning zero yes and question what I'm doing the second one okay - yes - is that lady it was just one - yes - is that lady it was just one - yes - is that lady it was just one number left just two girls two dozen same way that should be one it's only one case that the case last he put this one first then there should be one oh so now it's returning zero so I don't even know but body too soon one of this should be one so when is - chocolate - to justice for two - to chocolate - to justice for two - to chocolate - to justice for two - to encase you okay mmm any specified in my way because we did encounter one that we will move to put on okay so we don't get here at all do we catch something silly oh my god huh twice to one over you just got lazy that's also why we got different answers for four different sub problems with same problem is now it gives me the right answer but that one now we try for two it way too many silly mistakes yeah that's also correct how do I only get dysfunction is not pulling its weight Oh mija yeah I'm living there's Maathai wants Aristo so yeah because this should be too yeah this should be too two one it's okay to have out laughs excess you let me run okay it's more like time you have to imagine on the last one someone like right I guess I come in you know plus one even that's true though no just feel happy that one kind of and one day it just one no that's alright one should live here Oh mrs. Takase pay which means actually do I know this is way best to look at but I'll fix it about I'll clean it up okay yeah of course if we have no more xlab it doesn't matter what ours tell me it's time to try it on a bigger cell no me okay well buddies for some caves now you go through civil wave up that's sad okay well my logic is I'm more confident about my logic now so I'm just so there's just some coding issues just fine good that seems reasonable actually we choose disses well I think that we've Tuesday as well as meters off by one with this maybe is wrong that should be true maybe right that's definitely true medium yeah just now I come back to this is quite right because you put one knowing that you've walked in X just him you start okay yeah well that may be a little too much actually because it's very but okay I mean that is to choose function is right I think cuz well you're gonna tail one also we just don't end up reducing not don't using not using K anywhere someone like - okay as well that's where someone like - okay as well that's where someone like - okay as well that's where we use it and now we have to check in declaring maybe it's quite sudden crash actually but okay mmm okay so I'm more covered by this choice function so now maybe the other function needs help so yeah one song left with makeup to soak up that squirt I have won some weight on one I believed her it took 221 this is this should not be a well actually I'm mixing some stuff again I leave my pace cases as well but this should actually be one why because if one song and to let the one possibility because they're just the same song and we don't have to care about Kay in here okay I believe that so why is every touring as you don't um this is returning so close test takes account just takes account Kay okay oh just do another function that I've got course this is right but I think I'm mixing them in not necessary correctly but because I'm trying to componentize it in a way that maybe issue but it cannot be componentize possible people like this fall yeah I think maybe this Way's also well oh man but how did I make them right cuz not combining them necessary and in my way because I think some part of this a simple to some part of this assumes data cuz I mean I've refreshed in something but uh some point of this assumes that we already took care of K and somewhat apart systems that we didn't mmm-hmm we've got to stop I'm scratch mmm-hmm we've got to stop I'm scratch mmm-hmm we've got to stop I'm scratch again no got my first solution I think that may be my first lotion is still closer now I see the for my second object all right it's my original code from the first time that's not true that's ways half of it yeah I didn't copy the whole code Dallas then I do here yeah I'm just missing one case maybe I could have been better mmm what's actually okay with you I just needed to buy them in chunks um okay mmm so like that but what kind of nice that's perhaps don't oh yeah is it and I know that's why I got confused to be a change K now well just long face yes this is roughly more right but I don't think about it in my base case as well I will rethink my base case okay so I guess we get to a point where yeah don't even happen where I didn't even expect this to be waited on us you like we know I just protect this if this somehow works I don't even know how that is both hilarious witness that way can you do more time questions yep okay what did I do mmm-hmm typing all the other cases that mmm-hmm typing all the other cases that mmm-hmm typing all the other cases that they give us okay well I guess my initial intuition was more correct let me say well let me say like okay at ease as well yeah that just seems like an edge case though it was three four into that means dead and two apart I said yeah well that's not good wait what's two songs with legs doing it was like almost right but not really because I've just to maybe most is just negative one oh yeah well we have one song into that is laughs yeah that should be soo oh this thing mmm that's not that rare could I be negative numbers with maybe okay I mean this is cleaner but I guess this is pine away maybe okay fine uh-huh because you won maybe okay fine uh-huh because you won maybe okay fine uh-huh because you won this second part if that's why it's bad but okay I'm just struck David an uncanny do not know whips me so why did I change okay well so I took care wonder educators okay so that yes on the end is still telling programming I don't know why it took me and now when I have to solve this problem I think I was maybe there's enough I win some of my logic but basically yeah there's some to look back in my notes and see how I formulated a no way but basically yeah this part is just the number of recurrent or the number of playlists that you know we put this letter is our last one I think we had in you before so there's a and then we're done with that dad's song and this is the number of ways such that we put in this song but that song is not finished just like -1 and in this n minus K just like -1 and in this n minus K just like -1 and in this n minus K because this X tiffin there's that many places to put the next song I just kind of over complicated myself and open an expense up but uh yeah I guess part of it is was to haven't got a couple of weeks but huh yeah so this is just uh this should be a standard dynamic programming problem but I thought every will complicate it but uh yeah I think this is yeah this is worth every standard I don't know I think for an interview question I like have you happen this thing before well we haven't and my style is that I actually like any aversion to have more type poet so that when you give hint or not the person for one point if they have trouble they take it maybe you know you still have some signals and in fingering if it's worth like you know maybe you know she's just work with dynamic programming maybe they could you know do some qualms or something like that so I'd like to kind of like proms have got a mode for part where like if you stuck with one point maybe you could you know nudge them to focus on the other port and kinda minis get something done and kind of see the signal to then you know in aggregate you can see if you know what level you she is that but in this case it's still just you know it's dynamic programming farmers may be a tricky one maybe is the easy money but how you feel about it but uh but it's still you know once you get to recordings are straightforward and if you've been practiced on that program well maybe that's it'll go a little bit easier yeah I had so many part of this so I think one thing I just as a personal thing is that I just need to get banjos I've been interesting to be a little bit more practiced but definitely add all the components they I just didn't really put it together in the end and hopefully if this was a really real interview don't touch me in the right way a little bit but well for I think this is an okay problem yeah and I think the other kind of tricky thing about this problem that you might have to worry about is that because the mod the module to modulus its way close to a barrier where we just cost a billion but it's also like just slightly under end but not so slightly that Jeff waving one so that's why I like you see use a long over the place and in theory or everything should just be long and then you kind of mind in the end that to help buy you some peace of mind while you some peace of mind because you know that you're only doing multiplication between two numbers that should be in so that when your modded it would still be int so that and yeah because if you multiply two ends and two bursts you get ISM it's a 64-bit integer so everything will stay a 64-bit integer so everything will stay a 64-bit integer so everything will stay so you can prove to yourself that if it's for that living will still be smaller than mine before and afterwards yeah cool I mean yeah I'm gonna have to look at it eight two can't go through to see what how you know what kind of hosted I get stuck on and I think that's something that uh you know I think people should figure out what they've been doing correctly and incorrectly so I was definitely in that | Number of Music Playlists | uncommon-words-from-two-sentences | Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
* Every song is played **at least once**.
* A song can only be played again only if `k` other songs have been played.
Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 3, goal = 3, k = 1
**Output:** 6
**Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\].
**Example 2:**
**Input:** n = 2, goal = 3, k = 0
**Output:** 6
**Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\].
**Example 3:**
**Input:** n = 2, goal = 3, k = 1
**Output:** 2
**Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\].
**Constraints:**
* `0 <= k < n <= goal <= 100` | null | Hash Table,String | Easy | 2190 |
1,007 | everyone welcome back and let's write some more neat code today so today let's solve the problem minimum domino rotations for an equal row so basically a domino has two sides the top side and the bottom side so we're given an array called tops which represents you know all the values of the top array and another array bottom which represents all the values of the bottom portion of the dominoes each of the values on a domino can be a value between one through six so this one is a value of two and the bottom one is also a value of two but we could have any values between one and six it could be a one it could be a six it could be a four etcetera we're allowed to rotate any of the dominoes so we could rotate this one or any of them and all we really want to know is what would be the minimum number of rotations so that all the values on one of the sides either the top side or the bottom side are all the same if it's not possible though then we have to return negative one so let's take a look at an example we can see let's just go through each of these dominoes so this one has a value of two this one has a value of five this one has a value of one this one has a value of two 2 and 2. so now the question is there a possible way that we can rearrange these dominoes not rearrange basically swap some dominoes so that all values on the top or on the bottom are equal is it even possible well for that to be possible every single one of these dominoes has to have one value that's common between all of them is that the case right now it is this one has a two and they all have twos right not all the twos are on the same side you can see that this one has four twos here and here while the one on the bottom has three twos here and here so we definitely know that it's possible but the question is what's the minimum number of rotations in this case well it's not really difficult to come up with how to get that minimum because you know when you take a look at this domino of course this one is missing a domino and this one isn't we know that each of the dominoes has at least a two some cases both of them have a two value but the only thing we need to know is that how many dominoes on the top side are missing the value of two in this case two of them on the bottom there's three that are missing right so how many swaps would we have to do to fill in the top we'd have to do two swaps how many swaps would we have to do to fill in the bottom we'd have to do three swaps so in this case we'll take the minimum which is two and then perform two swaps and then return that so pretty straightforward but how can we algorithmically verify that it's possible to achieve this and then get the minimum number of rotations needed well the good thing for us is that the values are actually limited between one through six so we can actually have six different for loops or while loops or whatever and check that check for every single domino does at least one of them have the value one check that for each domino if they don't we try that we repeat that for values two through six we check does at least one of the dominoes for every single domino have a common value pretty much so it would still be a linear time solution because six times n is still big o of n time complexity but we can do slightly better we can actually get this down to be uh two times n and the reason is we can literally just take any arbitrary domino we could take the first one and just say okay the first domino has the top value of two or a bottom value of 5. so we know that the only possible values that are common to every single domino are going to be either 2 or 5 because we know for sure that 1 is not going to be common to all the dominoes because it's not even in the first domino so it's not gonna work same for three same for four same for six none of those are going to work in this case we took the first domino but we could pick any domino we could take the second dominant and see oh well both of them have two so the only possible value that's going to work is 2. so then we'd check every single domino with the two value but in the generic case they'll have two different values so then instead of having six loops we'll have two for loops checking if two or five are common to every single domino and at the same time we'll be keeping track of how many uh missing values are on the top row and how many missing are on the bottom row and if we do find that it's possible to do the rotations we'll have to return what the minimum number of rotations is so still overall a big o of n time solution no extra memory needed though so now let's code it up okay since we know we have at least one domino i'm just gonna take two variables target one and target two and just you know take let's say the first domino the top value of it and the bottom value of the first domino and just say you know these are our two target values we're going to go through two loops and check are one of these values in every single domino we'll go through top bottom in we can iterate through two arrays at the same time in python by zipping them so top and bottom zip together we'll be iterating through a value from each of those i know the naming might be a little confusing since there's just an s missing from each of these but so this is our first loop where we're going to check okay is either the top value equal to the target or in this case target 1 or is the bottom value equal to the target well in that case we would want to continue but if that's actually not the case where we can check pretty easily just by putting this whole thing in a parenthesis if this is not the case then we're going to break this loop and just exit otherwise we want to keep track of how many are missing and how many are missing on the top and on the bottom so i'm going to create two more variables miss t and miss b for missing bottom and top maybe i should just add the three characters to make this a little bit more clear so now we can actually increment the missing accounts for the top and the bottom so if top is not equal to the target then we can say missing top is going to be incremented by one and do the exact same thing with the bottom so if the bottom is not equal to the target then missing bottom is also going to be incremented by one and at the end we're going to return the minimum of these two but how do we know if every single domino contained that or not well the easiest way here would be to check the index so if we did have the index i is equal to length of tops or bottom because the length of these arrays are going to be both the same but basically if i has reached the last index then we can return and what we're going to return is going to be the minimum of missing top and missing bottom but it turns out we didn't have the index when we wrote this loop but we can do that pretty easily just by wrapping this in another function called enumerate which will just basically allow us to get the value and the index at the same time as we iterate through it so on the top just have one more variable i for the index so now this is pretty much good to go now obviously if this didn't work uh on the outside we'd have to try it the second way right with the second target value over here but we can actually just maybe instead of copy and pasting this we can reuse this code by uh maybe saying target in uh this array t1 and t2 these are the two target values we're gonna try of course if we had to do it the other way where we uh we're gonna you know literally iterate through all through values between one through six we could replace this array with an array of one two three four five six but this array is a little bit smaller so let's use that and actually let's just not even create variables t1 and t2 let's get rid of that as well and let's replace all the uh calls to t1 uh the references with target oh and actually i noticed i had a t2 here that was unintentional by the way we were supposed to have t1 here not t2 okay and that's pretty much the entire code so i think if we enumerate this it doesn't return three values so instead of getting both of the values like when we zipped it we're going to get the pair and then we can just extract that pair of values in to the top and bottom variables because while this does return you know an index and a pair that pair is nested inside of this pair that's returned as well so we can't extract those in the same line i think but okay so that's pretty much the entire logic now of course if neither of these two targets works then on the outside we want to return negative one and as you can see on the left yes it works and it's very efficient so i really hope that 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 | Minimum Domino Rotations For Equal Row | numbers-with-same-consecutive-differences | In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6` | null | Backtracking,Breadth-First Search | Medium | null |
131 | welcome back guys to the cool show this is harvest and today we are going to resolve palindrome partitioning problem on liquid so first we are going to explain the problem and second we are going to digging down to the hood level so what they are expecting to get input as a string like aab and then you they are expecting to subset or substrate sorry substring is solid string this partition or this string it to a small palindrome rotations so we're going to decompose or substring the main string ministering to a small shrinks or a small trunks or whatever partitions but should be a palindrome partition so we're going to explain first the expectation from to imagine how we can substring our string all right so in this example we got a b so we're going to substring first a and this a it's a valid palindrome yeah it's a valid palindrome then we are going to substring the another character it's a so it's also a valid palindrome and we will end by p it's about it also it's a valid palindrome because it's every little element in this string it's a balanced rom so uh a it's a parent room it's a valid balance room and a mb then we're going to back because we are already in a backtracking function it's a back tracking problem so we are going to pack to increase our substring to check it's valid or we can create another patent drum partitions or not so for example or in our code will behave like we'll take a and b because you are backing from the last level so we are getting e and a so we increase dna so it's a not palindrome problem so we're going to ignore this result we're going to eliminate or ignore the non-palindrome partitions so we're the non-palindrome partitions so we're the non-palindrome partitions so we're going to ignore aap and we'll increase or eliminate b and take a and a so it's a valid palindrome partition for me so i'm going to take b and alone it's already a palindrome substring or a balanced partition for the code so for now we got the two result that we are looking for so or the problem blocking four so aab it's happen and a with b so it's already happened here in our solution and last thing we are going to do to take the full string uh together the four elements together it's not abandoned service triangles are not room rotation for the code so we are going to uh ignore this result also so we are going to pack just the valid palindrome partitions or valid for palindrome substring elements so let's digging down to the code but before we're going to dig down to the code we are going to create two functions the first function is the dfs or our back tracking functions the second function we are going to create a function that is it will be responsible for detecting if this element or this substring it's a palindrome or not so we will name it is palindrome it's a boolean function or not so we that's it we got these two functions let's dig down to the code first is they are expecting to return a substring a vector of substring of string so we're going to name it to define a container as a big result and we're going also to define our the result itself that we are going to inject or inserting it inside the container for sure we are going to return this container also we are going to call our backtracking function to build or our backing tracking function to build is this sub string is so we're going to start by zero this is our element or our pointer that will be uh responsible for locking for each element inside this inside the string so we're going to first define our void dfs function and this is our pointer or our position and this is our items here it is a string this is a string but we renamed the two items so this is pure a recursion a recursive backtracking function so we are going we have to but we have to determine our base conditions so our base condition is when the position is equal items both sides this is our base condition so is this condition happen we're going to push inside our container to push back the result so let's build this result in our recursive function so we're going to define we are going to create a function or sorry a for loop toward to iterate over every element inside this uh inside this string so first i'm going to define this is it's looking weird but it's not big we are not just we're going to start from this position of zero we're going to from this position to avoid the duplicated result and to prevent any infinity loop and are going to continue f i lower than items dot size and then we're going to increment this i plus then we're going to this is our loop and that we are going to looping over our each element or each say each character in the string so our we need to do um substring or artificial inside a partitioning process so we're going to define a variable we name it string we name it so we're going to sub to substring this um items a two starting from position zero or whatever position until i minus position plus one and that's our trick query our trig port that we are going to substring we are going to store some string between range so this is our part in this board we are going to partition our substring by range so starting if the position equals zero so an i equals zero so are going to take to pick one element we go so we incremented we added plus one here so we're going to take a and in the second iteration you only take the second element will be a and the third iteration we are going to pick b so and in every iteration this range will be will uh will be um we will be increased to get the fall as a full string as we explained here so are going to pick only if this m is a valine drum or not so this is our big scenario that we are going to pick if only we have only if only the stem is a palindrome substring or a palindrome partition so let's define the palindrome partition first function so it's a boolean function we'll take the string temp and what's the palindromic function we're going to do for example let's first take level as a temp as a variable so we are moving to using a two pointer the first pointer is looking for the first character or first element in the string and the for the last pointer is looking for the last element in this character so we're going to move we're going to iterate over this string using a two pointer in this two pointer uh in every iteration one we are trying to make sure that the last element of the right pointer is equal then equal to the left pointer so are going to decrease we're going to decrease uh right pointer and increase the left pointer to lock to the second character if it's already equal right so is a valindronic so is if not we will return false so let's do let's determine our left pointer is equal zero because we are starting from the beginning and right pointer is equal to temp dot size minus one because we are looking for the last pointer the last characters the character yeah so we're going to loop if lift is lower than right lower than or equal right okay to and this condition to uh to prevent any overlapping here so to prevent also any infinity lobe and we are going to check have the stamp of left not equal our temp of right so we're going to return false else we're going to increase the left pointer and decrease our right pointer and then we're going to return through because it's a could arrive if the iteration is uh yeah if the compiler arrived here so this is a right palindromic ring so we're going to pick what's what we are going to pick this result the stamp inside already defined the resultant variable so we are going to push back the stamp and then we're going to recurse here like we are going to solve is the smallest this is that we are going to resolve the sub problem for from starting from this position so we're going to pass i plus 1 because we already solved with i so we're going to solve i plus 1 and then i think the items again and we are going to undo our result to uh to free space for the another scenarios so we're going to pop back and this is our do scenario and this is our pop so let's run this code forget to add a semicolon okay let's pause aab as an example or let's use yeah let's use all like testing cases all right it's accepted let's submit and get accepted right we get accepted thank you for watching it's including show | Palindrome Partitioning | palindrome-partitioning | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters. | null | String,Dynamic Programming,Backtracking | Medium | 132,1871 |
1,879 | hey what's up guys uh this is chung here again so uh design number eight number 1879 right minimum x or sum of two arrays uh so this one you're given like two integer arrays right number one num2 of the same length and the xor sum of the two integers is for each corresponding index we do xor for those two numbers and then we summarize everything together right and you need to rearrange the elements of numbers too such that the resulting of actual sum is minimized right and you just need to return the this the minimize the minimum x or sum after the arrangement right okay so pretty straightforward and the constraint is like this so n to the power sorry and it's only 14 length so you know every time when you guys see this kind of like a smaller length here you pretty much know already we can try like using the beat mask which means we need to have like bitmaps to represent each number right uh with some state and even if this happens you know usually we also we can also use some dp plus uh bitmask bit manipulation technique to solve this problem so let's take a look right i mean since we can rearrange nums too it means that you know given for each given num num1 here uh it can be it can do x or with any number in nums too right since we can arrange the numser and in any way we want and obviously there's no greedy approach here because ax or is pretty unde determined different ministries right it's quite undetermined uh when you when it comes to xor because you know there's no such in a greedy way such that you okay we find like two numbers with the biggest number and we do xor so because the result could be anything that's why you know since there's no greedy approach we have to use some we have to try all the possible scenarios right and you know so the fact and one fact is that you know since we want to find the smallest actual sum you know if we have like some uh arrangement right if this one if you do x or for these two arranged uh number numbers here you know if this one is smallest any subset of the uh any subset of these two numbers basically if this thing is smallest this one if we do x or with this part it will be it also be smallest i mean the smallest in the sense that you know if there are like three numbers if we pick three numbers sorry if we pick three pairs out of the six pairs and if we can if you want to do x or sum and then that three pairs will also be small uh the smallest number there's i think there's a proof for that but i'm not going to detail into detail for that so which means that now we can break this problems into a smaller size problem right since you know since we're getting the biggest one sorry the smallest xor for the entire sub entire pairs right and so the sub problem is that you know any sub pair is also smaller value it's also smallest extra sum given that size that's why you know we can have like a deep state here you know so basically uh we can use the dp state so the first one is i here you know second one is the mask right so what does this one mean it means that you know the i means that you know uh we are trying to uh basically this i mean that you know we have already matched uh i numbers from 0 to i and now the mask is that you know the mask basically it was like a 1 zero one zero right so zero means that number from num that's the mass for numbs two zero means that number in number two has not been paired or has not been matched before one means the ones the number has already been paired so which means that you know given this num given the i and the mask here so this one means that it uh zero to i so the numbers in num one right the numbers in num one from zero to i has already been matched given this two state this one means that you know the minimum sum right given this state which means that we have we still have some numbers from numbers one that we have we need to match from i to n right and then the second one is that you know and we have this kind of uh numbers from nam su that we haven't matched given this two state we can get uh the minimum value right the minimum like sum for the remaining numbers and among all these kind of possibilities you know we need to get the minimum and that's the uh the definition of this dp right and actually this one is a pretty classic dp definition you know uh we have a lot of dp problems has a similar like state definition where the first one is the uh it's a current uh nums one that we're trying to match right and the second one is the mask that's the candidates that we can use so basically to match the current ice numbers we need to try all the possible numbers that hasn't been haven't been matched right and once we find once we do that right we can update the mask accordingly and then we can move this eye forward and we just need to get the minimum amount of all this kind of scenarios right and with the dp it can help us reduce the complexity because like i said uh given this i if the eye and the mask are the same right and then the result should be the same because we already know the answer right we if we already know the answers uh given this iron mask right we don't have to recalculate right we can just simply return it okay cool so and the implementation actually is pretty short you know we have defined dp right there's i and the mask and then we have r u right of cash none so if the i is equal to n right we simply return zero it means that we have matched all the numbers we can stop here and then times 1 otherwise right we try all the possible numbers from numbers 2 that has not been matched before right so for j in range of n we just need to check if this bit has a value have the value zero so we can do a uh mask to uh this kind of beats left shift by j and then if this one is zero it means that okay we can pick this one right and if we pick this one it means that we're going to use this number to match the current ice number right it's going to be the nums i x or nums times j right so i think we need to have like parenthesis and then the remaining part we can handle it to the next state which is the i plus 1 and then the mask will be this xor we're going to mark this bit to become one right okay so return the answer so that's it i guess right dp800 right all right if i submit yeah there you go right so nothing too fancy and so the time complexity here we have the mask right obviously this one is 2 to the power of n and then we have another like i here um i would say this one is like in here maybe and then we have another n here like yeah but this one is like i think 2 the power of n is much greater than the n than n squared here right so it's more like of 2 to the power of n well you can add this one i think it doesn't really matter and yeah so that's it right i mean a very classic dp plus beat mask problem right i mean this is like a pattern already right basically you use two states here you know the first one is the one uh it's a number that we're trying to it's a it's an item that we're trying to process and the second one it's that the is the other side like the uh what are the candidates that we can apply to the card number and once we apply that one you know we update this mask we pass it into the next state and then among others all those kind of scenarios we need to get the minimum right since we can break this problem into a smaller size problem that's how we can use db right okay cool i think that's it thank you for watching this video guys and stay tuned see you guys soon bye | Minimum XOR Sum of Two Arrays | maximum-score-from-removing-stones | You are given two integer arrays `nums1` and `nums2` of length `n`.
The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).
* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4`.
Rearrange the elements of `nums2` such that the resulting **XOR sum** is **minimized**.
Return _the **XOR sum** after the rearrangement_.
**Example 1:**
**Input:** nums1 = \[1,2\], nums2 = \[2,3\]
**Output:** 2
**Explanation:** Rearrange `nums2` so that it becomes `[3,2]`.
The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.
**Example 2:**
**Input:** nums1 = \[1,0,3\], nums2 = \[5,3,4\]
**Output:** 8
**Explanation:** Rearrange `nums2` so that it becomes `[5,4,3]`.
The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `1 <= n <= 14`
* `0 <= nums1[i], nums2[i] <= 107` | It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation | Math,Greedy,Heap (Priority Queue) | Medium | null |
1,822 | oh hey everybody this is Larry this is day two of the medical day challenge hit the like button hit the Subscribe and join me on Discord let me know what you think about today's poem so you're given a function that returns one of X is positive negative one return sign of okay I mean yeah I think we just multiply them all and then just return this right and of course you can't really do it quite that way because even for modest and this is going to overflow just to be clear but if you kind of think about the domain of numbers uh that can be um you know both an input and output then you know it's kind of simple and that you just convert everything to one negative one and they're just kind of product over it so yeah or maybe you step down like this and then for x and nums if x is greater than zero uh you know nothing changes right so then now X is zero then uh and then else if x is equal to zero then current is equal to zero and then that's pretty much it right I mean you can probably do this in a one-liner if you're really like funky one-liner if you're really like funky one-liner if you're really like funky about it but I don't really think I'm gonna you know uh it's fine I'm a little bit lazy right um you could also done it with like an if statement or something like you know if x or if zero is in Norms we turn zero uh and then maybe just do some count or something like that if you want to do a one-liner I don't know it's pretty uh one-liner I don't know it's pretty uh one-liner I don't know it's pretty uh today's a pretty silly poem to be frank right so I mean but it is you know not uh but just to be clear right like that may not be the intention to make it not complicated it's okay to warm up once a bit but definitely uh you know if you're trying to do one problem a day and this is your one problem maybe uh maybe challenge yourself a little bit slightly more anyway I have with this one that's what I have for today really I don't know don't have much to add to this one so yeah stay good stay healthy do good mental health I'll see you later take care 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 |
242 | is valid anagrams from lead code and this question is also listed in the blind 75 given two strings s and t we want to return true if t is an anagram of s and false if it isn't so anagram is different than what you might have heard from in the past compared to a palindrome so palindrome reads the same from left to right as it does from right to left for example one two three two one an anagram is simply a frame a phrase formed by rearranging the letters of a different word or phrase so as long as the letter count is the same and the length is the same then it is considered an anagram so for example if we look at example one anagram um for s t is an anagram of s because the number of times the letter a and g are am all those letters occur are the same now if we look at example two rat and car you can see that there's an r and there's a c and there are just letters that appear in t that doesn't happen that doesn't appear in s so this is false another example is here on the right hand side bobby right b o b y and the group underneath y-b-o-b-b y-b-o-b-b y-b-o-b-b these are anagrams because the letter count is the same what isn't is the one below with an exclamation mark there's a character here that appears in one which does not exist in the other it's not a valid anagram also if the length is different then it's not an anagram because there's an extra letter now this is the way you'd want to mentally visualize it if we're concerned about the occurrence of the characters we need to create a map that maps the letter to the occurrence so on the left hand side s right for anagram we know that a occurs three times and occurs once g once and so on now we need to have now we need to compare that to t so let's go ahead and iterate through each character in t starting with n we know that on the left hand side n occurs once and we need to know um does t satisfy the anagram requirements and if it does we can subtract n we can subtract the number one from n so now our map n is shown as zero and what we can further do is just delete that key and you can see from the object in the center and is gone and i've just left it as a red on the left hand side now we'll shift over to a and for a current count is three and on the right hand side from letter t we can we want to subtract 1 from the total so it becomes 2 and we will move on to the next letter g currently occurs once and we'll subtract 1 and that becomes 0 and we'll remove that from the object and we'll move to a occurs currently twice now because we've already deleted it once we subtract one and we'll move on to the r is currently one we subtract it becomes zero we remove it a again is one it becomes zero we'll remove it from the key and finally m is one we remove it and now this is an empty object and what you can do in javascript is do an object.keys and that'll return object.keys and that'll return object.keys and that'll return an empty array a length of zero so this is the mindset is s is our template it's what we are it's a reference right all the letters and its occurrences are going to be from s and t is where we subtract the letters that we see and if everything turns out to be zero it is an anagram so let's dive into the code okay so diving into the code i'm not going to live code it here but i'm just going to narrow it through i think it's a little bit easier for you guys to read our first check right here is i'm checking the length of snt if they're different we can return early because it is not a valid anagram and then i'll have my s letters object this is my map between the letter and the number of recurrences it'll have so i instantiate that and then i'm going to iterate through s to build that map so for every character in the string s if it doesn't exist then we're going to map as it occurring once now if i encounter that letter again we're going to increase that count this line these lines actually build the map now from line 20 onwards i'm comparing t to the map so for every character in t if that character doesn't exist in my map i can also return early and it'll be false but if it is in that map we can subtract it and if it becomes zero we're going to delete that key and after all the iteration of the characters if at the end everything is deleted we'll get an array from object.keys with a length of zero from object.keys with a length of zero from object.keys with a length of zero and if it's zero we'll return true otherwise we return false that's it thanks | Valid Anagram | valid-anagram | Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case? | null | Hash Table,String,Sorting | Easy | 49,266,438 |
36 | let's solve valid sidoku number 36 on leak code we want to determine if a 9x9 sidoku board is valid so here for the first row all of the numbers we have placed there must be no repetition and they all must be numbers between 1 and n and we're also guaranteed that each element is a digit 1 to N9 or it's a period saying that it's nothing at all first we're going to validate the rows and we're going to make a set each time we look at a new row if the number is already in the set that means that you have a duplicate you should return right away and otherwise you only want to put that number into the set if it's not a period so we'll add that number in the boxes are these 3x3 squares for each I start and J start in the starting positions you need to send I through I start and I start plus three and J through J startart and jart plus 3 to look at that specific box once we've gotten here we've validated the rows the columns and the boxes and we can return true drop a like if this was helpful | 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 |
1,675 | hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you not like the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started so problem is minimize deviation in array uh we'll be given an array of n positive integers so if you see the input there is an area given and it has n integers and those all will be positive you can perform two operations on any element of the array any number of times so this operation we can perform on any element in the array any number of times if the element is even we can divide it by 2 so 4 is even 2 is even we can divide by 2 for example here array is what 1 2 3 4 you can do this operation on the last element is 4 which is even so we can divide it by 2 so 4 divided by 2 will be 2 so array will change to here 2 will come and if the element is odd for example in this area we have one is odd so what we can do we can multiply it by two so one into two will be two so this here then two will come and rest of the array as such so right we can do these operations if the element is even we can divide it by 2 and if the element is odd we can multiply it by 2. the deviation of the array is the difference maximum difference between two elements in the area that is maximum difference between two elements we need to return the minimum deviation that can in the array after performing these operations for example we need to reduce this deviation the difference between two elements we need to reduce is as much as we can and that is a reduced deviation we need to return so let's see this example this is test case given right let's understand what the problem is first so we need to uh in the output we have to return minimum deviation what is deviation is the difference between it's the deviation is c deviation is a maximum difference max difference between two elements now obviously see guys what will be the maximum difference between two elements in an array if we take the smallest number and if we take the largest number that is largest number minus smallest number will be the maximum difference between two elements this is so easy right like what will be the maximum difference we take the maximum number we take the minimum number we subtract them and that will be the maximum difference so here maximum difference is 19. this is the deviation this is deviation we need to re we need to reduce this deviation we need to minimize it minimum deviation that means see when we are saying that we need to reduce this value 20 minus 1 is equal to 19 we need to reduce this 19 minimum deviation so what how that can happen we are subtracting see we are subtracting maximum and minimum right how we can reduce this value fun there are two things which we can do either we can do these things like see either we can decrease this maximum value we decrease the maximum and we increase the minimum right so like if we decrease maximum let's say 20 is it's changed to 10 and this one is increased it's increased to let's say 5 or 6 so now see difference will come less now so we need to return minimum deviation that is we need to reduce this 19 this value deviation value so for that we have to decrease the maximum element the value of the maximum element we need to reduce and the minimum element value we have to increase so that the difference is reduced right this will be the approach now how to execute this thing how to apply these operations because see how we have to reduce these values this maximum value this minimum value we have to reduce the maximum and we need to increase the minimum but how we will do that there are certain rules we can only do these two operations all right so see here what do we have here we have maximum value as 20 this is the max and minimum is 1 in the array so over here they have written that if element is even we can divide it so we can divide this 20 because this is even so this is even right 20 is even we can divide it by 2 so then we get 10. then again this is even r so again we can divide it so 10 divided by 2 we'll get 5 now we cannot divide because 5 is odd we cannot divide 5 and see there is no point in multiplying also because we are reducing from 10 to 5 now why to multiply again we were already at 10 so there is no point of multiplying right again so we not multiply we will just stop here so from even number see from this even number we reach to the odd number then we stopped when we reach to the odd we stopped because we cannot divide by 2 because divide by 2 only we can do for even and multiplying by 2 doesn't make any sense because we were earlier at 10 only so why do again go to 10 all right this is one thing for this minimum this is odd number now so odd number we can multiply by 2 so let's do that because we need to increase the odd uh increase the minimum number so we'll multiply it 1 into 2 this will be 2 because this is odd this is or that's why we are multiplying right if let's say here it was 2 the minimum element in the array was 2 then we will not able to multiply because this is even number we can only divide by 2 even numbers we cannot multiply so here if 2 was there we cannot multiply it by 2 here minimum is odd it is 1 that's why we are multiplying by 2 right so don't get confused on that so we multiply this 1 by 2 because we want to increase the value of minimum so that's why we are multiplying it so now we get 2 now we have to stop here because now we cannot see now we cannot do anything now here we cannot do anything this is even so for even either we can divide so but why to divide we were already at one so if we divide it we again go to one that's that doesn't make any sense right so see guys now from this you will see something see if you look closely this one if your minimum element which is given in the array is odd number here it was 1 if you multiply it by 2 because odd number we can multiply by 2 if you multiply by 2 you will be thinking why we are multiplying because we need to increase the value of minimum so that this deviation is decreased right if you multiply it by tuna it becomes even any number any odd number three five seven once you multiplied by tuna it will become even number so you can only multiply once any odd number by two so this multiplication operation can only be done once on the odd numbers i hope you are getting my point see this multiply this multiplication operation can only be done once on all the odd numbers so let's do one thing we have this arena 4 to 5 23 we have this array 4 to 5 23 so we concluded that only once we can multiply all odd numbers by 2 because once they are multiplied by 2 they become even so then we cannot multiply again and obviously there is no point in dividing because then it will reach back to its original number so see what we will do in a first step one we will multiply or all numbers once because once only we can do we just saw that multiply all what we are doing over here is multiplying all odd numbers by two this is first step so let's do that basically what we are trying to do now we are trying to reduce the max element as low as possible we will do by dividing it by 2 if it is even and we are trying to increase the value of minimum so that deviation is reduced we need to reduce the minimum deviation right this is what we are doing so now we will see the dry run of this approach so first step what we are doing we are multiplying all odd numbers by 2 so here 4 is will be as such it's not odd also here it was one i by mistakenly written it in the test case here it was 1 4.5 23. case here it was 1 4.5 23. case here it was 1 4.5 23. so here one will come so this odd number will get multiplied by 2 so 1 into 2 will be 2 see now it is even now 5 is also odd 5 into 2 it will be 10 20 is even as such and 3 is also odd so 3 into 2 6. so this first step is done multiplying by all odd numbers by 2. so this is one step we have done all the minim this odd thing we are done with this now we can use this second operation was if the element is even divided by two so now we will reduce the even elements so that difference is reduced so second step will be what we will do see what we will now try to do see this is kind of you need to understand what we will do now so see right now the minimum in this array is 2 minimum is 2 right maximum is 20 max is 20 and difference is 18 20 minus 2 now we need to reduce this difference so max we need to decrease this 2 cannot be increased further because this is even either we can divide it or we do nothing right so dividing doesn't make any sense it will again come to one so that we do not want to do so this is the maximum minimum that can possible right as of now maximum is 20 we need to decrease this so what we will do we will divide this 20 by 2 so let's do one thing every time we will have to find now that what is the maximum element in this array we have to traverse every time let's avoid that we can make a we can have a data structure that every time that will give us the maximum element which is in the area so for that i hope you guessed it we will be using a maxi we use a max heap so maxi give us the maximum element every time so earlier when we were multiplying all the odd numbers by 2 as we will be multiplying like we multiplied 4 will be as such so we'll pop it we will push it in the max heap then we get one into two we get two so two we will push in the maxi so like when we were multiplying that then and that step only we can also push in the max heap so here 10 will be pushed 20 and 6 so this will be your max heap right now see what we have to do we will pop out uh the maximum element from this maxi 20 will be popped out 20 is the maximum we can store it in a variable 20. now what we will do uh we will find the difference let's find the difference this is the maximum element 20 minus 2 18 so 18 is the right now the difference now what we can do is this is even number this is even so we can reduce it by we can divide it by 20 divided by 2 so this will become 10 so now we can push this 10 in the maxi because now this 20 here this 20 is reduced to what 10 we divided by 2 so 10 we will push in the maxi 10 so see guys what we do what we did in the second step we popped max element from heap right we compare we found out the difference will be minimum of the current difference which is the current difference and the this element which is popped minus the minimum element this will be the difference all right so then after that what we will be doing is we will reduce this element by two and we will push it in the push in the maxip again push in maxi because now it's reduced 20 is reduced to 10 so we'll add it in the maxi push in maxi also we need to just need to check whether this mx by 2 this new element 10 if it is uh less than this minimum because if this is less than this minimum then that will be the new minimum so we will just check whether the current minimum should be is like minimum of current minimum and this mx by 2 right now 10 is not minimum so 2 will be the minimum only now let's again do this so what we will do is again see i know it's bit of complicated but when you will try running you will understand don't worry so now we will again pop max element from heap then we'll be put so there are two tens so first this let's say this 10 is spot 10 is bond all right now we will find the difference 10 difference will change now difference will be this is the maximum element right now see right now this is the maximum element in the array so 10 minus difference is 10 minus the minimum which is two so difference is right now eight difference is right now 8 this is the answer like this is the output which we will return this will be the this we have to make it minimum all right so difference we have done but then we will divide this by 2 so 10 by 2 see this is even so that's why we are dividing it by 2 10 is even so 10 by 2 5 and we push it in the maxi so 5 is pushed in the maxi why all right and then what we do is so this 10 is now again change to five okay now we will be calculating the minimum so minimum this is five and five is not less than two so minimum will be this one now again same steps will pop from the above maximum element from the heap so what is the maximum element is 10 will be mobbed and difference will be again 10 minus 2 so it will be 8 only nothing will change and push it again in the maxi so 10 divided by 2 5 so 5 will be pushed in the maxi here 5 will be there 5 so 5 right and then this minimum will be to only now again same steps so now again max will be popped from the maxi so you will be thinking till how long we will do these same steps again you'll understand right we'll get to that let's do it again so now maximum is six so six will be popped and we will find the difference so six minus 2 6 minus 2 is what 6 minus 2 is 4 so minimum is 4 sorry difference is 4 now and we will divide it by 2 so this is 3 and we push it in the max so this is 3 here this is now change to 3 all right and then minimum will be three uh so three and two minimum is two only so minimum will not change now see now again same steps maximum will be pushed from a pop from the sta this maxi so now maximum is five now guys see is there any benefit of doing all these steps now why no benefit because this five is odd we cannot divide it by two so we cannot decrease further this is the maximum element that can be now we cannot divide it further by two this is all this is odd element so either we can increase its value by multiplying it by 2 or we do not do anything so see we need to decrease now we need to decrease the maximum value and this could be the lowest possible maximum value now it could not be reduced further so these steps we will do until the pop element from the max heap is even until the popped element is even we will continue doing will be continuing uh continue doing the steps popped element is even until once the popped element is odd this was odd then we can stop because this now further cannot be reduced we cannot do mx by 2 for this is odd now see we are we will come out of the loop and at last the difference will be maximum is 5. that is we pop we will pop from the max heap the maximum element 5 minus the minimum which is 2 so the difference which is 3 this is the minimum deviation this is the difference which could be and this is the minimum difference so 5 minus 3 the maximum element minus the minimum element so this is how we will approach this problem i hope you got some idea this is uh see earlier what we did now we first of all got to know that this operation multiplying by 2 1 this can be only done once to all odd numbers and we have to increase the value of the minimum so that's why we are multiplying and then this division we can do to decrease the maximum value all right so try to dry run this on other test cases also this approach so i hope you understood let's see the code once for this so see first of all so we are creating this maximum maxi so this is i have taken this max heap this is maxi priority queue and then this m is the minimum element this thing which we have taken and this difference also i am taking so both i should be minimum now so i'm initializing them with the maximum value which could be there so this difference also should be minimum and this minimum also should be minimum so initializing it with inbox into max then first step what we are doing is we are multiplying all the odd numbers by two so here we are going to each element in the vector in the num array and if they are odd then we are multiplying them by two finding the minimum every time because like when we go to each element so we will be finding the minimum also along with it so minimum two will come all right and uh side by side we are pushing them also in the maxi so we discussed that right when we will be multiplying odd numbers by 2 like 1 into 2 here 5 into 10 was here now so like that then we will be also adding it in the maxi so this is done after this is the second step now second step we will pop until the number is even so keep doing this until number is even that is the top element uh on the priority queue max heap is a even number and what we are doing see these steps pop from the stack uh sorry maxi we are popping then we are finding the difference between this element which is popped and the minimum element this m is the minimum we are finding the difference and then see finding the difference and then what we were doing we were pushing in the maxi and we were mx by 2 and we were calculating the minimum whether this mx by 2 is the minimum element so these two steps pushing in the maxi finding the minimum like updating the minimum you can say after this see when mx was five so now this while loop will not run and this code will not run so once we are we got a odd element on the top of the prior maxi then we come out of the while loop and then we find the minimum difference from the current difference what is the current difference and the top element was what five now five minus the minimum which was two so five minus two with the 3 so what is the current difference and this thing like whichever is minimum that we will return all right so this is the code i hope you understood the code and i hope you understood the approach also let me know in the comments if you have any doubt and if you found the video helpful please like it subscribe to my channel and i'll see in the next video | Minimize Deviation in Array | magnetic-force-between-two-balls | You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109` | If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible. | Array,Binary Search,Sorting | Medium | 2188 |
1,514 | hey everyone welcome back today we are going to solve problem number 1514 path with maximum probability first we'll see the exponential of the problem statement in the logic on the code now let's dive into the solution so in this problem we are given an undirected weighted graph of n nodes so here n is 3 so we have three nodes here 0 1 and 2 and we have given an edges list so the edges list represents the connection between two nodes so here we have zero one connection and one two are connected and 0 2 is also connected here right then we are given the weights for each and every connection so for zero one path we are given a probability of 0.5 path we are given a probability of 0.5 path we are given a probability of 0.5 similarly for one two path we are given point five and for 0 2 we are given point two and then we are given two variables start and end so the goal of the problem is to find the maximum probability that I can find between the two nodes 0 and 2. so first we need to start from 0 right since the start is 0 we need to start from 0 and then we need to check how I can reach 2 so here we have the direct connection between 0 and 2 right so the probability is 0.2 also I 2 right so the probability is 0.2 also I 2 right so the probability is 0.2 also I can reach 2 from 0 by traveling from 0 to 1 and one to two right this is also a possible path so when you have multiple paths we need to multiply those probabilities so here probability between 0 and 1 is 0.5 between 0 and 1 is 0.5 between 0 and 1 is 0.5 and the probability between 1 and 2 is 0.5 so here we are going to get 0.25 so 0.5 so here we are going to get 0.25 so 0.5 so here we are going to get 0.25 so we can reach the node 2 from 0 with two possible ways so we need to pick the possible way which gave me the maximum probability here so here 0.25 is the probability here so here 0.25 is the probability here so here 0.25 is the maximum probability right so this path from 0 to 1 and 1 to 2 is the maximum probability path so we need to return 0.25 as my answer for this particular 0.25 as my answer for this particular 0.25 as my answer for this particular input right so to solve this problem we are going to use breadth first search approach so now we will see how we are going to do this so here we are representing the graph in a dictionary so here the connection between 0 and 1 has been stored and that connection index will be stored with one so the connection index between 0 and 1 is 0th Index right so we are storing 0 here then there is a connection between 0 and 2 and their indexes 2 right and since this is the undirected graph we need to do it for the other nodes as well so here we have represented the connection between 1 and 0 and that connection index is 0 and so on right so then we are going to create a list of zeros and we are going to create this list of zeros based on the number of nodes so here we have three nodes so we have three zeros here right so the intuition behind this approach is that we are going to calculate the maximum probability for each and every node right by doing this we can easily access the maximum probability for the given end node right so then we are going to make the starting notes probability as 1 at the start so the starting node is 0 so we are going to make the zeroth node probability as 1. we are initializing it as one right then we will be having a queue in the Cube we will be appending the starting node at the start so here we have 0 now we need to pop the first enter element in my queue so here we have only 0 so we pop zero so current node will be 0 right now we are going to analyze the neighbors of 0. so first we pick the first neighbor in my dictionary so the first neighbor of 0 is 1 the neighbor is 1 and that connection indexes 0 I will make this as I so now using this index value 0 we have to pick the connections probability score so the probability score between 0 and 1 is 0.5 right 0 1 is 0.5 so we and 1 is 0.5 right 0 1 is 0.5 so we and 1 is 0.5 right 0 1 is 0.5 so we pick that probability score and now we need to multiply this with the current notes probability score so the current nodes probability score is 1 current node is 0 so the zeroth node probability score is one so this will be 0.5 now we score is one so this will be 0.5 now we score is one so this will be 0.5 now we need to compare this probability score with the neighbors probability score so the neighbors probability score is 0 since 0.5 is greater than 0 we need to since 0.5 is greater than 0 we need to since 0.5 is greater than 0 we need to assign this point Phi to the neighbors probability score so the neighbor is 1 so at the first index I will make this as 0.5 so this is the maximum problem as 0.5 so this is the maximum problem as 0.5 so this is the maximum problem ability for Node 1 so far after updating the neighbor we need to append one to the queue then we pick the next neighbor of 0 that is 2 and their index is 2. so the index value of the connection of 0 and 2 is 2 right so now we need to take the probability score of this connection that is 0.2 and we need to multiply with that is 0.2 and we need to multiply with that is 0.2 and we need to multiply with the current notes probability score which is 1 it is going to be 0.2 only which is 1 it is going to be 0.2 only which is 1 it is going to be 0.2 only then we need to compare the score with the neighbors probability score which is 0 neighbor is 2 and in the second index that is 0 so here Point 2 is greater than 0 so we need to update the neighbors probability score with 0.2 right so in the second score with 0.2 right so in the second score with 0.2 right so in the second index it becomes 0.2 after updating we index it becomes 0.2 after updating we index it becomes 0.2 after updating we need to append 2 to the queue so now we are done with all the neighbors of 0 then we need to pick the next node from the queue that is 1 right so the first neighbor of 1 is 0 right so the neighbor is 0 and that index is 0. so now we need to take the probability score of the connection that is 0.5 and we need to multiply with the is 0.5 and we need to multiply with the is 0.5 and we need to multiply with the current nodes probability score that is 1 so we need to take the probability score of 1 which is 0.5 here we are score of 1 which is 0.5 here we are score of 1 which is 0.5 here we are going to get 0.25 and then we need to going to get 0.25 and then we need to going to get 0.25 and then we need to compare this with the neighbors probability score which is nothing but 1. so here 0.25 is not greater than 1 so 1. so here 0.25 is not greater than 1 so 1. so here 0.25 is not greater than 1 so we don't have to append 0 in the queue as well as we don't have to update 0 in the probabilities course right then we pick the next neighbor of 1 that is 2 and their connections indexes one so we need to take the probability score for the current connection that is 0.5 for the current connection that is 0.5 for the current connection that is 0.5 first index connections probability score is 0.5 right then we need to take score is 0.5 right then we need to take score is 0.5 right then we need to take the probability score of the current node that is 0.5 right we need to node that is 0.5 right we need to node that is 0.5 right we need to multiply with that one then we are going to get 0.25 right then we need to get 0.25 right then we need to get 0.25 right then we need to compare this with the neighbors probability score that is 0.2 so probability score that is 0.2 so probability score that is 0.2 so neighbor is 2 so the second index probability score is 0.2 so since 0.25 probability score is 0.2 so since 0.25 probability score is 0.2 so since 0.25 is greater than 0.2 we need to update is greater than 0.2 we need to update is greater than 0.2 we need to update this value in the neighbor's probability score right so here in the neighbors probability score it becomes 0.25 then probability score it becomes 0.25 then probability score it becomes 0.25 then we need to append 2 again in the queue so we just have to keep on doing this until my queue is empty here the probabilities course is not going to change so we need to return the probability score that exist in my end node 2 so here the answer will be 0.25 that's 2 so here the answer will be 0.25 that's 2 so here the answer will be 0.25 that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we are initializing the graph as my list dictionary and I will be appending the starting node in my queue then I will be writing a for Loop where I will be representing the connections in the dictionary right with that connection indices then we are creating the list of zeros for the length of n where we will store the probabilities course and we are initializing the starting notes probability score as 1 at the start right then we will be writing a while loop we will run the while loop until the queue is empty so initially we will pop the first entered element in the queue that will be the current node then we will analyze all the neighbors of the current node using the graph dictionary right then we will multiply the current node's probability score and the current connections probability score then we will compare that value with the neighbors probability score if the calculated value is greater we need to update our neighbors probability score right after that I will append the enable to the queue then finally we need to return the maximum probability score of the end node in the probability list right that's all the code is now we will run the code so the time complexity will be order of n into e so where n is the number of nodes and E is the number of edges right and space complexity will be n plus e thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys | Path with Maximum Probability | minimum-value-to-get-positive-step-by-step-sum | You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.
Given two nodes `start` and `end`, find the path with the maximum probability of success to go from `start` to `end` and return its success probability.
If there is no path from `start` to `end`, **return 0**. Your answer will be accepted if it differs from the correct answer by at most **1e-5**.
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.2\], start = 0, end = 2
**Output:** 0.25000
**Explanation:** There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 \* 0.5 = 0.25.
**Example 2:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.3\], start = 0, end = 2
**Output:** 0.30000
**Example 3:**
**Input:** n = 3, edges = \[\[0,1\]\], succProb = \[0.5\], start = 0, end = 2
**Output:** 0.00000
**Explanation:** There is no path between 0 and 2.
**Constraints:**
* `2 <= n <= 10^4`
* `0 <= start, end < n`
* `start != end`
* `0 <= a, b < n`
* `a != b`
* `0 <= succProb.length == edges.length <= 2*10^4`
* `0 <= succProb[i] <= 1`
* There is at most one edge between every two nodes. | Find the minimum prefix sum. | Array,Prefix Sum | Easy | null |
1,092 | all right let's talk about shortest common super sequence so you are using the idea for longest comma sequence and i'm not going to just explain what's longest common sequence because you can just go on my video to check it check out the longest comment sequence video so it's built build a table list your table and then you and you're starting from the uh right hand corner to the top left corner so i'm going to say explain how it actually works so here's measuring so if i have to move right i have to compute my charge charts understand if they are not if they are nothing i have to compare which value is greater so i move so if i move up i need to store the value of rule if i move left i need to store the value of column so a and a c and b right c and b they are not equal so i check one or two way one two is greater than one smaller right so i move up before i move up i need to store the value of right c and b okay two so i start value a b and b are the same so when we build the table we actually add the diagonal value plus one right so we have to move diagonal diagonally and then and it doesn't matter uh which value you add because p and b are the same so just at b okay let's check top and left okay actually they are actually saying a and a are the same so i have to go diagonal right it was actually lightly right so a now uh you reach the end of the rule but the colon is there i mean there's still one over here because you start from zero right so just add a column because you move column to the left so c a b a c okay the string looks perfect but when you build it and we go the backward to the end to the first at beginning you are adding the string reversely so you have to reverse the string later on so i'm going to um write my idea on it so there's my dp and then here's how the longest common sequence build and then i have a dp right so i'm going to uh move through it so my row is my string one column is a string two right so this is my index right so that will be your indices right now i'm going to say wow i greater than zero and j greater than zero okay what should i do i should actually check the character right charge all the sound now if string won the chart at i minus 1 is equal to string 2 the chord at j minus 1 there's a reason why i use i minus 1 and j minus 1 because i represent the length of the string and you represent the length of the string two right and you use the minus one to get your last character last charge so they are the same so i can just add either one of them right so string one the chart a minus one i minus one so i can either add either one of them right b or b right because i have to move to diagonal so when i move the diagonal i have to subtract the row by one and column by one to get to this position right so i minus and j minus now if they are not the same if they are not saying i have to check the value which one is greater right top or left right so if dpi minus one and j i'm gonna say dpi j minus one okay i minus one represents top j minus one represents left right so i can say greater so if this is greater then i would say top greater than left okay if this is happen this is happening and i move the row up so i look at the chart on the row right and i know my rule value is string one so string on dot chart at i minus one and decrement i minus one by one and exactly the same thing for the j minus one right so append string two dot chart at j minus okay so when we add this position right we still have one character left so you have to keep adding the remaining but in this case i becomes your but j is not right but we can also have another situation i is not 0 and j is right so just keep appending stream 1. at i minus one and i minus same idea for the j minus one okay so i just said that when you're adding the string back reversely reverse right so you just have to reverse the string and then just two stream on your stream builder and that will be your answer and let's see all right i have a typo okay i don't even have a stream builder okay stream builder so this is how you ask for making mistake and chart line 15 chart and this is char okay i'm making a lot of mistake char all right a little bit a speed up and app e and d oh yeah what else no all right congrats oh my god cool so what happened i should not see c j minus two okay j minus one okay let's try again okay oh my god okay so the time and space okay for the space is all of m time and depending on your string right m time and the space on your db so out of m time and i'm going to write down all of n times n now for the time it's all of m time n because you are actually traversing the traversing table right from here to here right so it's n time and the worst case on m time n right so all of n time and that will be that would be your worst case and the solution is much it and sorry for typo and let's keep rocking | Shortest Common Supersequence | maximum-difference-between-node-and-ancestor | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`.
**Example 1:**
**Input:** str1 = "abac ", str2 = "cab "
**Output:** "cabac "
**Explanation:**
str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ".
str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ".
The answer provided is the shortest such string that satisfies these properties.
**Example 2:**
**Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa "
**Output:** "aaaaaaaa "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of lowercase English letters. | For each subtree, find the minimum value and maximum value of its descendants. | Tree,Depth-First Search,Binary Tree | Medium | null |
334 | foreign level question okay let's discuss the question briefly here given an integration array nums written true if there exists a triple indices ijk such that I use result J and less than K and the next condition also is nums of I should be less than um J should be less than um uh we should just return false if there is no such condition exist so I will discuss the example using whiteboard and we'll discuss the algorithm over there only okay these examples given in a question one two three four five and these three examples so here there existed triplet which follows those two conditions I should be less than J and J should be less than K and nums of IE should be less than observed J and nums of J should place the numbers of K therefore uh the triplets here are one two three is one triplet and two three four is another triplet and three four five is also another triplet therefore there exists a triplet in this example therefore we written true and will come for next example two one five zero four six here uh two one five doesn't make a triplet one five zero doesn't make a triplet so we'll check 504 doesn't make a triplet now here zero four six uh which make a triplet following those two conditions therefore we should return true and we come for next example five four three two one here five four three doesn't make a triplet four three two uh doesn't make it replace three two one node doesn't make it repeat therefore we just written false here okay we'll discuss the algorithm uh taking the second example here this is example two one five zero four six is a given num's array is a given nums array first here we assign two variables Max one and Max 2 1 and Max 2 with the max value of our integer's max value should be assigned to these two variables Max 1 and Max 2. now we will check if the given is the given number in the array that is uh now numbers of 0 should be okay now we'll iterate the whole array and we'll check these two conditions okay first condition is if nums of I is less than or equal to Max 1 then we should update the max 1 with the value of and the value of terms of I the value of I'm sorry like that so uh we'll iterate this array so now nums of I equal to 2 it is obviously less than or equal to Max in major value so we'll update Max 1 with value 2. okay now we'll go for next iteration now Norms of I equal to this I first for first iteration now we'll go for one now numbers of one uh numbers of I equal to one uh it's less than maximum value max value is now with 2 now we'll uh the condition is true therefore we will update Max one with one second we will erase this okay now Max 1 is Max 1 contains now with value 1. okay now we'll go for next iteration now nums I is equal to 5 uh this condition is false for the uh this condition doesn't hold now we'll go for next condition uh this condition may be true for this iteration because uh Max 2 contains the maximum value of integer till now uh we'll check for Phi yes its uh 5 is less than maximum value therefore we just update nums of uh now we update maximum value to with 5 for next iteration nums of I is equal to 0 uh the first condition here itself holds true therefore maximum 1 Max 1 is now updated with value 0 now for next iteration nums of I is equal to 4 first condition is false for here next condition is true holds true three four five is updated Max 2 is operated with 4 now for next iteration numbers of I equal to 6 here the first condition also falls for the uh for the value 6 and second condition also doesn't hold therefore will come for else uh L statement and just we need to return true here we've done this because the maximum value max value Max 1 in the given algorithm holds the least value in the given integer array and Max 2 holds the least second the value in the given integer array and if there exists another value which is greater than Max 1 and Max 2 and if it also satisfies the condition ild less than JL less than K therefore then will come for else statement and we just return true here if it doesn't hold if there is no such integer which is greater than 0 4 okay let's uh let's Analyze This example okay if this is the case uh this is the given integer array then it doesn't get into the else statement so we'll just return false here for the given Give an example the answer would be false so let's analyze the code now okay first we declared a value K Boolean value gave it false and nums uh length with the n and as uh as we discussed in the algorithm Max 1 will be equal to maximum value of integers and the max 2 is uh also equal to maximum value of integers we'll just iterating from 0 to n here if we encounter any value with the uh with less than maximum one we just update maximum one if the condition doesn't holds will just come for LC flow L shift condition if there exists a number which is greater than Max 1 and Max 2 also then we will come for else statement and we just return the not value of K that is here first we uh we declared the K with value false now we'll return value true if no such conditions are evaluated then we just come out of the loop and we return the value false which is previously declared for k please do consider like share and subscribe | Increasing Triplet Subsequence | increasing-triplet-subsequence | Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity? | null | Array,Greedy | Medium | 300,2122,2280 |
406 | Hello hello friends today speech that sprang its problem number forces construction institute subscribe to hai ya given at least in wich every question side issue on number panel veer ahead of the acquisition se say no liquid the subscribe like subscribe and this channel subscribe Must subscribe and subscirbe ki 24 karat every post nfo account Dr to do subscribe to the seven work interview black 06 the effigy stand example day for this like 0.2 200 subscribe to this like 0.2 200 subscribe to this like 0.2 200 subscribe to one whatsapp text this report Seervi Effect 6 Subscribe To Narrated Till We Like This How I Can Make Face Pradesh Hai Android Free Welcome Pure And You Are Interested In And Not On That Can Five Come A Gaspee Ko Only You Comment Thursday Third This Number One Subscribe Button Ki Rupee British Nav Das Prashan Karta Hoon Ka Record Yaar Tu Questions Enrique 125 In This Place From All Subscribe To Andar Sahu Village State Repression And Induction Only Andhra Loot And Subscribe Now School Subscribe The Two And Hai What Is This Tractors Definitely subscribe register subscribe | Queue Reconstruction by Height | queue-reconstruction-by-height | You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`.
Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue).
**Example 1:**
**Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\]
**Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\]
**Explanation:**
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue.
**Example 2:**
**Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\]
**Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\]
**Constraints:**
* `1 <= people.length <= 2000`
* `0 <= hi <= 106`
* `0 <= ki < people.length`
* It is guaranteed that the queue can be reconstructed. | What can you say about the position of the shortest person?
If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person? | Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting | Medium | 315 |
1,629 | Ko Same Everyone Welcome Back To Recording In This Video Badminton Kabaddi Question Number One Offbeat Ko Bhi Contest 21 Ki Dashi Problems Have Already Been Uploaded You Can Find A Solution To All Problems And Provide Drinking Description Oil Gauge Cloud Channel And Find These Videos Nor Its Processes in Fact to Where is Problem Chal Problem Test Sohanlal Decide Keypad and State Where Test Surprised Sequence of Increase One at a Time When a String Key Press Top Length 0 Key Press Aaye Voice BJP President Sequence and Short List Release Time with This Time is What Is the time filed that list buddhi are Ashwin text-20's list buddhi are Ashwin text-20's list buddhi are Ashwin text-20's WordPressed every time she rot and every subsequent's WordPressed exact time decree's voter's list were return trouble's press daddy longest duration of medical research president lexicographical this last key office's press Assigned Activities Were Given A Sequence Of Ideas Playlist Sunao Tak Events That At The Time The Rosary Is Time 98100 Skin Haq's Bt Cotton 98100 Show Dresses Tuition For Which It Was Pressed Software's Laddu Safed Reliving This Truth And Value's Half Hour Hospital Contrary to the administration's claims that I am S10 I am Suresh SM This is VAS of zero and decoration Interior decoration Interview CEO of which bank The financial year's Nobel Prize from is equal to one is a small town Astro science that and half Inch plus a solid calculate duration in different key the integration is equal to this Vivo 5 - v5 - one sunidhi chauhan if this Vivo 5 - v5 - one sunidhi chauhan if this Vivo 5 - v5 - one sunidhi chauhan if impression is equal to kar di ko maximum depression till now his team ki main mendis k switch you consider the answers to maximum of answers Comedy Current Character Figure Skating Electric Graphically Letter On I Just This Green Team The Answer Is Equal To f5 That Also In This Case Ko Too Take Map To Make It Is Equal To Team Vestige Middle Nau And T20 230 Creativity Nau And Finally They Can Return the answer This is in terms of peace I am in this stuffing solution and in terms of time it is 11:00 Time So is 11:00 Time So is 11:00 Time So for Deposit Role Singh Guddu English 4th Entries Offspring I am so widowed or separated and fixed Deposit sediments plus 2 inches Questions Notification Plain distance from example sophisticated contest video please subscribe my channel thank you | Slowest Key | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released.
The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`.
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**.
_Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._
**Example 1:**
**Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd "
**Output:** "c "
**Explanation:** The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
**Example 2:**
**Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda "
**Output:** "a "
**Explanation:** The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
**Constraints:**
* `releaseTimes.length == n`
* `keysPressed.length == n`
* `2 <= n <= 1000`
* `1 <= releaseTimes[i] <= 109`
* `releaseTimes[i] < releaseTimes[i+1]`
* `keysPressed` contains only lowercase English letters. | We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly. | String,Greedy,Binary Indexed Tree,Segment Tree | Hard | null |
139 | hello welcome back this is logic coding today we're going to look at two world break problem the first is medium the second is a hard so the first medium we are given a string and a dictionary of string world dict and we want to return true if s can be segmented into space separated sequence of one or more dictionary words so what does this mean is if we have a string and we have some world dictionary we return true if we can segment the string into words and note that the same word in the dictionary can be reused multiple times in the segmentation so if we have a lead code and we can segment into lithium code so return true if we have the code lead and since lead is again in this it can be used twice and second example if we have apple pen and apple of course it will return true as well since we can segment into words in this word words dictionary the last example is cat scent or cats dog so if we do cats we would have uh and dog so we find out no matter where we do the segmentation we cannot segment the whole string into words so how are we going to approach this so we know the input we know the output and how are we going to do this so if we found um for this one i think we can definitely do a dynamic programming word dp means true or false which means up to index i can wait or up to length i can we do segmentation so um how can we update this dp then so dpi will equal to true if we can find dpj which is true like dpj which is true and the substring from j to i like inclusive um is in word dict so under this part we see that we need to have um have operation to judge whether a substring is in this row dict so we better use a unordered set which will support constant operation for to check whether it does consist of the word and we will just return dpn at the end so in this algorithm the time complexity will just be o and square because we will have two nested for loop and the space complexity will be o n within that let's try to code it up let's first get the string.length and get the string.length and get the string.length and we know that if actually we don't need to consider n equal to 0 for now and then i will associate a boolean vector for my dp array whose size will be n plus 1 and the beginning will be false but dp 0 which means length when there is no word will equal to 2 and at the end i'll just return to dpn so how can we update dpi i outer loop will be for into i equals to 1 i grade equal to n i plus the inner loop will be four into j equals to zero j is smaller than i j plus if we find a dpj which equals to two and um s dot substring came from this j and the length will be i minus j because when j equal to zero i can go up to n so the length will be n and i have okay so first let me convert my vertice to a set to an unordered set such that this operation will be constant time and this substring is in my set then i can say okay my dpi will equal to 2 and i just break from this once my dpi equal to true i'll just do break let me submit it cool seems to be working and that's pretty much about it this is like a classical dp so for dp problem we have three ways we have prefix in which case this is a prefix we the i depend on whatever goes before that we have a surface which i depend on i plus 1 i plus two come after that and we have substring is for dealing with like palindrome or um and palindrome uh basically but i will be making videos regarding to all those questions in the near future so that's pretty much about it whenever we met such a dp problem um the first thing is to reduce it to something that we are familiar with write out the pseudo code analysis the time and space complexity and then do the implementation that's it for today thanks you guys for watching i'll see you next time | Word Break | word-break | Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**. | null | Hash Table,String,Dynamic Programming,Trie,Memoization | Medium | 140 |
201 | hi everyone welcome to my channel let's talk about today's lead code daily challenge um today's problem is about beat wise operations yeah and it's about and the problem is like uh you are given two integers from left to right you should and all the numbers in that range and return the answer for example if uh the first one is five to 7 so five six and 7even let's take a look at that 5 six and seven so the first thing that you should think about when you are given a problem that is about bitwise operations uh especially and or and X or is to think about the answer in terms of bits because the answer for each bit is not related is not depending on any of the other bits so for example for this bit you can just calculate the answer based on the bits in this column for the other for this bit uh you can just you take a look at the numbers here and so on so for example in this example yeah so here um if we are if we want to know the answer for this column for this bit which is 2 to the zero this is uh beat zero basically the answer is zero because we have one zero in this range remember this is the key here again we have one zero in this range it a zero here we don't have any zeros so the answer is one okay so if we go back and look at the range of the numbers first the range is very big so it's the maximum integer it's 2 to the 31 minus 1 and so you cannot do a for Loop what you can do is if you have seen binary representation of the numbers you may remember that there is a repetition pattern for each bit for example if you look at this bit it's one0 1 0 and so on if you look at the first like beat one this is beat zero if you look at beat one it's 1 one0 0 one 0 so the period length here is two so the first one is two to the zero the length is one 2 to the one the length is two 2 to the two the length should be four let's take a look so here we have four sorry one and then 0 Z and zero you see the length is four and 2 to the three the length is eight um okay so that means if for example if the number of the if the total numbers that you have from left to right is greater than eight sorry is greater than eight so for example if you have 10 numbers so uh I'm going to call it total count and that would be right minus left plus one right this is the total count so if the total count is greater than eight what does that mean that means in this range you from left to right you will definitely have at least one zero for beat three so for beat uh three yeah so here for example it goes from here all the way to here and you will have one zero here these two are zero and it doesn't matter how you move this like where you pick your 10 numbers if you have 10 consecutive numbers there is at least one zero for bit three this is the key all right so if this is the case that bit is definitely zero but otherwise if total count is less than this period length let's say for example it is four now we know four is less than eight so now it depends where is that for a starting like where is the left and where's the right so if it's here from here to here like this one and this one so you see that uh here we have one zero but if that one is from for example here to here we see that all of them are one so how do you find out so in order to check this you just need to check L and R why so if you're checking beat I uh beat I you just need to check if left has that beat and if right has you know that beat is set for L and R uh why because if these two are one like if this is one and this is one definitely anything in between is one as well because it's not possible that you have one and then you have a bunch of zeros and then you again have a bunch of ones it's not possible why because of this condition we have already checked that from left to right we have less than or equal uh numbers uh of two to the I and 2 to the I is the length of this period so for example from left to write there are if there are less than or equal to eight numbers it is not possible to have a few ones and then a few zeros and then a few ones because this here this itself these Zer itself is two to the I while we know we have already checked that from left to right uh it's less than or equal to the I so it's not possible to have two to the ey number of zeros in between these this left and this right so you just need to check this beat and this beat from left and from right okay so let's go and see how we can write the code so I need some variables to keep count of the total numbers so in total count is going to be right minus left + count is going to be right minus left + count is going to be right minus left + one so here you should be careful not to get overflow because if right is 2 to 31 then this is going to be 2 to the 31 plus uh sorry 2^ 31 minus 1 + 1 and if plus uh sorry 2^ 31 minus 1 + 1 and if plus uh sorry 2^ 31 minus 1 + 1 and if left is zero so in order to prevent that we will use unsigned integer and here we will cast right uh to unsigned integers so we will not have uh overflow then we need some variable for the result and then we just need to do a for Loop so B should go all the way up to 30 because 2 to 31 minus one that means all of the bits from Bit Zero to bit 30 are set that number is 2 to 31 minus 1 so we go all the way from 0 to 30 for bits and then we have in uh period length which I'm going to call period length and it's going to be two to the bit that is it and then here we check if total count is greater than period length Okay that is that means that we definitely have a zero for this bit in this period so we continue and here we just check the left and right so if has bit B and left and has bit B and right if both of them have this bit I'm going to add that bit to result so result is going to be or with 2 to the B and I need to add this function which is very simple I just need to check and see if that number has this speit so return to the bit and we will end that bit with number so if this the answer is greater than zero that means number has that bit and we will return true as a result and then here we just return result so this is our code and let's run and here we have three greens submit so that's it uh so as a followup question think what will happen and how our solution will change if we are going to do or instead of and think about it thank you | Bitwise AND of Numbers Range | bitwise-and-of-numbers-range | Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1` | null | Bit Manipulation | Medium | null |
68 | okay let's code 68 text justification welcome to the shitty tasks so straightforward problem very straightforward it has a rating of two to one the likes and the dislikes and the straightforwardness of this is this a text a sequence of words a width and we want to get something like this so the current with lines as many as there will be required no word can be separated between the lines so a word should belong to a line that should be in order then if a word takes less than the width space should be inserted and god knows how this description doesn't really make much sense and then the last line should be like padded to the left and everything else come afterwards okay so i have a feeling that this video is going to be long and unnecessary but i will try to type as fast as i can okay so initially this is going to look something like this so i would get some sort of let's say lines first would be a good idea to separate them by lines so let's say uh separate and i'll give this words end with next width okay so after this supposedly those are the lines that we want so let's say the resulting is also vector so this will be the result all right so until the last line note included -1 -1 -1 we will do something like pushback let's say just okay justify lines i alright then it is going to look something like this so um push back justify last length that back and this will be the result so yeah the main function pretty straightforward now for the implementation of these tedious functions so first to separate so the separate would be vector of vectors of string which would be separate as to the vector of string reference words and okay so how is this going to go it would be a good idea to typed this but okay so how is this going to go so i would create something like let's say vector string current short and then let's say current w so this is going to be something like this so i can kind of like i can even iterate over them so words so if okay this is going to be really difficult so the current size plus oh jesus so there should be at least one space between the words so each word kind of comes with its own space so the currents so the size of the current world if added to the amount of spaces that are already necessary between the word which means the amount of words that we already have for this line is less or equal this is going to be wrong i'm sure then i hit this anyway so not like this but current what we already have plus this plus the spaces lesser equal than m then we can add it as increase the width as the size and continue okay otherwise our result will be added to the current which would be current so the current will be cleared and this will start a new chain which would be pushback line which is s and the current weight would be s size terrible okay so i have no idea whether this even works or will work but we'll kind of have to find out on the way so now for justifying a line okay a string justify a normal line which is going to receive a vector of strings so this at least we know that is in the domain of the width so this was not too necessary but well it makes the code more readable i hope okay so the first thing is calculating the amount of padding that we want to spread so it's going to be something like um whatever we have left between the words should be split so it should be the number of words plus okay i will need a tiny sum function let's call it sum it's really not that relevant but i want to keep the code as separated as possible string that's words zero line words classical size return okay so i would say the characters of the words are going to be the sum words all right so uh left this means left over not like left b m minus characters okay so the padding the average padding is going to be oh jesus am i right to assume that all the numbers are going to be equal okay so the average padding is going to be the minimum value is going to be whatever is left divided on the number of words minus one and this is so accident prone okay i'll fix this later the case of having only one word honestly i can like do this quickly right now so if i have only one word just return it or start front okay now i have to pad worst at front plus no not like this okay some left okay so i will check it exactly right here so if i have only one word i want to return that word i'll go for front plus how many characters we have left for spaces which is this many no this was stupid way of writing so string again i don't know which one is which so let's hope this is the correct constructor to return this all right so if we have more words then this is going to be the minimum padding let's say the extra padding would be whatever oh jesus okay so whatever we have left which is from left minus where's that size minus one multiplied by parts so those are extra spaces which are going to be split from left to right so the result is going to look something like this so if i go over the words this is how it's going to look so first of all it's going to be the word okay so then it's going to be oh jesus this is so terrible really this is so terrible okay and then so if i have extras left i will add push back one space and decrease the extra i would say it's greater than zero it will work but i like it this way okay then we add pad the number of spaces so result that pushback no plus equal as to the string again hoping this is the correct signature padding and character all right then okay i think this should be it for this line oh my god okay so now the last line what was the okay so the last line only one space that's good so justify last i think no i have a vector strings words and the m again all right so again our charts would be the sum okay the leftover would be pretty much the same jars okay so in this case since we're guaranteed that it won't get over it would be i'll start with the result all right so i can go over the words again words all right so result plus equal the word result pushback space and minus whatever is left and then at the end return left plus as the string no result plus a string left and the number of spaces okay what are the chances of this being one-shotted okay compiler doesn't mean anything with the result okay perhaps it was one word okay i have no idea what this even means let's go ah and it's the max with same goes for this one okay wrong answer good very good so this is the input this is my out this what was expected so the first one okay example of text and third one died so okay this means that basically nothing works at all which is good okay so neither the splitting works nor the justification works okay first i'm just curious i think the justified last works that's kind of ironic but anyway so the justify doesn't work because of the number of spaces i assume it was too many so when they go wrong so this is the whatever is left to fill with spaces one word case taken with an if this is the average padding for each one of them whatever is left this is correct the extras are whatever is left minus this which is also correct hopefully i should have actually moved to or no okay this task is so not cool okay so this is the average padding for each word okay yeah this makes sense the last word shouldn't be averagely padded like this all right nothing will go wrong if i just replace this with the loop anyway everything is going wrong by default so nothing can get worse at least okay and then result plus and this hopefully should have the correct calculations where's that back okay so what about the splitting why didn't this one work i think this one didn't work because i had to check so if my current is not empty then i need to add one more so a result that pushback current okay one more time okay yeah w won't work anymore so words i okay this looks no this looks worse this is definitely worse so what happened here example for some reason the second word of both of them got swallowed ah fair enough plus okay that's weird oh if this type of a shitty test case passed then the probability that it would pass is let's say 95 ah jesus link there ask not what your country can do for you ask what you can do for your country if i talk about this i might get banned on youtube anyway so length there it is possible that i'm having like um zeros like a length can't it be zero i'm just okay i will just try something so just in the beginning of the test case so it will be i don't even need to assign it to something so string ss 0 space if this gives a runtime error at least we know where the problem is no i guess this isn't the problem okay yeah but i think this can be a problem i don't think i can even give a minus one the first parameter should be size t uh yeah that's cool let's go so whenever the problem is somewhere there is string being constructed with the negative value okay so where do i have string construction here this can be zero at most and i have string construction here this can be zero but not less and i have string construction here which again can be less okay so 16 ask not so cases 3 6 10. 14 so no this can't be only one line so this first three are on the first line then this i need to somehow print so that i can let's judge from the input so let's say that i print here so where's i so the catalyst know what which word this died so submit like give me my output okay so ask not your country do for okay this is even wrong so ask not they were supposed to be what here oh no i think the vote was in the justified last okay we'll leave that there so it came until you can which is somewhere here what you can so ask not country well ask not your country can is left over so um yeah so two four i know this is kind of just terribly wrong okay so it died after what you can somewhere here so it processed this and then it died here okay i will go for or stop back as well this gives more input i'm curious the last line or something else going wrong okay so it seems to be so asking what you can do for you ask what you can do yes a four-year country is this going to yes a four-year country is this going to yes a four-year country is this going to be in one line so three space for eight nine and then one two three four five six seven so it's like exactly 16 and it died there's an interesting test case so justify last supposes that this was supposed to be like something like zero huh that's interesting oh just for the justified last because the output shows that justify last was test case okay yeah this absolutely didn't make any sense the current empty repeats so okay it is possible that it died before this no i don't think it's possible the last thing we should have to do is to output the results so i'll press or start back i'm not sure whether they will allow this much output but what can i do about it okay so now so this like makes like no sense for the viewer so i'll separate it with two end lines and again challenge the space for that code okay so the first one ask note what your country can good i don't know what this is what your country can i'll just delete all the other sea outs here i think i can keep the last one okay ask note what your country can do for you ask and it seems correct what you can do for your country what the hell okay so if we got the last line this probably means that the justify last has been called with something that it wasn't supposed to be called which means that the output from here is gd that's interesting since everything got called the way it was supposed to be cold looks like here no i think i can kind of remove the justified last we don't want to see this yet i mean it gives the correct output and then it dies it's gonna but what you do for you ask what you can do good okay so the justifiable ah interesting so this the printed result was correct when i added this so the left kind of die so let's go over it again so some of the words m minus chars means that many extra spaces should be added result whatever and okay add the word add the space decrease ah okay yeah this can make sense to fit like a perfect fit all right i'm not going to give this too much thought all i'm going to do is if left is less than zero i'll do it this way so left equals std max left and zero and they should nail it and i have no idea why this was like this but oh my god this was still wrong oh yeah makes sense i think i can just okay remove this shitty line okay i know what i'm going to do i will do a result that pop back and remove the last space and increase the left this should fix everything okay great run times zero millisecond faster than one hundred percent of c plus bus online submissions for test justification i'm not sure where i should feel like good about this but yeah anyway we are done | Text Justification | text-justification | Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth` | null | Array,String,Simulation | Hard | 1714,2260 |
250 | lead code 250 account unit value subtrees so let's see what this question is the root give a binary tree and then return the number of uni values of trees so here for example if we have five here this node and this node their post leave their uni value the leaf is always unique value some trees here the five is also but here one is not equal to the leaf node so here is one sub tree here is two symmetry but here no so we have here is two and in this right uh root dot right we have this one is the leaf node so it's one subtree and here uh we have same value so it's another sub tree so total we have one two three and four so that's this example and if the root is uh no equal zero example three is the same just to have more five so let's see the java code we will use uh two rules first leaf node is always unimaginable subtree the second is if root node is same as leaf node it is also a universal sub tree which in this case five right the five dot and right is five so it's the same so it's the sub tree uh we use the fs recursion to solve this problem so here is the global value rest global variable rest and here we do the use the here for function dfs root and we return rest is the global result then we use the helper function private boolean dfs trinomial root here we use boolean because we need to see if the naught is unit value or not so if the root is equal to null which was nothing we return true which is like this case example 2 then if we go through like a post order binary tree we need to check the leaf node first like post order binary tree the leaf first left then next right then we check the parents then we go to the right side to check the leaf and the parents so here if um dfs root dot left exists we check if the it is a leaf node or not the same as the right who doesn't write we keep the recursion here and if the when the base case rules equals no we return true so if l and r are true so if a and r both true so in this case we have uh left and the right are both true or we have left is not true oh we have like five left is no five right has no we return true here so we have one counted in here rest plus um and the f left and right equals two so here left and right if they are both null so they are both true same here five left five right we plus so here we have result 2 counted and now we go here if left and the right oppose unit value 3 so here um we see if root dot right is not nor so for here example routine five dot right is not equals to no which isn't true and put 5 is not equals to 7 5 is not equal to 7 with 10 fourths we need 5 equals to 5 so this can be counted as the unit value sub 3 and same as the left uh root left is not north of true and the root dot menu is five and not equals to seven so it's false uh if it's same we can't if it's not same we just don't count then we return to here and the f left in the right or not in this if statement we return false then after all these hair perfunction we return the dfs route then in the dfs route we have content of rest then we return rest we will get the answer and here uh you can see if i change the node to here six so it can be also counted so six is one sub tree five is another subtree and the five is the muscle three and the five equals five is another trick so it's also five so it's also four so four here and the time complexity will be on it will be passed through all the node here uh if the space complexity is also all in since it will need to pass all the in the heap and gave the space for that so it will be on you | 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 |
1,254 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem number of closed Islands we're given a 2d grid consisting of zeros and ones I'll magnify the example a little bit over here it's a little bit opposite this time because zeros actually are land and the ones are water an island in this case is defined as some piece of land that is connected in four directions so zeros can be connected like vertically or horizontally like this they can't be connected diagonally so these two are not the same island this is like its own separate Island and this is its own separate Island now this island is kind of interesting because it's actually wrapped around some water over here but that still does count as an island like this stuff over here does count so among all of these I think I can count about four separate Islands but that's not what we care about among all of these islands we want to know how many of them are closed Islands a closed island is defined as being basically surrounded by water in every single Direction well wouldn't every island be surrounded by water well the ones that aren't are the ones that kind of border the edge of the grid here you can see that this guy over here I probably shouldn't have used Blue by the way because that looks like water but oh well this guy over here is not a closed Island yes there's water over here and water over here but there's no water here or here it's bordering the edge of the grid so this is not a closed Island same with this guy it's clearly bordering The Edge not a closed Island this one is a closed Island because on the left over here we can see water on the right there's water up top there's water and bottom there's water this is a closed Island and this one as well is a closed Island because every everywhere on the outside there is water and it technically is next to some water on the inside as well the important thing though is it's not bordering the edge of the grid so now we've made this problem pretty easy at least easy to understand but now what kind of algorithm can we use well pretty much any graph algorithm whether you want to use DFS or BFS it's up to you I'm going to stick with DFS but the idea is going to be the same regardless of which algorithm you choose for us to determine if this island or any of the other islands is a closed island or not we're going to run that first search on this island we could start at any position we could start here doesn't matter so let's just say we start here now we're running depth first search we're going to basically Go in all four directions recursively here and here we're going to keep going until we reach some base case that's what you do with recursion and in our case we're going to stop once we reach water so here if we went up we see there's water over here okay that's good we don't have to keep going in that direction we try to go left over here there's water we don't have to keep going there when we go down though this is a piece of land and when we go right this is also a piece of land on these two positions we're gonna recursively keep running depth first search so let's say we started at the bottom one now we're going to go left there's water we're gonna go right there's water we're gonna go up now here is the part where we don't want to get stuck in an infinite Loop if we go up then we're gonna go here then we're gonna go down then we're gonna go back up we don't want to get stuck in an infinite Loop so after we visit a position like this one Let's cross it out but in terms of code we'll mark it visited the way I'm gonna do it is with a hash set because I think that's the safest thing to do you could also actually overwrite the value in the grid you could probably change it to a one to represent water that would probably work in this problem you could also change it to a two to say it's land but it's been visited it doesn't really matter but it's possible we might not be allowed to update the input grid so I'm going to stick with the hash set so that we don't kind of make that risk but probably in a real interview it's worth clarifying with your interviewer now going back to this position we're going to go down we're gonna visit this we're gonna go left can't go there can't go down we're gonna go right and basically what's gonna happen is if you're familiar with DFS we're going to end up visiting everything and every time we try going out of bounds we're not going to be able to we're never gonna reach the perimeter of the grid and since we don't reach the perimeter that means this is going to be a closed Island and we'll know that after we visit every single position so we found one closed Island here if we run DFS on this guy maybe just starting at this point we're gonna try to go left that's water we're gonna try to go down that's more land we're gonna try to go right whoops that's out of bounds up is also out of bounds so as soon as we get there we probably don't even need to continue the DFS we will know immediately that this is not a closed Island we can do the same algorithm on this guy it's not a closed Island this one is a closed Island so we counted in total two close Islands that's what we're going to return just like in this example over here now the last thing is how do we run a DFS on all of the islands how do we even identify where islands are the easiest way is basically to go position by position with basically a nested for Loop anytime there's a one we don't need to run DFS so we're not going to run DFS on the ones we only care about the islands anytime we see a zero though we are going to run DFS so in this case we see that first zero let's run DFS on this position now we'd figure out that this is not a closed Island and we'd also end up visiting maybe these two positions in the process of doing that so we would also Mark those as visited that's going to be important because as we iterate through row by row we're not going to visit this here we would figure out that yes this is a closed Island and we'd end up visiting all of these in the process of doing that I'll mark those red just to kind of show you what I'm trying to point out here and next as we still go row by row we already visited this then we're gonna get here but we don't have to re-run DFS on this island we already to re-run DFS on this island we already to re-run DFS on this island we already know it's a closed Island and since we marked those visited we will know that we don't have to re-run DFS on this we don't have to re-run DFS on this we don't have to re-run DFS on this island using that kind of technique that will basically guarantee that we pretty much visit each position only like once or technically a couple maybe three or four times but still it is telling us that the overall time complexity is going to be the size of the grid which let's say is n rows and M columns so the overall time complexity is going to be n times M the space complexity is going to be the same because remember we do have our visit hash set I mean technically we could use the grid if we really wanted to it's up to you if you want to but I'm gonna assume that we can't modify the input grid so now let's code this up so the first thing I like to do with 2D grid problems is just get the dimensions of the grid because usually we need them multiple times so I'm going to get the number of rows which I can get by taking the length of the grid I'm going to get the number of columns by taking the length of the first row and I'm also going to declare our visit hash set since we know we're going to be needing that and then I'm going to first refresh to fix this leak code syntax highlighting and then I'm going to declare our DFS which I'm not going to fill out quite yet but we know the way we're going to use this is just by iterating over our entire grid so for R in range the number of rows that we got up above and for C and range of the number of columns that we got up above this is a position in our grid we want to run DFS on this position passing in the row and column we aren't going to pass in the visit hash set because we have our function find in the scope where it will be able to access this visit hash set but remember we only want to run DFS on positions that are land so basically the value at this position is going to be zero or we can say not this position or this value but remember also we don't want to run DFS on the same position twice so let's make sure that this has not been visited this is not in our visit hash set then we can run this DFS and we're going to use the result of that DFS to update our result remember our result is going to be the count of the closed Islands I usually just call it result and initialize it to zero but maybe a better name would be count or count of closed Islands it's up to you now one approach here would be to return true or false if we have a closed island or not and then here we could say if this returns true then let's go ahead and increment our result by one that's a completely valid way to do it but I slightly the easier way in my opinion would be just to if this is a closed Island return one if it's not a closed Island return zero that way we can do this we can just take the return value of the DFS and increment our result with that value well let me go ahead and add the equal sign that's what we can do if this returns one that means it was a closed Island in that case we would want to increment our result by one if it's not then we're going to increment it by zero AKA do nothing so it pretty much works out and after that we would just go ahead and return the result even if you don't know how to do DFS in a real interview I think you'd be able to get this far probably maybe you wouldn't have like the visit stuff but otherwise you'd probably know this much now let's try to actually fill in the DFS there's a couple of cases one case is where this is not a closed Island that would only happen if we went out of bounds so basically our row is less than zero or our column is less than zero they're too small the opposite case is where they're too big so our row is equal to the number of rows or our column is equal to the number of columns we don't need to check if it's even greater than that because it won't really be possible for us to go that far out of bounds we only really go out of bounds by one that's why I'm checking it this way now if any of these are true that means this is not a closed Island but we're not going to return false remember we're going to return zero this basically means false so I'll just add that comment but the other case is where this is a closed Island and that would pretty much only happen where the grid value at this position is equal to one that's the other Edge case because remember if this is zero if the value here is zero that means it's land that means we have to continue to run DFS on that piece of land well only if it's unvisited land remember so actually there is a second case here so either this is equal to water or this position has already been visited so we can check that by checking is this in our visit hash set if either of these are true we are going to return one AKA true this is a closed Island at least so far as we can tell this is a closed Island now if we ever find a zero or if we ever go out of bounds we'll pretty much know that this is not a closed Island knowing that I'm going to well first of all let's not forget we do have some parameters in this DFS the row and the column and also once we encounter a position once we get this far in our method we know that this is unvisited so let's go ahead and Mark it as visited so let's learn how to type here but this position is now visit before it was not but now it is and also we want to now run DFS on all four of the neighbors you can do that multiple ways the way I'm gonna do it is by just making a call to DFS four times so I'm going to say DFS on row plus one at the column position DFS at row minus one and the same column position a DFS at the same row but column plus one and lastly DFS at the same row column minus one now among all of these what do we care about let me ask you that if all of these return one what does that mean that means for sure this must be a closed Island but what if all of these return zero well that means this must not be a closed Island what if a couple of them return zero and a couple of them return one that means we were able to reach the edge of the grid if some of them return zero that means this can't possibly be a closed Island so basically if we ever return zero that means this is not a closed Island a really easy way to check that is actually just take the minimum of all four of these right because we just want to know was there a 0 or not so I'm literally just gonna go ahead and do exactly that get the minimum and then I'm gonna go ahead and just return that minimum so if any of these were zero we're gonna return zero if all of these were one then we're gonna return one that's exactly what we want and that's pretty much it so now let's run the code to make sure that it works and as you can see yes it does and it's pretty efficient I will quickly mention that we technically aren't immediately returning if we encounter a zero like we will actually make a DFS in all four directions but I think the overall time complexity is still the same so it's not a big deal if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free neatcode.io it has a ton of free neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon | Number of Closed Islands | deepest-leaves-sum | Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\]
**Output:** 2
**Explanation:**
Islands in gray are closed because they are completely surrounded by water (group of 1s).
**Example 2:**
**Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\]
**Output:** 1
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1,1\],
\[1,0,0,0,0,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,1,0,1,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,0,0,0,0,1\],
\[1,1,1,1,1,1,1\]\]
**Output:** 2
**Constraints:**
* `1 <= grid.length, grid[0].length <= 100`
* `0 <= grid[i][j] <=1` | Traverse the tree to find the max depth. Traverse the tree again to compute the sum required. | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | null |
122 | let's cover the second video of the best time to buy and sell stock series on Leo today if you haven't seen the first video please go take a look at Leo question 121 video different from that question this time you can trade as many times as you want to with at most one share of stock and your goal is still to maximize The Profit at the end the constraints are similar the lens of the price is within 3 * 10 to the 4 and all price is within 3 * 10 to the 4 and all price is within 3 * 10 to the 4 and all the prices are within 10 to the 4 one important attribute of the stock trading in this question is that you can actually sell the stock and then buy it back at the same day in other words you can always sell the stock first to secure the profit and then buy back if you know that the stock price is going to be higher tomorrow otherwise you can just wait for the stock price to drop the next day and then buy it back this strategy is literally the one who are going to implement I will first keep the accumulated profits in this variable profits which is defal to zero also like to keep track of the hpoz by press in a variable called Buy price which is default to like a very large number notice that the Buy price here doesn't mean that you already buy the price but rather you keep track of the Buy price from the previous days and when you see a higher selles price the later days you will know the profit you can actually get so here we will iterate through all the prices in the array if we know that the price is higher than the previous Buy price no matter where is from like from one of the previous days we can secure the profit first and then afterwards we will set the Buy price to this new price the reason why we need to set the price here is because we might want to buy in the stock today and then sell it tomorrow so we'll keep track of this value but we don't need to actually buy it today we will figure this out tomorrow the very next day at the end I will just return the profits cool now let's get into the code implementation what we are going to write down is pretty much the same as the sud code first I have a profit variable to zero I'll have a buy price set to an infinite number and since the constraint here told me that the range of the prices is within 10 to four I can use like a Medan here that's the infinite price now I will go through the price in the price L and then every time I will check if the price is larger than the Buy price so I will like to secure the profit and no matter what I will always reset the price to this current price now return the profits at the end one trick you can do here is instead of having these two lines you can always do profits plus equals to Max Z price minus 5 price so that if this number is larger you will get a positive profit otherwise you will be zero so this is just a trick that you can simplify your code a little bit now let's see if it works okay three test cases are passed now do the submission all right so it bits around 50% of the users and yeah that's the end 50% of the users and yeah that's the end 50% of the users and yeah that's the end of this video and thank you for watching | Best Time to Buy and Sell Stock II | best-time-to-buy-and-sell-stock-ii | You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104` | null | Array,Dynamic Programming,Greedy | Medium | 121,123,188,309,714 |
396 | hey what's up guys so it's always a simple question called rotate function okay so uh basically you have an array and there are k portions which is clockwise and you can define rotation function which f of k becomes 0 times a k over k 0 and k 1 of the minus k in and they return the maximum value of 0 1 and n minus 1. here you can check the example uh right so for example the first one is zero one two three the second one zero one two three but you need to shift it right you count zero six so basically you need to shift uh from uh the oh so zero become here i become here and then one becomes uh zero so basically everything shift to uh to right okay uh right everything shift to right and then so there are four of them okay and you ready to return the max okay so the uh the magnitude of this n is a 10 to a five right so if you create everything which may take the n square uh should not pass okay so the idea is that using the recursion uh so hopefully uh this probably simple that you can see there should be a recursion so let's consider f0 okay so f0 let's say our array is a0 a1 a2 up to a minus one so f zero will be uh zero times a zero one times a one up to a minus one a and minus one okay so let me just maybe write more terms so that uh so that you uh you guys can feel uh easy to follow okay so i can also write as k a k from zero to n minus one okay now i can consider f of one which is uh so everything shifted by right okay so i think it should be right so which a zero becomes here and a one become two and also the uh okay so what is the first term by zero and minus one so the final term will be a zero a 1 n minus 2 right so a minus 1 minus 2 okay so let's consider its difference so what is f1 minus f0 so right it's different so let's consider a0 right so ac there is one training a0 and the 120 a1 okay so you get a0 plus a1 uh up to what up to these turn also this a minus 2 also has the term a minus 2 okay but minus a minus one okay all these are plus these guys also uh only at least term is different minus right because there's no n minus one term in the second okay so this is will be your answer okay so let's massage it so i can just massage it as a zero a minus two uh plus a and minus one minus an a minus one okay so notice that this is the sum of a zero up to a and minus one okay so these guys are in variance okay so you get f one minus f of zero which is a that's called s which is summation minus and a n minus one okay so you can easily check that if you do f of two minus f of one unless you get the same thing right you get s which minus an a n minus two and you will get 2 x plus 3 minus f of 2 that will be s minus and a and minus 3. and keep going okay so this is very stupid right so you can once you get f of 0 right you just update your f 1 to be able zero plus s minus an a minus n minus one and you just keep going you can define your f of two to be f of one plus you know the f of s minus and a and minus two okay so you only need one number f of zero and then you keep doing the updating okay so you can compute s right so just a simple uh simple update and you can re you can initialize your answer to be that's the f of zero and the in each step you just maximize the answer with respect to f of n okay so now i'll call it very easy define a s which is sum for everything and the lens and you first compute f of zero right so answer initialize will be f zero and there is a value which is f of zero and then you go back for each term your value equals value plus sum minus n times this okay so which is exactly it is all right so this is your value minus sum minus n minus some particular term defined to be the next values right so this is the value equals value plus sum minus and the answer is defined to maximize the value okay so there's a simple update let's solve the problem that's it okay so there's a sim so i think this problem you can call it coding right but pre just uh just algebraic uh just algebraically you can solve it by definition see you guys the next videos | Rotate Function | rotate-function | You are given an integer array `nums` of length `n`.
Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow:
* `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].`
Return _the maximum value of_ `F(0), F(1), ..., F(n-1)`.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[4,3,2,6\]
**Output:** 26
**Explanation:**
F(0) = (0 \* 4) + (1 \* 3) + (2 \* 2) + (3 \* 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 \* 6) + (1 \* 4) + (2 \* 3) + (3 \* 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 \* 2) + (1 \* 6) + (2 \* 4) + (3 \* 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 \* 3) + (1 \* 2) + (2 \* 6) + (3 \* 4) = 0 + 2 + 12 + 12 = 26
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
**Example 2:**
**Input:** nums = \[100\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `-100 <= nums[i] <= 100` | null | Array,Math,Dynamic Programming | Medium | null |
1,685 | Hello everyone welcome to my channel Quote Sorry with Mike So today we are going to do video number 72 of Hey's playlist, it is a very easy question, actually it is 1685, a little observation is needed, it will be a very easy question, okay the name of the question is sum of. By saying absolute differences in a sorted, it's okay, sorted, it solved half of our problem, I will show you how, I will update. Who asked this question, very soon, sum of absolute differences in sorted, it is a very simple requirement, the question says You are given an integer array of numbers which is sorted in non decreasing order. Ok build and return an integer array of a result with the same length as numbers. That's the value of that result. What will happen? It is equal to the sum of absolute differences. Of Nam Sai with all the other elements, okay for example, look here like this is the index zero, index and index two and this is my result, so what will be the result of its zero index, let me tell you which among the numbers zero. The element is two, so take the absolute difference of that two from all the numbers, 2 min 2 plus 2 min 3 ps 2 mi 5, take its sum 0 plus 3 mav p 3, it is four, so the answer here will be four, okay. Here let's look at the problem 3-2 plus 3 P 3 - 5 How much is 1 P 0 3-2 plus 3 P 3 - 5 How much is 1 P 0 3-2 plus 3 P 3 - 5 How much is 1 P 0 P 2 Its answer is 3 And let's check it 5-2 Ps 5-2 Ps 5-2 Ps 5-3 P 5-3 P 5-3 P 5-5 0 P 2 P 3 Ok 435 was the answer, 5-5 0 P 2 P 3 Ok 435 was the answer, 5-5 0 P 2 P 3 Ok 435 was the answer, so I hope the requirement would have been cleared and it is a very simple requirement. You know, brute force is very simple. You know what to do actually. Right means root force is very simple. What will you do if the result comes? If you have to remove it, what will you do, go to this element, take the absolute difference of all the numbers aa, just write a for loop, for aa = 0 aa, lesson n aa ps write a for loop, for aa = 0 aa, lesson n aa ps write a for loop, for aa = 0 aa, lesson n aa ps plus, okay, now what do you do? That is, if we want to take the absolute difference of this i element from all the other elements, then sum i is equal to two, here we take ro, okay, all the elements are for j = 0 j < n j ps elements are for j = 0 j < n j ps elements are for j = 0 j < n j ps okay, what we have to do is sum plus equal to absolute value. The difference of the absolute value of numbers of aa from all the numbers is fine. Numbers of j, just here, as soon as the for loop ends, we will store this sum in the result of aa and return the results in the last. But pay attention, what is the problem in this? Is o of n s solution? We have not taken advantage of the fact that it is sorted here. If you pay attention, then there must be some benefit in it. Why have we given that it is sorted? There must be some reason, so let's see and try to understand. Brother, what is the benefit of sorted, we are fine, brute force is of no use, our o of n will give the time limit seat because the constraint is very high. Okay, let's come to the thought process of how we will build it. Now look at the solution. Let's try to understand the thought process as to how the solution to such problems is built. Let's take a look at the example. Emma B. Kama CD is fine and it is sorted in increasing or non- sorted in increasing or non- sorted in increasing or non- decreasing order. It is given here. In the question that it is sorted in non-decreasing order, okay, so now it is sorted in non-decreasing order, okay, so now it is sorted in non-decreasing order, okay, so now look, pay attention, here we go by the value that this is our I index, we have to find its answer, okay, this is the result, let's assume that we have found the answer to all these. We have to find out, okay, so look, pay attention, how will we calculate the result of a j b equal to two absolute value of numbers of a minus numbers of 0 plus absolute value of numbers of i minus numbers of one plus absolute value of numbers of i minus numbers of two isi Look, we took the difference from Nums zero, Nums one from Nums two and so on till Nums of I minus Nums of a my, this will also have its absolute value plus the absolute value of Nums of I minus Nums of I will also be taken from all the elements. Plus absolute value of numbers of i minus numbers of i psv plus dot absolute value of numbers of i minus numbers of which will be the last element in our n-1 index. Okay, so in our n-1 index. Okay, so in our n-1 index. Okay, so we used to get the result of every i like this, it is okay. And pay attention to one thing here, the numbers of i minus the numbers of i will definitely cry, so you can ignore it's okay because it is an obvious thing, it will cry, so even if you do n't add it will be fine, otherwise I have mentioned it. That's why I have cut it off, for now it does n't matter, the answer will be zero, Nam Sai Mine Namsai Ka, now pay attention to one thing, here the absolute value is given, so Nums value is given, the absolute value is given, so Nums of a minus Nums of 0, will it be negative or positive? It will be Nums of A minus Nums of This is zero, okay, this will be positive already because it is sorted in non-decreasing order, so C will either be sorted in non-decreasing order, so C will either be sorted in non-decreasing order, so C will either be greater than A, or equal to A, so it will always be positive, either zero will come, okay, so absolute. Even if you put no, it is the same thing because Nums of aa is bigger than Nums of zero, either can be equal, similarly look here also Nums of aa is minus Nums ofv is Nums of a yes is bigger than index number one Na, similarly, names of Aa are mine, here also you can remove the absolute value because anyway that positive value will come, because Aa element is bigger than Tu. Now look here also, names of Aa which is bigger than Nams of Aa. Either it will be equal, then there is no need to enter the absolute value, it will be the same, it is okay because the number of aa is bigger and the elements before it are all 0 1 2 and so on till aa is fine and then The eighth element has come here, numbers of aa minus numbers of aa, after that the elements after numbers of aa minus aa are there, see all this i pw aa p 2 and so on i-1 yes here the answer on i-1 yes here the answer on i-1 yes here the answer can be negative because see this. Which is Aa Pv, it is coming after Aa, don't you see Aa and Y i Pv, then it is obvious that it will be bigger or it will be equal, if taken in non-decreasing order, equal, if taken in non-decreasing order, equal, if taken in non-decreasing order, then what are the chances of it being negative, are n't there chances of that? That it can be negative, so we have to take its absolute value, either you write it like this, Nums of aa minus Nums of a, i is Pw, then make it like this, Nums of Aa, Pw minus Nums of a, it will not make any difference because we So at dand absolute value only has to be taken neither numbers of i + 19 numbers of i will be numbers of i + 19 numbers of i will be numbers of i + 19 numbers of i will be equal to absolute value of i will be equal to meaning what am I saying absolute value of m - n will be equal to absolute value of n - n will be equal to absolute value of n - n will be equal to absolute value of n - m thing one Yes, okay, now - m thing one Yes, okay, now - m thing one Yes, okay, now what I did here was write i + 1 first and write i aa what I did here was write i + 1 first and write i aa what I did here was write i + 1 first and write i aa later because i + 1 later because i + 1 later because i + 1 is bigger or else it will be equal element, so now see if it is bigger than this then it is obvious the answer is always positive. Now I can remove the absolute value from here, right? I have removed the absolute value because it will always be a positive answer. Why have you asked to put absolute? Because positive values have come, that's why Because positive values have come, that's why Because positive values have come, that's why absolute value has been said. It is okay to put it here. But let's see, similarly here also we can do the numbers of n -1 minus the numbers of a and here the of n -1 minus the numbers of a and here the of n -1 minus the numbers of a and here the absolute value can now be removed. Okay, now pay attention to one thing, the figure was out here, I also had the problem, you can rearrange it. You can do this, look at what is there from i -1 0 to i -1, what is there from i -1 0 to i -1, what is there from i -1 0 to i -1, look at that part from here till here, rearrange it, if I do, then look at the minus, come at numbers, what is there, came once, came twice, came thrice, came four times. aa and so on ok so how many times will it be added see so names of aa in aa times that will be added isn't names of aa plus names of aa p names of aa and so on aa times added ok so names of aa in We have done it okay and now pay attention to all these numbers zero numbers one numbers two till where numbers of a my till take the minus common of all, if you take the minus common of all then okay then see what comes from numbers of zero to numbers. From off one to plus p plus till where was the numbers of a miv tha. You are seeing that we have rearranged it and written it so well, here it means the numbers of i in a minus 0 to a miv tha, we just need to rearrange them. We have given the formula similarly, now let's look at this part, look at the sum from plus to n-1 and sum from plus to n-1 and sum from plus to n-1 and look here, minus if we take the common, okay, minus if we take the common, then numbers of a, see how many times it has come. Isn't it the names of aa, how many times would it have come, how many times would it have been added into n - aa minus one time, it would have been added, into n - aa minus one time, it would have been added, into n - aa minus one time, it would have been added, okay, that's why we multiplied it so many times and now I will show you an example as to why we have multiplied by aa here. And why did you multiply by n - i - 1, why we have multiplied by aa here. And why did you multiply by n - i - 1, why we have multiplied by aa here. And why did you multiply by n - i - 1, okay now you will understand, don't worry okay and look at all these names are being added. If it is okay, then here I write the numbers of a p plus dot till where the numbers of n are equal to the number, it is okay, if it is cleared till now, then the result is our, this is our simplified result. Our result is okay that the sum of numbers of a in a by two minus zero till the rectangle is ok then the sum of numbers of i + 1 to rectangle is ok then the sum of numbers of i + 1 to rectangle is ok then the sum of numbers of i + 1 to numbers of n -1 is even, numbers of n -1 is even, numbers of n -1 is even, this is also even, this one on the left side Is it even? The one on the left side of i is even. And look at this. The one on the right side of i is even. From i + 1 to right side of i is even. From i + 1 to right side of i is even. From i + 1 to n-1, the right one is even. Okay, minus numbers of i n-1, the right one is even. Okay, minus numbers of i n-1, the right one is even. Okay, minus numbers of i * n - i - 1. Okay, let's take a small example. Let me * n - i - 1. Okay, let's take a small example. Let me * n - i - 1. Okay, let's take a small example. Let me show you here, now look, pay attention, let's assume that ours is five, 6s, 8, 9, 11, okay, now pay attention to one thing, let's go by the values, index aa, ours is here, okay, so now pay attention to one thing. What was our answer going to be? 8 - 5 P 8 - 6 P What was our answer going to be? 8 - 5 P 8 - 6 P What was our answer going to be? 8 - 5 P 8 - 6 P 8 - 8 So it will be 0, so I will remove it. 8 - 8 So it will be 0, so I will remove it. 8 - 8 So it will be 0, so I will remove it. 9 - 8 + 11 - 8 This was going to be our answer. 9 - 8 + 11 - 8 This was going to be our answer. 9 - 8 + 11 - 8 This was going to be our answer. Now pay attention to one thing, pay attention to this. Okay on this, I am rearranging it. 8 p 8 minus taken the common. 5 p 6. This party becomes Y. Plus here 9 p taken separately minus the common taken 8 p 8. Okay let's assume here. But if there was another element, let's say it was 13, then there would be one more element here, 13 my 8. Okay, so what would happen here is 9+ 1 + 13 my off 8 + 8 + 8. Okay, 9+ 1 + 13 my off 8 + 8 + 8. Okay, 9+ 1 + 13 my off 8 + 8 + 8. Okay, this is my right part, is n't it? So look here, pay attention to how many times 8 has been added. 8 * 2 is how many times 8 has been added. 8 * 2 is how many times 8 has been added. 8 * 2 is right, 8 * 2 means look, zero is the index, right, 8 * 2 means look, zero is the index, right, 8 * 2 means look, zero is the index, first index is the tooth index, the value of i is 8 * is actually here, that's value of i is 8 * is actually here, that's value of i is 8 * is actually here, that's why here. But look at the numbers in a, it is clear till here, after that, the sum from ro to a, sorry, the sum from zero to i - 1, see this, the sum from f and 6, here is the sum from zero to i - 1, see this, the sum from f and 6, here is the sum from zero to i - 1, see this, the sum from f and 6, here is the sum from zero to i - 1, this is i - 1. Right, the sum till there i - 1, this is i - 1. Right, the sum till there i - 1, this is i - 1. Right, the sum till there is fine and let's see the second part from i + 1 to is fine and let's see the second part from i + 1 to is fine and let's see the second part from i + 1 to n - 1, hence the sum of element i + 1 n - 1, hence the sum of element i + 1 n - 1, hence the sum of element i + 1 means look at the sum of this and this, it is ok here and see how many times t has been added. What is said here n - i - 1 What is said here n - i - 1 What is said here n - i - 1 is ok n is my 6 - i is my 2 minus 6 value is ok n is my 6 - i is my 2 minus 6 value is ok n is my 6 - i is my 2 minus 6 value is two 4 minus one three times that is why I have n minus a minus here ok it is quite simple maths just here So if I simplify here and write that if you want to get the result of Aa then you do not have to do anything. Multiply the numbers of Aa by multiplying Aa by minus 0 to Aa. This is done on the left side. Done plus remember what was the sum of i + 1 2 n - 1 remember what was the sum of i + 1 2 n - 1 remember what was the sum of i + 1 2 n - 1 and what was this is the minus of numbers i * and what was this is the minus of numbers i * and what was this is the minus of numbers i * minus of numbers of i * n - i - 1 this of numbers of i * n - i - 1 this of numbers of i * n - i - 1 this is the simple formula we derived Okay so now a Please note that for each result, you will need the sum from row to a mive. Okay, so don't calculate the sum again and again. What would be better than this, we will pre-calculate the prefix sum pre-calculate the prefix sum pre-calculate the prefix sum so that we can immediately calculate the sum till any index. Look how much, if we need the sum from row to aa miw, we will get it immediately. Okay, our problem has become quite simple. Now let us see by running this example, the first apple station is 235, how do we get its answer. My name is 235. This is now. We do draw run completely. Okay, so what I said is that first of all I take out the prefix sum because it is going to be useful for us. Prefix sum 2 3 5 55 10 is clear till now look let's move ahead, we have to take out. Result came here, we don't know yet what is the result of came, because of the value of came now it is zero, 0 watt, okay, so what I said, what will be the result of came, what will be the names of come, i.e. is insect in came isn't names of come, i.e. is insect in came isn't names of come, i.e. is insect in came isn't it? After that, what was the sum from minus 0 to a myve? Okay, now look at one thing, pay attention, let's say there is some Hey, this is the prefix sum, its okay, you have to find it becomes i - 1, let's say you have to find it becomes i - 1, let's say you have to find it becomes i - 1, let's say if you get i. If you want to find the sum up to i - 1, if you get i. If you want to find the sum up to i - 1, if you get i. If you want to find the sum up to i - 1, then you find the sum up to i and if you subtract the numbers of i, then you will get the sum of this much, what am I saying? Prefix of i means you have found the sum up to i. If you add prefix sum minus number of i in it, then obviously this element will be removed and we will get this remaining, we will get the sum till i - 1. Okay, that is what I am get the sum till i - 1. Okay, that is what I am get the sum till i - 1. Okay, that is what I am trying to do here, whether it was 2 * i or not, trying to do here, whether it was 2 * i or not, trying to do here, whether it was 2 * i or not, what am I here? I will do minus prefix of i, it is ok till minus numbers of i, so what does it mean, I already had the sum till i, I already had the prefix i, I had stored it, if you minus the numbers of i, then from where to where. The sum will come from 0 to aa mive. Make sense. It was written here that the sum would be from ro to aa mive, that is why we had already found the prefix 'are' and kept it clear we had already found the prefix 'are' and kept it clear we had already found the prefix 'are' and kept it clear so that we can calculate easily. And after this, remember what was our sum from aa pv to n myv minus numbers of aa in mine aa miv so let's see here we need the sum from apv to n-1. Let's need the sum from apv to n-1. Let's need the sum from apv to n-1. Let's come here again what are you saying. Let us assume that this is my aa, I want the sum from aa to n-1, then see what I will do, want the sum from aa to n-1, then see what I will do, want the sum from aa to n-1, then see what I will do, I not only know the sum up to n-1 but also the I not only know the sum up to n-1 but also the I not only know the sum up to n-1 but also the whole sum till n-1 i.e. the whole sum till n-1 i.e. the whole sum till n-1 i.e. the prefix of n-1 What will happen from this, I will prefix of n-1 What will happen from this, I will prefix of n-1 What will happen from this, I will get the sum from here till n-1, get the sum from here till n-1, get the sum from here till n-1, I will subtract the prefix of aa, meaning what am I saying, I have subtracted the sum till aa, then what is left, aa. If the sum from pv to n miv is fine, then the same mind will be applied here also plus how to calculate the sum from pv to n miv, prefix sum n miv minus prefix of aa, then this sum from a pv to av will be found out ok. What was there after that, we had to subtract this one, numbers of i * 9 - i subtract this one, numbers of i * 9 - i subtract this one, numbers of i * 9 - i - 1, - 1, - 1, my numbers of i * n - i - 1, that's it, we have to my numbers of i * n - i - 1, that's it, we have to my numbers of i * n - i - 1, that's it, we have to get every result like this, okay, so its time complexity can be reduced to one. We are visiting the space approach whose time complaint is this. Now you can also do it yourself which is the approach that I will tell you in which you can solve it without taking a prefix. You can solve it on the fly. So let's see how he does his approach. Let's see it in his approach. Before that, we complete its dry run. We have to find the result of A. Okay, that means we have to find the result of zero th index. So Aa is zero now, it is mine, it is 2 * 0 has Aa is zero now, it is mine, it is 2 * 0 has Aa is zero now, it is mine, it is 2 * 0 has become minus prefix of aa, this is zero, this is one, this is two, look at the prefix of zero, it is two, 2 minus numbers of aa, numbers of zero are also two, it has become zero, after that look here, plus is the prefix of n. -1 is how much is 10 is the last one minus n. -1 is how much is 10 is the last one minus n. -1 is how much is 10 is the last one minus prefix of aa what is two is okay 10 minus two here minus numbers of aa means 2 in n - aa -1 means 3 minus 0 myv is okay let's in n - aa -1 means 3 minus 0 myv is okay let's in n - aa -1 means 3 minus 0 myv is okay let's see how much it is The whole is zero, right here plus here 10 my two becomes 8 and here let's see how much is 3 my two 4 becomes 8 my ch ok so how much comes 0 plus 8 my 4 becomes four so its answer is four here But remember, here there was also four, now let's find out the index number one. Okay, index number one here, what was Namas aa in aa, na namas, what is this time 3, so if 3 is Nav then it will be 3, this is the minus prefix ofv i.e. That 5 minus numers of aa is 3 so 5 i.e. That 5 minus numers of aa is 3 so 5 i.e. That 5 minus numers of aa is 3 so 5 my 3 becomes 2 then it is plus prefix of n my aa that means 10 minus prefix of aa is 5 Okay minus numbers of aa in that means that 3 in n my aa miv that is 3 Maiv i.e. in n my aa miv that is 3 Maiv i.e. in n my aa miv that is 3 Maiv i.e. 3 - 2 i.e. one is done na let me 3 - 2 i.e. one is done na let me 3 - 2 i.e. one is done na let me rewrite here 3 - aa 1 rewrite here 3 - aa 1 rewrite here 3 - aa 1 -1 3 - 2 1 is done 3 * 1 3 is done ok let's -1 3 - 2 1 is done 3 * 1 3 is done ok let's -1 3 - 2 1 is done 3 * 1 3 is done ok let's see how much comes. 3 minus 2 will become this plus 10 - 5 plus 10 - 5 - 3 will become 2 this plus 10 - 5 plus 10 - 5 - 3 will become 2 this plus 10 - 5 plus 10 - 5 - 3 will become 2 this is ok 3 - 2 becomes one 2 p becomes one this is ok 3 - 2 becomes one 2 p becomes one this is ok 3 - 2 becomes one 2 p becomes one so here we get three and similarly here we get five you can solve and see. If you can then ok then this is the dry run of our approach one and in this we had taken extra space. Now let us come to approach two in which without using extra prefix, we can make it. Look, in the first approach we are using our own space. Let's try to remove it. What is the meaning of Prefix Sum? For example, suppose you are standing here now. What is the meaning of Prefix Sum? The sum from here to here is correct and what do we have to do in our question? Remember, sum was required from 0 to i-1 Remember, sum was required from 0 to i-1 Remember, sum was required from 0 to i-1 and sum was required from p to a-min, and sum was required from p to a-min, and sum was required from p to a-min, hence the prefix Hey was useful. So what do I say, first find out the total sum. Total sum means the whole of this. Sum 2 P 3 P Pa How much is it 10 Now I am saying that whenever we are finding the answer and the result is coming, then in the same for loop we will keep finding the sum to know what is our sum, as if we assume that we are here now. Okay, so I have taken a variable named prefix even. Okay, I have taken a variable named prefix even. Now its value is zero. Okay, so right now I am currently at a. Okay, so behind aa i.e. from 0 to i - Where will I store the sum up to 1? i.e. from 0 to i - Where will I store the sum up to 1? i.e. from 0 to i - Where will I store the sum up to 1? Prefix sum is fine and the value of prefix sum is zero right now and that is also correct. Look, there is no element before this aa, so the sum is zero. It is fine and as we move ahead, it will be the same. We will keep on adding elements in the prefix sum, okay, let's say that now I have come here, okay, then in the prefix sum, I will add this two and at the same time I will add it, then the prefix sum will be two. Look, for a given, what is the sum from zero to seven, look, you will get this in the prefix sum, it is ok, then when we move further, we will add 'r' in the prefix sum move further, we will add 'r' in the prefix sum move further, we will add 'r' in the prefix sum and here When it comes, I will already know what is the sum from here to here, it will be stored in the prefix, that is fine, so our work can be done with only one variable, so this is it, we can find out the sum from 0 to i-1. so this is it, we can find out the sum from 0 to i-1. so this is it, we can find out the sum from 0 to i-1. Prefix sum is through the variable, we will keep storing its sum in prefix sum, but now comes the point, remember that we needed two things, we needed the sum from 0 to -1 needed two things, we needed the sum from 0 to -1 needed two things, we needed the sum from 0 to -1 and i to n also. Sum up to -1 was required. Remember the formula Sum up to -1 was required. Remember the formula Sum up to -1 was required. Remember the formula what we derived. Here is the sum from 0 to a. This will be calculated from the prefix sum. Now how to calculate the sum from i + 1 to n-1. Now how to calculate the sum from i + 1 to n-1. Now how to calculate the sum from i + 1 to n-1. So remember what I said in the beginning. This sum was calculated, right, this will help you. Look, now pay attention, you are currently standing at A, so you have this amount of sum already available in the prefix sum. There is two in it. Let's assume that you know what the total sum is. The total sum is 10, subtract the prefix sum from it, okay, 10 - 2 becomes 8, subtract the numerator of aa from it, - 2 becomes 8, subtract the numerator of aa from it, - 2 becomes 8, subtract the numerator of aa from it, minus the numerator of aa, then what becomes 10-2 my minus the numerator of aa, then what becomes 10-2 my minus the numerator of aa, then what becomes 10-2 my 3, 10 my do 6 my 3, 10 do 8 pa ho. Now look, it is correct, five has also arrived, the sum of our right hand side is fine till now it is clear, so I am saying that you do not need to take the sum separately, you can simply calculate the total. Let's calculate sum and prefix sum up on the fly. Okay, so our approach is quite simple. So, let's do one thing, let's code approach one and then derive approach two from the same. Okay, prefix sum is also the size of this. n will be okay and the first element of prefix sum will be equal to the first element of numbers after that simply we take out the prefix aa lesson and aa plus okay prefix sum of aa will be equal to prefix sum of aa my plus numbers off Aa is clear till now, okay, now let's come to our main code Aa = 0 Aa I Le A Aa Ps our main code Aa = 0 Aa I Le A Aa Ps our main code Aa = 0 Aa I Le A Aa Ps Now look, pay attention to what I told you that how to get the result Aa from Aa, let's first find the sum of the left side of Aa. And after calculating the count, you will remember well the formula which I told you. Here I also write the result of aa will be equal to two numbers of aa in aa. Okay, minus of 0 to aa is equal to my na to these numbers. Off aa in aa, we will easily find out 0 to aa, if we want sum of left or right, then I will write down what will be the left sum. I also told you that sorry prefix sum of aa minus numbers off aa. What will this give? Will it give you the sum from 0 to aa mive? And this one which is the product of names of aa in aa, so let's take out this too, let it be, we have taken out the left sum and right and one. Another thing was here plus remember I psv to a mive's sum is okay minus names of a in a minus a psv a mi a miv was sorry this was it so we have found out the left sum now let's find the right sum okay so Do you remember how to find the right sum? We need the sum from prefix aa up to n-1, We need the sum from prefix aa up to n-1, We need the sum from prefix aa up to n-1, so what will I do? Prefix, we have found the sum up to n myv, minus the prefix, we will do aa. Okay, so this will give me the right sum. 0 aa. Will give the sum from p to n-1, okay sum from p to n-1, okay sum from p to n-1, okay now just don't do anything, the result of aa will be equal to what was the numbers of aa in aa, okay this is done and minus of zero to aa is the sum of manav i.e. and minus of zero to aa is the sum of manav i.e. and minus of zero to aa is the sum of manav i.e. left sum. Okay, after that plus aa pv se av ka sum i.e. right sum minus names of sum i.e. right sum minus names of sum i.e. right sum minus names of i in a my aa mive this was a simple at ok and in the last return result and let's run it and see let's pass last cases indeed yes this Now we will submit and see and will also modify it so that we can make approach 2. Indeed yes we have solved this question using first approach, second approach also comes, second approach is very simple, I had said that we will not take only the prefix, we will not take the complete prefix. Removed it here, just simple, what did I say, we will already find out the int sum equal to 0, okay for a i 0 a i take a p sum inms of a sum, either one more big very to find the sum. The best way is to acuminate the sum from the beginning of the numbers till the end of the numbers, starting from zero, okay, you can get the sum like this too, so we have got the total sum, okay and there is no need to take prefix sum this time. Sum el t 0 Take one variable, that's it, i = 0, come n is left Take one variable, that's it, i = 0, come n is left Take one variable, that's it, i = 0, come n is left sum, remember earlier, what used to be prefix sum, we used to use are I will store it in this. Suppose now I am at zero, then there is no index before zero, so its sum is zero. Look, this is correct. Here the sum is zero, left sum is its right sum. I told you how to find the right sum. Total sum minus sum from row to a mive Prefix sum is ok, prefix sum is found but numerator of i will also have to be minus because if sum is required from i + 1 to also have to be minus because if sum is required from i + 1 to also have to be minus because if sum is required from i + 1 to n - 1 then total sum n - 1 then total sum n - 1 then total sum minus prefix sum i.e. prefix sum minus prefix sum i.e. prefix sum minus prefix sum i.e. prefix sum What was the sum from row to i - 1 and the number What was the sum from row to i - 1 and the number What was the sum from row to i - 1 and the number i was also minus till now it became clear, now there is nothing after this number of i * i now there is nothing after this number of i * i now there is nothing after this number of i * i this is clear left sum right sum everything else is the same let's run and see Have hope fully we should be able to pass all the test cases yes one thing we have missed na update prefix sum bhi to keep doing prefix sum p = bhi to keep doing prefix sum p = bhi to keep doing prefix sum p = numbers of i ok let's submit and see indeed yes we have solved this question no Bhi doubt raise in the comment section try to help out see next video thank you | Sum of Absolute Differences in a Sorted Array | stone-game-v | You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104` | We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming. | Array,Math,Dynamic Programming,Game Theory | Hard | 909,1240,1522,1617,1788,1808,2002,2156 |
202 | hi everyone today we are going to talk the little question happy number so write the algorithm to determine if a number n is happy so happy number is a number defined by following process so starting with any positive integer replace the number by the sum of squares of its digits repeat the process until the number equals 1 or 8 Loops enter 3 in a circle which does not include one those numbers will reach this process ends in one or hobby so return true if N is a happy number and a force if not so let's see the example so you are given 19 so we Square each number I got 10 intense digits and one's visit so like a we Square One and there is also Square 9 and the total is 82 and again so we Square each number like eight and two so we square a and the square two and the total is 68 and same thing we Square 6 and the V Square 8 and then get the 100 V squared 0 and the total one and finally we get one in the case uh 19 is a happy number okay so let me explain with this example so n equals 19 and actually I already wrote down the algorithm here so we can do the uh this process like one by one and then first of all we need to get one digit so how can we do that so this is the formula so n plus and 10. so if 90 if n is 90 so we will get the 9 so 9 percent 10 is 9. because uh we will get a remainder from this formula so if n is 15 we will get the 5 if n is starting we will get 3. so it's easy so now digit is nine and uh we move next so now digit is 9 and we write like asterisk twice and the two so this means that so digit by digit so that's why uh we can square digit number with like asterisk 2. so in the case uh nine by nine so output is 81. and then next so n is 19 and the slash thrusting is just a divider uh 19 with 10 so in the case this n should be 1. and then go back to the first process so again now n is 1 and percent 10 is 1 right yeah it looks good so we successfully um nine and the one separately so I think uh the order of like uh numbers are not programmed and uh so now this is one and uh I'll start a size two so is one so that's why total number is now 82. so yeah it looks good and then now n is one so n is zero so now n is zero in the case uh start stop this process and return output so which means id2 yeah looks good and then we do the same process again and then in some point if we get the one we should return true and if not we should return force and sometimes we get a same number we already checked in the case uh also written Force because uh the numbers definitely a loop like an infinity yes that is a basic idea to solve a description so with that being said let's jump into the code okay so let's write a code first of all initialize visit variable we set so this visit variable is used to check whether we already visit the number current number so that we can prevent Infinity looping so start routing wire client number not in basic in that case first of all are the correct number to visit is it to add in the current number and next get the next number so n it equal self dot get next number passing the current number so highlight the function later and then if n equal 1 in the case down through if the loop is finished in the case we don't find the RP number so just return false okay so let's get next number function So Def get next number and itself number so this function is easy to write the code so because we are already explained earlier so initialize output with zero and start looping wire and so first of all get some module so visit equal in percent 10 and then uh we will Square the digit number and then add the number to Output so output press equal digit asterisk twice and 2. and then uh get the next digit number so n equal n slash and then yeah okay that's it so that now and then return output yeah that's it so let me submit it yeah this solution works so let me summarize step by step algorithm this is a step-by-step algorithm of a this is a step-by-step algorithm of a this is a step-by-step algorithm of a happy number so step one initialize visit we set step two start looping at the current number to visit to get the next number and the checks if the number is one step three to get the next number we repeat doing this process as I explained earlier so actually that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question | 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 |
373 | Hello everyone welcome back to me channel once again so here we are going to talk today about the daily problems of the court, NDA question is of medium level and also in this question you will see implementation on priority, okay so because I am in this I was thinking of a simple iterative type solution to the question, but when I saw that people have again discussed it in a related topic, I said, why not, we are also interested in this and it will become a little easier, I will discuss that too with you. In the future, you will have to handle that a little bit, it will become a little easier, you will get the thing by making a bunny, okay, people understand that all the elements together, you will be number one here, let us suppose that in one element, if you are an element, then it is total, if we are talking about you. Take one element from total element and n23 for cell then n1 * n2 which will be very big. It then n1 * n2 which will be very big. It then n1 * n2 which will be very big. It said that out of all these you have to choose the leg of k and do things on k in such a way that If it is even then there is an element and if it is even then whatever is even is the smallest, then you will consider the lowest one to be just the latter, so whatever is there, return it to you in this way and lower it down to the right. Look, it has been made very simple, beautiful and the most. The first thing that comes to mind is the method, but when you look at its constraints and look at its stand on the tent, then you realize that your approach should not be too n². If these people have more approach than what they are, then you will have to Tali will give right. Okay, now there is one more thing that the maximum value of K is up to 104, so if we are not building on it more than the whole, that means we will not be tweeting on more. So one thing is this. This is your time which comes within the range, okay, which you must understand, after that, like I have taken this one, okay with the four of seven, now any element which will come after seven or after seven, okay their. The sum will always be the highest of it, believe me, why am I saying this because it is in the ascending order, so the element after it will either be greater than the seven in the ascending order. From this, if we are taking Melamet, then it will be greater than four, then obviously its sum will be greater than these two, meaning seven plus any one number will come and four will come, then obviously it will be 11 plus Whatever is yours, I am saying that if you have given a late supposition, whatever is your condition, which is the retirement of your leg, it is being satisfied and completed here, where we can take a break. If it is in increasing order, then the first one we will make will be the smallest, after that, the one which will be bigger, we will put it in our false loop in this manner, we will see that both the upper ones are ours, they go in the loop, then we have to remove them and if the retirement is completed. After this, the number which is being formed is not small but it has become big, it means that it is not less for those who are in the future to leave me, okay Shimla will decrease, you can try, maybe I think we can approach this also. Can do what I am doing first look 17 246 is your second so after picking this element I will go to the maximum how far I can go ahead of yours which is any first element which is fine for basic first If I find an element bigger than this then I will leave it there, it has its own region and we started from now, what will happen if I was reducing the maximum, then only the maximum will always be on the top, then first of all we will check that the hip dot size is yours. Give hip dot size grater or not if it is done that if it becomes greater then it is enough for you wood retirement is as much as it is, yours is ok if how it becomes more then our retirement is over then I will see the summary that which Coming is even, if that coming is smaller then ok if coming is smaller than this top one then I have to keep it if not then what will I do simple yours because yours if this coming is bigger than the top one then your How did this one happen where all of us will be your superiors, so simply make us there, I will break you in the court, the director will take you to the court, which will make better sense, okay, so let's go here, this is fine, it is possible. Why did you make one, privacy, why is it keeping your sum, it must be keeping both the elements, okay here, after taking the sum, if the priority is because the size is less, then we are directly keeping it complete, right, if the sum is Which is fine, if this is the size of ours, it has become what it is today, but it is such that an element smaller than the one we have is made of some one, so how can I indirectly pump it to the other. I will do this so that the one who likes me will remove the big element and I will push the small one and then it will do it automatically in the hit and yours will always be on the top. There was only one point which you must understand, this one is divided like this, so all your numbers will be your max, that is, they will come in this loop, so why not break it and leave it for further competition. Go because they are useless, there is no rule in this question, right here we made a break and now what do we have, now the legs that we have come with the smallest sum and all we have to do is simply do it. If you want to print and return then we have created the answer vector, okay today vector and here we have simply picked it up from the simple sorry, it will run while adding here and after that simply returned the answer ok so this is easy, I will be telling you in this. I will tell you here three things, we have stored sum first element is ok, understand that your song is number one plus you are your delete kar dun hata dun to main kya sum minus one ok hai retirement kahan pe yahan pe so I can do this If I am first then second, then I will be removed there, then if you want, you can make this priority with two arguments and in this way you can handle it, now whatever is mine second will also reduce it, but you will have to implement it a little like this. Look, we are doing the same thing, here also the same thing is happening, as long as your size is less, we are adding, so we have seen the sum. If the sum means less, then we are checking it, adwise. It is recording directly and basically it is there to store it for you so that your doubt will be cleared. Similarly, the question was very dangerous, leader, very easy type of question. If you may have an issue, then that implementation can be like this, so for this I have written the code. If you code in the description box added below, then you can easily code there. If you want to take help, I am saying that you have to take help, you do not have to copy and paste, it is absolutely fine, so you can do it in that way with help. And what I told you is not necessary, along with its three arguments, I have kept it in this way only so that you can watch this video at the end and you will know that okay, we could have done it with two more comments as well. So that's all in this video, see you in the next video. Bye. | Find K Pairs with Smallest Sums | find-k-pairs-with-smallest-sums | You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`.
Define a pair `(u, v)` which consists of one element from the first array and one element from the second array.
Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_.
**Example 1:**
**Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3
**Output:** \[\[1,2\],\[1,4\],\[1,6\]\]
**Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\]
**Example 2:**
**Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2
**Output:** \[\[1,1\],\[1,1\]\]
**Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\]
**Example 3:**
**Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3
**Output:** \[\[1,3\],\[2,3\]\]
**Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\]
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `-109 <= nums1[i], nums2[i] <= 109`
* `nums1` and `nums2` both are sorted in **ascending order**.
* `1 <= k <= 104` | null | Array,Heap (Priority Queue) | Medium | 378,719,2150 |
87 | what's up guys so let's solve this decode problem 97 called scrambling string scramble string okay so all these problems are very uh strange that uh so given the string i'll given the string at length one then you have two ways right the first if the string is one stop the length of a quadrant one then you can separate into two x and y and then randomly premiere or not okay and now given to string x one and x two you need to return whether s2 is a scramble string of s1 okay so immediately uh if you haven't seen this problem immediately you will think you may think that uh actually any string can be an unfactorial permutation you can get from it but actually this is not true uh great and uh r g ht is obvious right if i cut here and i read and i exchange rg right i can exchange then i first cut here and i don't permit and i cut the left then i get rg right okay so this problem is actually cannot get a cannot get any possible situation for example if abc you can cut here and then you will and you so the left must stop right bc for this guy you can permute okay and if you cut here then you get a bac or uh cab right so basically you can see that uh you can see that there is only one two three four right you got four choice there's no way that you can get an factorial permutation all right so for example uh a b c d e c a e b d this answer is false you cannot get it okay this problem is not true so i think the idea is dynamic programming so let me just uh tell you the key point okay so keyboard is that the key point is very simple either you can let's say you create f which you create a function f basically somebody give you a string s1 x2 you return true if s if s1 is a scramble can be scrambled to s2 force if not okay then how do i write down the permutation right so given the string s1 and string s2 uh i can first i can let's say uh lens must be the same right so i can choose let's say i cut this right i cut i go through each i go through indices and i cut i and i ask whether and i uh cut it right let's say i cut it okay so there's the possibilities that there's a possibilities that uh this guy can be scrambled to this guy okay so this is the case that the orleans guy can be scrambling into this guy right so this is the case one okay so case one basically you just go through the lens of s1 and so for i in range let's say lens of s1 and you can separate into left and right so let's say you separate into left and right obvious let's say you choose indices i and it chooses separate into s1 up to i right you separate into two okay and then you can and there's so simple case is that uh let's say you separate these and you don't do anything but these guys scramble these guys is remotely okay now you can call what then you can call it or you can call so you just ask whether uh your small s1 to your left is the same as the this s2 right out here and the f right is s2 uh i plus one i a good right so basically you just separate this part okay so this is the uh fab right so uh this is the white set okay uh this is the first case right uh there is a second case so second case is that it is what is that if you separate you need to swap right once you swap and these guys are scrambled these guys scramble these that's it there's only two cases and then for this guy i just write down close so you can check the detail but it's almost the same right and i use and you need to use the cache or basically a memory so let me just first just tell you the time exist method but so this guy is very simple right so this guy is telling his method everybody pass a lot so basically this is the uh the uncached version so there's no memorization once you add the memorization then you can solve this problem so if their lens is different then immediate return falls right in trivial right if a b if a and b are the same return true right if then they will understand it and false and uh you separate it right so if you need to check where left is the same write the same otherwise that you check that you do a swap right so the first i is the same as the negative b the b part and the right part is the same as the right part the left part right and the return true and uh if r if you do everything and there is no way that you usually return false right and then this will return f1 s1 s2 right so this is the time tle version because it doesn't use attached but this is the actual correct solution okay so the correct answer is that you add a cache right so you can just you can if you are you can add this the mouse in the cache right but uh the step by step maybe you create a dictionary and if you enter a dictionary you're going to return if it's uh if you already compute so if a and b return true so now for this one you so basically you do the same thing right just add this dictionary and for each step after you get some computation you store into n right so finally just written as x minus two basically you will just get your edges right but at least m will uh it's already pre-computed in just that so already pre-computed in just that so already pre-computed in just that so that's it so basically this is the cache version of this uncached version so uncashed version is also correct but uh just spin a lot so many times but basically you can use this to solve this one see you guys next videos | 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 |
808 | Hello everyone, welcome, you are going to do the 50th question of my channel. Okay and you will know that in this playlist of mine, you can read the DP from the scrap in the section of DP Consider Questions. Okay, today's problem is the date of lead 08. Okay. It is quite doubting, it has this statement which is not a problem, there are a lot of words but it is a very simple explanation, actually it is a very simple explanation and I will clearly show you why it is such a simple explanation, it is okay, just understand that the question is being given. You can write yourself by doing dog pose, soup servings is ok, the name of the question is asked in Google, there is just one extra thing to pay attention to this question, which I myself observed, it is ok from the example but it is very simple, we will see how now. We will make this, as I told that I have started doing both recension and bottom off, in the playlist of my DP concept area questions, there I will teach bottom up along with it, okay, in this video I will make it with recension and memorization, okay So let us understand, what have you given here, there are types of soup, there is also time, okay, there are two types of suits, they have n milliliters, this is also n milliliters in my hand, okay, now look at these four. So you can do any of these operations, first of all, if you have got 100 N-75 from some person, you will be left with it, okay N-75 from some person, you will be left with it, okay N-75 from some person, you will be left with it, okay and here, by doing similar, there is an operation on Power Silver, okay, three or four, do this. It's an operation, see when they serve even soup, whenever we serve soup, you have given some and they have no anchor habit, meaning if you have given, you will not get it back, we are fine, we don't know why we have given, it was not necessary to make such a statement. H Turn Way Bill Choose from the four operations with an equal probability 0.25 What this means is that as many times as 0.25 What this means is that as many times as 0.25 What this means is that as many times as you will get the chance to serve, OK, now you can do any one of these four operations. It is possible that you have taken this or this is okay. Here the probability has also been clearly told to you, so there is no need to take tension, 0.25 has been so there is no need to take tension, 0.25 has been so there is no need to take tension, 0.25 has been given, it is okay and if you want to do the fourth operation, then do the fourth operation. If you see what is happening, you have to give 25 million of each but if you have only 5 children then there is no problem, give five of five, it is completed here, the same is written in the bill survey, as much as is possible, we give. Will give ok and we will stop when both of mine become zero, from here it is clear note date video note have an operation where 100 ml Rusev first see this is a very important line you will know at the end why he has told this line Okay and literally I don't like these kind of questions at all, it's okay because I had this doubt in the interview, you must have told all these things, these are discussed in the further discussion, such lines which are not discussed in the interview, just like a mother takes questions. Given that you have solved it, after that it comes in the further follow up, all this is fine, so the ultimate return D probability was soup A, bill B, first, okay, the question is so easy, isn't it, its logic is like this, which means you will not believe it is as big and long as the question, isn't it? It is not easy in the solution, it will be empty soon, it will become zero, okay, its probability has to be calculated, plus look, pay attention, plus half the probability, date from time, half the probability written from time, look at this line, which is written. Well, this is a head-spinning line, but it is Well, this is a head-spinning line, but it is Well, this is a head-spinning line, but it is so simple, let me tell you now, I am a little scared that you will come to know, okay, now pay attention to one thing, now answer some of my questions, I am telling you right now. Look at you how friend, see what do I have to calculate the probability that A which is empty means whatever A means A. Now remember how much was the quantity N was A. If A becomes empty then it means right N which is equal to zero. Let it happen and whatever quantity is mine, take it equal, you become zero because I have completely served A. Okay, if mother take only one quantity, it is already zero, it is already empty, then brother, what is the property, tell me, what is the probability, brother, already. Zero will be one if not already, I mean, I am saying that if the quantity of A is already taken equal to you are zero, then brother, what will I do, will I return one or not? Tell me, I will return already one cup of one. If there is only one A which is empty, then what will be my probability? It will definitely be one because it is 100% possible because there is only one because it is 100% possible because there is only one because it is 100% possible because there is only one A which is empty, it will be completely clear. Now pay attention to one more thing, look at this is a 100% very easy statement, you must have come to know 100% very easy statement, you must have come to know 100% very easy statement, you must have come to know that this is correct, right? Find out the probability that one is empty and if it is already empty then I will return one. I will do 1.0 because double. I am I will do 1.0 because double. I am I will do 1.0 because double. I am returning the answer. Okay, after this, the line that turned heads was this, whereas this line is actually very easy, plus half D probability, A and B, both are B, one T means, what are you saying? When A takes the bill of B, you become equal to zero and B also becomes zero. He is saying what is the return to be made in the immunity of this question. Understand first, if A is already zero then it will be priority one. If you have seen it here, then here also. There should only be one, brother, so zero should already be one, but one more thing has been added here, that both should be zero, and you know what has been said in it that 1/2 D probability, so halve it and said in it that 1/2 D probability, so halve it and said in it that 1/2 D probability, so halve it and send it, brother one. Bye you send it i.e. send it, brother one. Bye you send it i.e. send it, brother one. Bye you send it i.e. send 0.5. Try to understand why I wrote one here first. Think it will be one. Here it is but in the question it was said that if both become zero then you have to take 1/2 D probability. So what did I you have to take 1/2 D probability. So what did I you have to take 1/2 D probability. So what did I do, I took 1/2 i.e. it will return 0.5, do, I took 1/2 i.e. it will return 0.5, do, I took 1/2 i.e. it will return 0.5, even this would have been very clear. Okay, now coming to the third condition, now tell me one thing, it is very simple, I ask you a question, what is it to remove me? Tell me, I have to find out that when did A impati occur, meaning it is AMT, what is its probability, it is required, if A is empty already, it is already taken, if you are equal, you are zero, then you were returning one, because this is already zero, but if A is already B. If my turn equals you becomes zero, then I don't even want its property. I don't even want its product. Otherwise, I will make my turn zero. Look, in every condition, the matter is being discussed in the case of A. Here too, the matter is being discussed in the case of A. Here, A is being discussed in the upper case of A and B has also been said because in the question it has been said to do this, so this is why I have written B's here, it is okay and if it is BG here, then I should talk in its upper case. There is no question has been asked, so why would I add to B's property, brother, why would I add to his, by now it must be clear to you, now this thing is clear, a little more than what I have given in this first example. In the matter of probability, let us first understand that from the given example of liquid, I understand you one thing, look at this example, also see my first example, if you understand, then this is my first example, and here I write that A and What all operations of B have you said are possible? Brother, this is 100 ml, this is zero, this is 75, this is 25, this is 50 and this is 25, this is 75. Okay, till now it is clear. Now see if I did the operation first. The question is, what is the meaning of A? The quantity of If you want zero for B, then you can't give 100 for A. I already have only 85, so it's okay, give as much as you have, so in the question it was said, give as much as you have, then the whole will be zero in one go. One will end up okay and the priority of zero I know that one is very good, if I get the probability of the first operation, then this is one answer, then I got one probability, so I write p1, this is okay and I get all the operations. If I want to calculate the probability of A, then what will I do? I will keep adding everyone because this is one answer to zero. Let's see if we take the second operation, then A's 75 and B's 25. If we have to take 75, then look, it's gone. So this is it. If you have 50, if you can't take it then give as much as you have. If you have given 50 in full, you will give 50 in full. This has become zero again. One has come from here, this one is 50-50. What does it mean this one is 50-50. What does it mean this one is 50-50. What does it mean that now the BB of 50 is 50, so it is ok. Let's see, A got 50 and B got it, both became zero, now the question is now let's go to the fourth one, this one got 25, this one got 75. Okay, so look here, pay attention, A took 25, so how much did A lose, 25 eagles. went and asked B to take 75, if B took 75, he would not be able to take 75. If B has 50, how much will B go back? 20 will go back, because there is no 75, if there is 85, then B's entire money is gone and one If you take 25, then subtract 25 from 50. If you go back to 25, then look here, notice that A has not become zero, but B has become zero. I do not have to calculate the probability of B, so in this way, I have to return zero, this is also mentioned above. It was written to you that the priority number is four. What did I say that if B <= 0 then What did I say that if B <= 0 then What did I say that if B <= 0 then return 0.0, return 0.0, return 0.0, but a very important thing has been given in the question that the probability of tightening each operation is 0.25, so we have to multiply by it. is 0.25, so we have to multiply by it. So you will have to multiply, right? And see in the earlier example also he has multiplied by 0.25. Okay, so also he has multiplied by 0.25. Okay, so also he has multiplied by 0.25. Okay, so what am I doing? 0.25 * Probability what am I doing? 0.25 * Probability what am I doing? 0.25 * Probability of one plus 0.25 * Probability of two plus 0.25 * Probability of two plus 0.25 * Probability of two plus 0.25 * Probability of three plus 0.25 * 0.25 * Probability of three plus 0.25 * 0.25 * Probability of three plus 0.25 * Poverty. But either do it like this, 0.2 + p3 plus p, add all the priorities, + p3 plus p, add all the priorities, + p3 plus p, add all the priorities, after that multiply it in the last part by 0.25, this will give us our answer. by 0.25, this will give us our answer. by 0.25, this will give us our answer. Okay, so its code will also be very simple, the code will also be just written, whatever. The story has been told, look at the story, you can convert it into code by pausing now, see how simple its code will be, think about what I said that the function we have to calculate is only to calculate the probability of a getting empty, so I will not write the name of the function. I give the probability that B has had a child and what is the quantity of B has had a child. It is simple. If it becomes zero, then I want only that return one. I told you this above, right here, this one, I told this and this one. I had also told you that if 20 becomes zero then I do n't want it, I will make it 0.0, here I will make it 1.0, okay 0.0, here I will make it 1.0, okay 0.0, here I will make it 1.0, okay and by not doing internet here, I will make double return here, it is clear till now, after that Pay attention to what I said that we had tax operations, so I have stored those four operations in a vector, I have stored them here, okay, what was the first operation, A was 100 and B was zero, the second was that A was 75. And after this 25 and B's 75, doing the same operations are possible, so I have put a loop on the operation, but auto, I have taken out the let first, that brother, I have kept the variable till here, probability is equal to 0, just add. I have to keep doing probability plus is equal, you are ok, tell me there was nothing hard in this question, just the problem statement don't think was a little ok and it is also very easy to memorize because only two variables are changing, are n't two variables changing? If so, then we will memorize it easily, but one problem will come, let's try to memorize it and I will tell you what is that problem, then you will know the meaning of why this thing is kept in the last, okay, so first of all this is this. Let's try to memorize by writing this recognition code. Now literally the question must be very simple to you are just trying to understand it, but this question has got a lot of dislikes, you notice the reason for that too, I will tell you that it is a very bad one. There is a thing in this question which I will tell you in the last, okay, so first of all, I will write a simple one, do not give the name of a big function, we have only one quantity N and the quantity of B is also N, okay Okay, now look carefully, I first told you that if A is equal to zero and B is also equal to zero, then half the probability becomes 0.5 <= 0, then we want this, otherwise becomes 0.5 <= 0, then we want this, otherwise becomes 0.5 <= 0, then we want this, otherwise how can it be 0.0? Will return, okay, how can it be 0.0? Will return, okay, how can it be 0.0? Will return, okay, after that let's take a variable in which I will add all the probabilities. Okay, and remember I told you that there were tax operations, so I will define that here too and give it on the vector off. First of all, what was 100? Comma zero, what was there after that 75 comma 25 What was there after that 25 comma 75 It's okay by doing this operation So okay let's calculate, let's keep adding to the probability plus this is equal, you solved it earlier - Kitna nikal liya is earlier - Kitna nikal liya is earlier - Kitna nikal liya is Once served A - A was taken and B was taken and Once served A - A was taken and B was taken and Once served A - A was taken and B was taken, from here we have taken out 0.25. If we want to multiply all of them, then we 0.25. If we want to multiply all of them, then we 0.25. If we want to multiply all of them, then we took out all of them once and multiplied them in the last one. Let's see the example, time limit is same or So it will give some issue, it is okay, late C, what issue comes because you see there is a big constraint of N, the power of the tank is 9, okay, so now look at the power of the tank itself, from nine, I saw a glitch because see, if I will also do memories A and B, so I have taken a vector of two dimensions, I am fine and first check here, aa sorry, here we will check that IF T of A B, note this is equal to minus one point zero means that state is solved. First of all, return T of AB, okay, and before returning here, return AB, okay, now see what will be its time complexity, see N, what is its dimension, N cross N, right, N + 1, either and either. N cross N, right, N + 1, either and either. N cross N, right, N + 1, either and either. N + N, this is N, let's go to the mother, so n², N + N, this is N, let's go to the mother, so n², N + N, this is N, let's go to the mother, so n², how many will be its total status, how many total sits will be n², so what year will we visit n square status, okay and brother, look at the maximum value of n, tank and nine is nine to the power of 10. It is not possible that this solution is acceptable to you. Look, I have run it and seen that it will immediately fail for a very large value of m. We are taking up so much space. The value of n is so big and so big. Now you will not be able to make vector. Okay, so brother, there was a lot of bed for this, but this solution, now tell me dog, this is also an acceptable solution. In the interview, they will be already impressed by you. Yes, now they will follow up that the value of N will be big. So what will happen, okay, now let's come to it, okay, now see, from our farm, no mimogation, flower imagination has also failed, okay, so now see how to handle it, first of all, let us tell you that the official lead code. Don't look for the solution. Big conjuring solution is fine. I told you the simplest solution which I found. It is fine here but the lead code has also taken a particular value that if it finds anything bigger than the particular value then it directly returns one. But do n't look at him as his solution. Okay, but let me tell you, I will try from my side to understand how to handle someone. Okay, look, I told you in the beginning that this statement I have given is not in reality. What is the significance of this, it is clearly stated here that they do not have any operation where 100 ml is consumed first, what will happen to them in any operation where 100 ml has never been spent in one go. No, this has never happened, okay, so as N gets bigger, look at the water of A. One thing is clear that B will never finish 100 at a time, okay. One thing, I came to know that second, it will be easier to finish A quickly, because look, there is 100 in A, there is 100 for A, so finishing A will be a little, compared to S, you are B and as soon as N is my big. It will continue to happen in the same way, it will become difficult to finish B quickly and this means that its priority will keep decreasing. If the priority of finishing B is decreasing, what does it mean that the priority of finishing A will flood? I am telling you again, N. Look, B will never finish completely in one go. Okay, and as it means, what does it mean that A has a higher priority to finish quickly? A is easier to finish, and so on. As I will grow bigger, it will become more difficult to finish B first. Okay, that is, the probability of finishing A will become approximately one, very close, you will become one, it will become 0.999, this is how I do it, you will go through it. You 0.999, this is how I do it, you will go through it. You 0.999, this is how I do it, you will go through it. You can also try and see the value of N. You keep increasing, let's go to 8000, let's go to 9000, let's see, the product of A becoming zero, you will close, you will become one, a time will come when the absolute value will be exactly equal to one, it is a relief. It will keep happening, okay, so now what is the point of this, you cannot sit in front of the interview and say that if the value of N is ≥ 5000, then I will always if the value of N is ≥ 5000, then I will always if the value of N is ≥ 5000, then I will always return priority one. If you are close to one, then I will return one. Because you don't know how this ₹ 5000 came, okay now there how this ₹ 5000 came, okay now there how this ₹ 5000 came, okay now there must be some maths behind it which is completely out of our scope right now, we do n't know that much in depth in maths because right now we are studying DP, okay But you can definitely tell them that as the value of N increases, the chances of it finishing first will reduce further, which means it will finish first and the priority of finishing only one will become closer to one. So how will we make it a return band and here I don't forget 5000, you tell me that big n is ok but now we have to submit today's lead code challenge, so for that I will tell you the value of n is greater than equal. You keep checking, make it 5 thousand once, make it ₹ 6000 once, make it ₹ 7000 once, by doing this I make it ₹ 6000 once, make it ₹ 7000 once, by doing this I make it ₹ 6000 once, make it ₹ 7000 once, by doing this I think it will become less than 5000 and now we will do it and see, if the value of N is more than 5000 then it is okay. Now I do n't need to do any memorization, I will return this one at this time. Okay, let's try it. Let's try it here and see what value of N should be kept. So I am late looking here. If those If the value is >= 4000, then I If those If the value is >= 4000, then I If those If the value is >= 4000, then I will return one here, if the one bigger than that comes then I don't need to do anything, ok, let's see once it passes or not, ok, submit it and see if it passes. It's good, you have passed it, right? And I think you will increase it even more, either make it 5000 or even 5000, even then it will definitely be a dog and the probability of getting the same finish is getting less and less. And see. My time is running out as I am doing return one for 5000 cases ok any doubt resident comment area ultra next video thank you | Soup Servings | number-of-matching-subsequences | There are two types of soup: **type A** and **type B**. Initially, we have `n` ml of each type of soup. There are four kinds of operations:
1. Serve `100` ml of **soup A** and `0` ml of **soup B**,
2. Serve `75` ml of **soup A** and `25` ml of **soup B**,
3. Serve `50` ml of **soup A** and `50` ml of **soup B**, and
4. Serve `25` ml of **soup A** and `75` ml of **soup B**.
When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability `0.25`. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.
**Note** that we do not have an operation where all `100` ml's of **soup B** are used first.
Return _the probability that **soup A** will be empty first, plus half the probability that **A** and **B** become empty at the same time_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** n = 50
**Output:** 0.62500
**Explanation:** If we choose the first two operations, A will become empty first.
For the third operation, A and B will become empty at the same time.
For the fourth operation, B will become empty first.
So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 \* (1 + 1 + 0.5 + 0) = 0.625.
**Example 2:**
**Input:** n = 100
**Output:** 0.71875
**Constraints:**
* `0 <= n <= 109` | null | Hash Table,String,Trie,Sorting | Medium | 392,1051,2186 |
4 | today we're going to solve a tricky coding interview problem median of two sorted arrays you're given two sorted arrays namson and nums to upside m and in respectively return the median of the two sorted arrays we can solve this problem pretty easily by merging the two sorted arrays but the constraint to this problem is that we have to solve this problem in logarithmic time complexity which makes this problem critical to understand so what is a median if you are given a sorted array the median is the middle element if the length of the array is even then the median is the average of the middle two element for this array the median is 3 plus 4 divided 2 which is 3.5 and for the array 3.5 and for the array 3.5 and for the array of odd length median is the middle element here 4 is the middle element so for this array 4 is the median so basically median partition an array into 2 equals half for this array we see the median is 3.5 all the element on the left 3.5 all the element on the left 3.5 all the element on the left are less than 3.5 and all the element are less than 3.5 and all the element are less than 3.5 and all the element in the right greater than 3.5 in the right greater than 3.5 in the right greater than 3.5 so we see that this number 3.5 so we see that this number 3.5 so we see that this number 3.5 partitions this array into two equals half on the left we have three elements on the right we have three element and in this array we see we have median for this four partition this arrange two equals half on the left we have three element and on the right we have three element and the element on the left are less than the median and the element on the right are greater than median if you are given two arrays num s1 equals to this array and nums to equals to this array now how we can find the median of these two arrays first let's merge this to array if we merge this two array then we get this array in this array we have to find the median the length of this array is even so the median for this array is the average of two middle elements so 15 plus 16 divided 2 that is 15.5 15.5 15.5 so for this two arrays we have to return 15.5 we can solve this problem pretty 15.5 we can solve this problem pretty 15.5 we can solve this problem pretty easily by merging these two sorted array into one array then we can find the middle element depending on the size of the merged array for even length will have the average of two middle elements for odd length we'll have one middle element for this array we have two middle elements 15 and 16 and the average of this two element is 15.5 so element is 15.5 so element is 15.5 so for this two array median is 15.5 for this two array median is 15.5 for this two array median is 15.5 how we can solve this problem in logarithmic time complexity let's suppose that we are given num sun equals to this array x1 x2 x3 x4 x5 and x6 and nums2 equals to y one y two y three y four y five y six now our goal is to partition this two array such that they follow this condition x three is less than y4 and y3 is less than x4 we will partition this array in such way that we get this partition okay if we can get this partition what does this really mean it means that every element in the left partition is less than y4 so this element and this all element less than y4 and every element on the right is greater than y3 okay and also for here every element on the left less than x4 and every element on the right is greater than x3 if we can find such partition that follows this condition then we can find our median so for even length we'll have median max of x 3 and y 3 plus mean of x 4 and y 4 and the average of them using this formula we can solve this problem so our goal is to partition two sorted arrays in such a way such that they follows this condition every element on the left is less than x4 and y4 and every element on the right is greater than x3 and y3 now let me summarize our goal is to partition the two sorted array in such a way such that all the element on the left are less than x4 and y4 and every element on the right is greater than x3 and y3 if we can found this partition then we can return the median using this formula we can use the same logic for different length of array if we are given namsun uncles to this array and obstacles to this array we can use the same concept to partition this array here also we'll apply the same logic we'll partition this two array in such a way such that the follows this condition then we will return max left the max left in the sketch x3 or y3 okay and we can get that by using max of x3 and y3 all right so here what do we see that if we can partition that two given arrays in such a way that follows this condition every element on the left x4 and y4 is less than x4 and y4 and every element on the right of x3 and y3 are greater than x3 and y3 then we can find the median using this formula okay now our goal is to partition the 2 array that follows this condition now let's see how we can solve this problem using some example this is our blueprint to solve this problem we assume that we found the perfect partition for this two array and that follows this condition and we'll use this logic to solve this problem all right suppose that we're given this array of length six and we're given this array of length six so we have here two sorted arrays now our goal is to partition the two array in such a way that follows this condition to partition this two array we're going to use this algorithm so first mean equals to zero and imax equals to length of the first array all edge is going to be the array of minimum length if the length of two arrays are not the same then we're going to calculate the half the length of the two array plus one divided by two and then i equals to i mean plus i max divided two then z equals to half minus i if we partition this array then i mean equals to zero i'm x equals to six happy goes to six i equals to three is equals to three and you can calculate this for this two array i points to this index three and z points to this index three so we're going to partition this array right here in between index two and three and for this array at here in between index two and three i mean points to the first index imx points to out of our arrow boundary now we have i in between i mean and imax now let's apply this logic does y3 is less than x4 here this is y3 and 15 x4 does 18 less than 15 no then what we will do we will apply this logic so we will move i mean to i plus one so i mean will point right over here when i mean change its position we have to calculate the partition again all right i mean points right over here when we have i'm in equals to four and i'm x equals to five then we have here this value we can calculate that for this two array so in this case we have i equals to five so i points to this element 17 so we're going to partition this array right here then we have z equals to 1 so z points to this element 11 at index 1 then we're going to partition this array right here now let's apply this rule does y3 less than y4 7 less than 17 that is true okay so this condition false then let's check this condition since this condition is true so we will not move i mean then let's check this condition does x3 less than y4 does 16 less than 11 no this is false for that we're going to move imax to the left of our i okay we see that this condition is true x3 is greater than y4 16 is greater than 11 so we're going to move imax to the left of i and the laptop i is i mean so let's move imax right here so i mean pointing to this index for also imax pointing to this index four and let's calculate i and z so we get i equals to 4 and j equals to 2. so we're going to partition so i points to this index 4 so we're going to partition this error right here we have z equals to 2 is a point to this index 2 and we're going to partition right here now let's check this two condition this element is greater than 11 and this element 15 less than 18 so these two quantitation falls here so will not move neither i mean nor imax we see this condition mass here all the element in the left partition of 16 and 18 are less than 16 and 18 and all the element on the right partition of 15 and 11 are greater than 15 and 11 so we found the perfect portion now we're going to apply this logic here we see the sum of the length of the two array is an even number so we're going to use this formula to calculate the median so let max is 15 and mean right is 16. so 15 plus 16 equals to 31 divided 2 equals to 15.5 31 divided 2 equals to 15.5 31 divided 2 equals to 15.5 so we have the median for this two array 15.5 15.5 15.5 if we merge these two array then we see this array right and the median for this area we see the average of 15 and 16. and what we get here okay so we have found the median of the two sorted arrays in logarithmic time we can use this concept to calculate median of two sorted arrays now let's see when we have the different length and we might have s cases let's see how can solve that problem we have here blueprint right and this is your algorithm to partition the given array and here we have the partitioning result so we are given this two array num so equals to this array and obstacles to this array we calculated this partitioning result already so let's apply this i points to 2 so i mean 0 then i'm x4 i mean point to this index 0 i'm x pointing to the outside upper array then i equals to 2 so i points right here so we're going to partition this array right here then j equals to 4 so the point here we're gonna partition zero right over here okay now let's apply this logic and this is our algorithm okay let's check this element and 9 does 31 is greater than 9 yes it is so let's check does 11 is greater than 26 no this is false since this is false this condition apply here so this so i max equals to i minus 1 so imx points to this element when you see i'm exporting to the index one and i'm in pointing to the index zero so i'm pointing to the index zero so we're going to partition right here z equals to 6 is a pointing here so we're going to partition right here on the left we have no element on the partition of the first array so we have nothing to compare here does 23 is greater than 16 yes it is so this two condition falls here we don't need to move i mean or imax all the element on the left partition of 17 is less than 17 and all the element on the right partition of 16 is greater than 16 so we found a partition when we see i points to 0 then we will return the left max that means the maximum element on the left partition and that is 16 okay and we'll use this code to do that we will see that how it actually works when we go through pseudocode and if we merge this to array then we get this array here we see we have 16 all right and we get here also 16. so our median for this two sorted array is 16. to better understand this problem try with different examples then it will make sense if you aren't understanding this video explanation don't worry try with your own examples and apply the same logic i'm performing here now let's see how i can solve this problem using pseudocode first we're going to declare a function median that takes two array as input num s1 and numstro then we're going to find the length of the two array if the length of the two array are not the same then we're going to call a function find median with the two array where the first argument the array of minimum length if we see len 1 is greater than 2 then we call these functions by providing the numbers to array as the first argument if not then we're going to call this function with num so and nums2 so this will be the array of minimum length so now let's see the implementation of this function find median first we're going to delete a function find median that takes to array a and b where the length of this array a will be minimum if the length of the two array are different then we are going to find the length of the two array m equals to length of array a and n equals to the length of the array b then we are going to declare i mean i we're going to calculate the hub then we're going to run a loop while i mean is less than or equals to imax then we're going to partition the first array using this logic we already have seen in the slide right then we're going to partition the second array then we're going to check and this is the boundary cage uh if we see this condition is true then we will move i mean to i plus 1 what does this mean it means that on the left partition we don't have all the element less than our right partition okay then we're gonna check this condition this is boundary check and here we're checking if the element on the right partition is greater than whatever element we have on the left partition for two arrays not for only one array okay then we will move imx to the left of our index if not then we're going to find the median okay this is for lift max if we see i is zero then we will have left max on the second array all right if we see z equals to zero then we will have litmex on the first array to understand this problem you should go through with your own examples if not then we will find max upper left partition then we're going to check if the sum of the length of 2 array is an odd number that will return the max left if this is not true if the sum of the length of the two error is not an odd number we're not gonna declare right max equals to zero then we're gonna check if i is equals to m then min write is exist on the second array if z equals to n the min right exists on the first array if not mean mineral equals to the minimum element we have on the right partition at the end we'll return the average of a max left and min right this will applied when we have the sum of the length of two array is an even number if not then we will only return zero point zero okay now let's see how this actually works let's assume we're given num some equals to this array and nums equals to this array first our goal is to partition the two array okay so we have i mean equals to zero i'm x equals to m i'm x equals to the length of the array is six so zero plus six divided two is three so i points to three and zip points to three as well because half is happy equals to six minus i equals to three so we're going to partition the first error right here and the second error right here so we have here i mean that points to zero and we have imax that points to the outside of our array then we're gonna check does 15 is greater than 18 no so we're gonna move i mean to the index plus one that will point to four you see we have already calculated here for better understanding okay so let's move i mean right here and we have already calculated the partitions for this two array and here we have the value then we're gonna check that 17 is greater than seven yes it is then let's check does 11 is greater than 16 no so this l tip works here so i max is points to this element 60 so imx point right here and we have already calculated the value of i and j to partition the two array okay i point here and j point here so partition this array right here and i right here now let's check the 16 is greater than 11 yes it is does 18 is greater than 15 yes it is so we found a perfect partition now our goal is to find the median so the maximum of this 2 15 and 11 is 15 and that's what we're doing right here so let max equals to 15 and this condition is false here because the sum of the length of the two array is an even number not odd number then right max the minimum of 16 and 18 is 16 so 15 plus 16 all right we found let max equals to 15 and right max equals to 15 all right then we're gonna return the average of this two and that's equals to fifteen point five so for this two array we'll have our answer 15.5 and this is how we can our answer 15.5 and this is how we can our answer 15.5 and this is how we can sublime i know this problem bit of exaggerated in order to properly understand this problem use the concept i shared in this video to understand this problem and use your own examples to see how it actually works the solution will takes big of log minimum of m and n where m is the length of the first array and n is the length of the second array and this solution takes constant space complexity since we're not using any additional space here we're just using some variables hope this concept was clear if you have any question if you have any suggestion let us know if you have understood this problem let us know thanks for watching this video i will see you in the next video till then take care | 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 |
258 | hey this is tover with a lonely Dash and today we're going over leap code question 258 add digits which says given an integer num repeatedly add all its digits until the result has only one digit and return it for example if you're given a number 38 we know that the output is going to be 2 because 3 + the output is going to be 2 because 3 + the output is going to be 2 because 3 + 8 is 12 wait let's see 3 + 8 is 11 sorry 8 is 12 wait let's see 3 + 8 is 11 sorry 8 is 12 wait let's see 3 + 8 is 11 sorry and 1 + 1 then is 2 right so 3 + 8 11 1 and 1 + 1 then is 2 right so 3 + 8 11 1 and 1 + 1 then is 2 right so 3 + 8 11 1 + one is two since two only has one + one is two since two only has one + one is two since two only has one digit then you can return it uh the other example they give you is if they give you zero oh obviously there's only one single digit so it'll end up being zero um when I first looked at this question I sat there and thought oh because of the examples we're going to have to take apart even if it's a really long integer add each and every number together every time we don't have to do that we can do this recursively and it'll be lovely but then when I got to the bottom of the question it also asks could you do it without any Loop or recursion in 011 time uh and I thought to myself no I can't until I figured out how so for our question today we're going to solve it in two different ways one using recursion and the other one solving it mathematically uh okay so here are our two examples so first is recursion the second is math recursion this is really kind of a simple example or a simple answer basically all we're doing is taking the final digit and we're going to be separating the final digit from the rest of the question and we're going to be adding it to the rest or sorry rest of the number so we originally started with 23851 now we're just going to be adding 1 to 2385 which we know to be 2386 then we're going to take this number and we're going to just add the six to 238 which we now know is 244 now we're just going to separate the last digit and we're just going to do this by dividing and using modulo right so if we take 244 which we've done up here we divide it by 10 we get 24 if we modulo 244 we get four so we're just adding the modulo to The Divided number uh and then of course we get 28 so 28 divided 10 is 2 and 28 modulo 10 is 8 so 2 + 8 is 10 uh which if we add 0 to so 2 + 8 is 10 uh which if we add 0 to so 2 + 8 is 10 uh which if we add 0 to one we know we get one so we want to make sure that we've done this correctly I like using Microsoft's calculator because if you come up here there's a little programmer button and so we're going to type in the original number which was up here uh there we go make sure I type it in right we've got 23,8 23,8 23,8 51 uh and we are going to what am I going to do what did I say I was going to modul okay modul 9 and we'll explain how this works in a second and so one is the correct answer now what did I just do I basically just took a number 23,8 51 and I moduled it by 9 and just 23,8 51 and I moduled it by 9 and just 23,8 51 and I moduled it by 9 and just got the remainder which was one and this is how we're checking uh whether our recursion worked but it's also how we get our mathematical answer our second answer and the best way I can kind of explain this is that we know that the root of any number whose digits add up to nine is 9 right so 81 8 + 1 is 9 to nine is 9 right so 81 8 + 1 is 9 to nine is 9 right so 81 8 + 1 is 9 uh 4 + 5 is also 9 so if we are thinking uh 4 + 5 is also 9 so if we are thinking uh 4 + 5 is also 9 so if we are thinking um that we are looking 81 modulo 9 a root is going to be zero right so that's fair enough we've got 45 modulo 9 uh it's also going to be zero because 9 divides evenly into both 81 and 45 and this is the case in every single number where digits add up to nine all numbers whose digits add up to 9 our modulo 9 oh equal 0 not 9 0 equal 0 there we go therefore and I know this math kind of seems weird the difference in a number modulo 9 will be the result so the example we just did here was our 23851 modul 9 was 1 but let's think about it just a smaller number just to double check ourselves well 56 okay 5 + double check ourselves well 56 okay 5 + double check ourselves well 56 okay 5 + 6 is actually 11 uh okay 1 + 1 cuz 6 is actually 11 uh okay 1 + 1 cuz 6 is actually 11 uh okay 1 + 1 cuz that's 11 equal two so we know the answer is going to be two but if we double check ourselves 56 modul 9 the result is two bam very easy so even though the question kind of starts off by saying hey we're going to be adding all of the digits until we have only one digit left well if we do that's basic mathematics uh so it's a super misleading question but for our purposes today we're going to solve both of them using recursion uh and using math so hang tight we're going to take a look at our constraints and see if there's any edge cases we're going to need to consider literally the only constraints that are put on this question are that the number provided is going to be zero or greater and less than 2 to the 31st power minus one so it's not going to be an enormous number it's not going to be a large number but it's something that we're going to be able to deal with so um as long as it's not negative right because that will work slightly differently as long as they're not negative we'll be okay with the two solutions that we're working with uh so let's take that and uh let's get to some pseudo code okay so for our pseudo code we're going to start with our recursive answer and the first thing we need to do is make a determination if number is less than 10 right so if the number we're given is less than 10 then we don't need to do anything because it's only one digit in length we just return the number that we were given great uh otherwise that'll be our else um it means we're have a number that's greater than 10 so we need to remove the last digit from num and then add it to the new num right so we're just taking the last digit off that gives us a shorter num and then we're just adding that those two new integers together pretty simple and straightforward uh now uh what do we need to ask the question again if num is less than 10 then we can return num otherwise that's going to be our another else otherwise well we just need to run the algorithm again okay and that's the recursion we're just going to run it over and over again until at some point our number is going to be less than 10 and that's going to be our answer so this is our recursive pseudo code but our mathematical one also needs to be figured out and it's pretty simple they're almost identical in some ways so the first question we need to ask is if our number is less than 10 what do we return our number very simple uh but what if our num uh can also be divided by 9 right if it can be divided by 9 and there's no remainder then we can just return n right because that's what we talked about uh 8 + 1 is 81 it's N9 so the about uh 8 + 1 is 81 it's N9 so the about uh 8 + 1 is 81 it's N9 so the answer is nine very simple and straightforward uh otherwise that's else if it can't be divided by nine with a remainder of zero if it can't be done uh we're going to return the remainder of the number divided by 9 and that's it that's the entirety of the pseudo code for our mathematical answer so we've got our recursive answer we've got our mathematical answer let's take both of these options copy and paste it and let's get coding okay here we are working in the Java lead code area of the website and we're just going to go with our recursive answer right off the bat so I'll make sure I'm lined up here properly I could do that so recursive answer if num is less than 10 we can just return num so that's just if our number is less than 10 uh we can return num and all that is saying is if our digit that we are provided is less than 10 it's single digit long we don't need to do anything let's just return it um otherwise it is longer than our on digigit requirement so we need to remove the last digit and then add it to the new number so I'll tell you what I'm just going to write this out and then kind of explain it when we're done so num is equal to num / 10 uh plus num is equal to num / 10 uh plus num is equal to num / 10 uh plus num modulo 10 okay so all this does is say okay hey we're going to take our number and we're going to modul it by 10 and that's going to give us the remainder as if we divided it by 10 so this gives us the very last digit so for example if the number had been 678 then when I modulo this uh by 10 it's going to give me 8 and if I divide 678 num divided by 10 it's going to give me 67 so right here it's telling me hey you got 67 + 8 here it's telling me hey you got 67 + 8 here it's telling me hey you got 67 + 8 that's exactly what this line does here and that's going to reassign number that value so we've removed the last digit and we've added it to our new number now if the number is less than 10 we can return it and interestingly that's exactly the same code that we just wrote up here uh it's going to be kind of repeated a lot as we write it through um and then if by now it is still not one digit in length we're just going to have to call our add digits algorithm again so we're going to return add digits num bam done right so we've asked is it one digit in length if it's not we're adding the last digit to our number or ask the question again and if it's still not we're going to do it all over again we'll hit run see how we did and 0 milliseconds that's pretty good we'll hit submit see how we did against the rest of the cases I'm going to guess it's pretty darn fast so we beat 100% of users with Java and 70% but beat 100% of users with Java and 70% but beat 100% of users with Java and 70% but I'm going to guess this isn't really all that accurate um simply because I think this is the normal way that people will solve this question because we also have our mathematical way of solving it and we're going to give that a go and I think it might be faster uh don't know yet we're going to give it a try so let's comment out our recursion and try mathmatical and interestingly the very first part of our mathematical answer if numbers is less than 10 we can return num is the exact same first line as our uh recursive answer there we go okay got it on there now if the number can be divided by nine we're going to return nine okay so that's uh if we're going to try this num modulo 9 equals 0o uh-huh then we're going to 9 equals 0o uh-huh then we're going to 9 equals 0o uh-huh then we're going to return 9 okay so this is basically just saying if we divide our number by nine and there's nothing left over then we're going to return the number nine pretty simple otherwise and we're down here return the remainder of our number divided by nine so that's just going to be an else we are going to return uh num modulo 9 because that's just going to be whatever is in the remainder so that's that we're going to hit run make sure I didn't make any mistakes okay still zero milliseconds seem to take longer though which surprises me we're going to find out here come on oh wow it is slightly slower I don't believe it I going to hit submit again and just see if our mathematical solution is better um no it's pretty adamant that it's not as fast uh I am very surprised by that well we did reach 100% again this time uh but we did reach 100% again this time uh but we did reach 100% again this time uh but apparently it's not as memory uh useful as our recursive solution but if it were me and I was in I don't know some type of interview trying to solve this question for my interviewers I would definitely go with the recursive solution first um it's kind of the obvious solution that it seems like they're leading you to and then they just kind of challenge you hey could you do it without any loops and you're like oh crud okay there's got to be a mathematical way of doing it that's what this is but no harm no foul either way if you're doing it if you're solving 258 using Java this is the way I'd go | Add Digits | add-digits | Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime? | A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful. | Math,Simulation,Number Theory | Easy | 202,1082,2076,2264 |
81 | so there were no duplicates but today in the question the second part of it does not necessarily connecting with the distant value so they say that it's like I need the tickets as well so here you could say array sorted zero one two five six so two is similarly in this example also array need not to contain duplicate elements so with the same code of the unique elements code will work here no there is one Edge case which will add everything else Remains the Same so the if you haven't checked this video yet I have given the video link in the description box so please refer that and then come to this video right so if we are doing the normal way so this will be low and this will be high so mid will be over here so usually what we were checking here so we used to check whether Lewis is an equal to my then in this condition otherwise this condition will make this lesson are equal to high that means which part of the array is sorted so either low temperature mid to high sorted we could see 5 is it less than or equal to no so this is not sorted but 2 is less than equal to 4 so this part is sorted but this one is not sorted hence what we need to do we have to check whether the element is present here or not we used to do that so that works here now same pool and working so this is okay next we will go to this case now so here in the in between the array duplicate elements so if you see this example at the end of the array duplicate elements are present right so now we will again Mark the loop and hi and let this beam item so now I have to check what again same condition where the lowest lesser liquid high no it's not circuit here whether mid is equal time yes who is part is short again we have got definition so even this both the code works with the same code as a rotated sorted array with the decent elements now we will go to the last so here it is low then hi so here map will come here one okay this is good the same condition here also is it low less than or equal to it yes it is given that condition also satisfies so how do we get to know that which part is sorted or not Hollywood okay if low distance are equal to it then we will do this otherwise we do this the rule let's say I'm going to quit but this part is not sorted so what do we need to do so what we'll do is we will print down the question itself we could see three and three are equal so what we do is whatever the repeating numbers same duplicates are present in the end of the array we will cut down that so cross Three cross three and point row here I here now once again check whether 3 and 3 are equal same number are present in the end of the PS low and high yes it is now if you see the question one comma 2 comma 3 comma one comma two comma three foreign change between improved and we have to do is before doing this part right so if the meeting is equal to Target derivative then you can return that you need not to trim down that side so if wind is not equal Target then you have to check for this connection so that connection will be length so array of low equal to array of net click add array of mid foreign copy the same code okay so if mid is not equal Target then here you have to check so here you have to check if terms of low equal to nums of milk nine amps of milk equal to terms of 5. so if this becomes true then low equal to low plus 1 then high will be equal to 5 minus 1. so later you have to give continue if there is still exists this condition then you have to delete that as well so we will run this just a second because the mistake here is we have to return either true or false but in this question you have to return if the target is present that index will return so instead of index if you find the element then so if you don't find it at the end we write down false yes and for Java also it's a same code only instead of size you have left so we'll submit this also he has successfully submitted if you understood the concept please do like the video and subscribe to the channel will come up with other my next question until then keep playing thank you | Search in Rotated Sorted Array II | search-in-rotated-sorted-array-ii | There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why? | null | Array,Binary Search | Medium | 33 |
162 | hello everyone so in this video let us talk about a very standard and very important problem the problem name is find Peak element so let us talk about the problem shipment first and then understand how we can solve it out problem shipment goes like this that you given a peak element is an element that is strictly greater than its neighbors okay now you given a zero index integer array nums find a peak element and return its index if the array contains multiple Peak return the index of any of the Peaks and you just have to find out that you can also imagine that the two extremes of the arrays are minus negative which means that you are like very deep point so just assume that they are very uh like infinitely negative points and uh like you can consider always any element always considered to be strictly greater than its neighbors outside the we must have toze an algorithm to run it in log in time whenever you see login time I generally try to think it in some sort of a binary search because binary search can do that in Lin time uh given to find out some elements inside some array uh like I possibly try to think in that direction but let's some see some examples let's take this as example and the oral thing we'll also understand it by drawing it out as well so let's say that we have uh some Peaks and trots so you can see that uh okay so I like 1 2 3 4 5 and six okay so the first point is one the next point is two the next point is one the next point is three next point is five then six and then four so this is how the actual things look like okay so as you can see that there are two peaks this is one of the Peaks the peak is that any element whose left and right are smaller than so as you can see for this element the left and the right are both smaller so this is one of the possible PS can be here as well now how can it use binary search and like try to find it out so what do actually binary search do binary search comes closer to the Final Approach like uh binary search can only work you can say when you actually have some sort of this pattern only okay why by pattern I means that it some it tries to converge to a particular Point okay um uh a you can say a local Minima or local Maxima a point okay that is what B search is very capable of finding out a possible best scenario among all the scenarios so it has all the scenarios like this can be a point but whatever is a point that we're looking for that can be used to find out by binary search now how can I use that so what binary search is capable of so let's say we have two extremities I'm just giving you a very small example of what B search is capable of and then we try to expl it to this example so we'll come to the middle in binary search with the two L andr we have L and R the extremities we come to the very middle check out whether the element I'm looking for is in the middle if not then we'll check out whether we should go to the left side or right side and we try to converge to a part that's it okay now try to exp explorate this particular thing to here as well we either can be on the left side of the Hill or the right side of the Hill it simple if we somehow doing binary search over this array let's say this are defin this we somehow let's say land on this point that is three let's say this point if I land on any point the oral original idea is that either we can be on the right side of the hill or the left side of the Hill how we can check that we can check it by comparing it with the two neighbors if the element dent I have I am on if the right element of it the next element of it is larger and the previous element of it is smaller which means that I am on the left side similarly if I land upon let's say this point and if the element on the you can say right of it is smaller and the left of it is larger then which means that we on the right hand side and based upon that if we are on the top Point how we can know that both of its neighbors are smaller so if you're on the top Point both of the neighbors are smaller if this condition is meant we have to go somehow on the right hand side because the right hand side if we land upon this point our Peak will be on the right hand side but if we somehow land Upon This Side of the Mountain or yeah we have to go on the left hand side and we have to keep on doing this iteration until we hit the point of the peak that's it that's the complete Logic for this particular problem I'll show you with the quote part now but if you still have any doubts you can rewind this particular video I put that in the comment box I will try to solve and try to give as many supplies okay so uh that's the complete logic that you have to use so let's remove some part out and then we'll see how we can understand it here as well let's start remove the complete dra and see so what you can see here is that we are doing a binary search in B search we defined out the limits so we have defined out the limits L and R the two extremities then we'll completely do a while loop until we find out the peak so we'll do a y Loop because do not know how many iterations we'll do so we'll do a v Loop and the iteration V Loop condition is L should be less than R because L and r are the two extremities of the area we are finding out and we keep on like you can say decreasing the limit until unless like keep on decreasing the limit until we find out our complete Peak okay so if this overlaps like if they cross out each other we should stop so lnr find out actually uh our range okay we find out the middle element we can easily find out the middle element now our condition is that if we land upon the element that we're looking for okay that is the element that should be a peak element so the peak element has this condition now let us understand this condition we all we understand that the peak element it says that the left of it is smaller the right of it is smaller the left of it is smaller if it exist that is one thing what we are given is that the minus one index and the very last index the N index are already Infinity which means that they are already very small so we can always assume that they're small so if the minus one index mid is the element I'm on let's say I'm on this element if the minus one element exist if it exist and if it is smaller if it doesn't exist because it is an or if it doesn't exist then we already assume that it is smaller so we just leave it so this condition just check that the left element exist and if it is smaller if it doesn't exist it is already smaller how we can Des exis if I on the very first element if we are assuming that the very first element is the peak element then it is also fine because let's say that the array has only one element it has only seven that is also fine because if it is only seven the minus one element and the nth element are already minus negative which is already like very small so this should be upal I hope you understand the logic here so if the left element exists it had to be smaller if the right element exists it has to be larg like smaller as well if both of them smaller then the element I'm on is the right element it has to be a peak element return that we just got the if not we have to find out that whether I am on the left side of the mountain or the right hand side how we can check out if the like mid plus one which is the right hand element if it exist and if it is larger if it exists and if it larger which means that I have to somehow go to the right hand side and if I go to the right hand side the range should be such that my L should be becomes mid plus one and if you have to go to right like left hand side R should be like midus one but I should not make it midus one why because I have to somehow converge to a point and the converging if I make like uh the point can be missed if I make mid plus one andus one like this is a very standard thing that you have to only make one L equal mid + one and right make one L equal mid + one and right make one L equal mid + one and right should be mid only it converges to a particular point in the end what if he just somehow got the point it will return here if not the answer will be it's a very standard I have a complete series on binary s you can watch out that particular thing I have used this particular logic again and again there that how you can do B sour to kind of things but I will also put that in this particular I will put this problem in that particular uh you can say playlist as well so go check it out I will also put that in the description so I have complete very big playlist of b s you can learn it from very St and that's how you can find out the particular Peak element of a particular area that's the complet logical code part for this particular video I hope you understand the logic if you still have any doubts you can mention in the comment box at this particular video I will see you in the next one let keep coding and bye | Find Peak Element | find-peak-element | A peak element is an element that is strictly greater than its neighbors.
Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**.
You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in `O(log n)` time.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 2
**Explanation:** 3 is a peak element and your function should return the index number 2.
**Example 2:**
**Input:** nums = \[1,2,1,3,5,6,4\]
**Output:** 5
**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
* `nums[i] != nums[i + 1]` for all valid `i`. | null | Array,Binary Search | Medium | 882,2047,2273,2316 |
122 | in this video we're going to take a look at a legal problem called best time to buy and sell stock so say you have an array prices for um i element is the price of the given stock on day i design an algorithm to find define find the maximum profit that uh you might complete as many transactions possible um and sorry as you like and then buy one and sell one share of the stock model times we still have the same role as best time to buy and sell stock uh one and then you might not engage in multiple transaction at the same time so you must sell the stock before you buy one again so it's the same role as the first one but what we're trying to do is we can be able to have multiple um like we can be able to buy stock in multiple times to get the max profit so in this case we have an array and then in this case we can buy from one to five so buy from one and sell at five and then we're going to buy a three and sell a six um so we can see that our profit is going to be seven so five minus one is going to be four six minus three is going to be three so four minus three is going to be seven and we also have another example where we have one two three four fives you can be able to um do it two ways so one way you could do is you can like buy at here uh where's yeah so buy a here and then sell it here so you get make one profit so price uh so you make one so make the profit is one and then you buy it here and then sell it here as two buy here and sell it here as three you buy it here and sell it here is four or what you can do is you start it here and then you sell it at five so either way works um but the max profit in this case is four right and then here we have another example where we have a declining array so basically in this case we have no profit at all so let's talk about how we can solve this problem to solve this problem i think in my opinion it's pretty easy it's very similar to the best time to buy and sell stock one we're going to implement the same thing how we did on the best time this to buy and sell stock one on the second one as well so in this case what we're going to do is we're going to start um at basically how we're going to compare is that every time we uh find a max profit when we find a profit that is bigger than zero then what's going to happen is we can immediately just add that to our profit so we're going to have a variable called total and then we can kind of use the same approach that we use in buy best time to buy and sell stock one we're going to have our minimum variable which basically keep track of the minimum value that we're going to buy from uh where we want to when we want to buy and then in this case we're going to get the minimum value to start at seven and then we can start at index one just like how i did in the best time to buy sell buy and sell stock one and then in this case we're going to basically trying to see if the current position minus the minimum value has a value that is bigger than zero if it's bigger than zero we're going to add it to our total and then what's going to happen is we're going to continue to do that until we get our profit until we get our total uh sorry iterate the entire array to get our total and return the total about variable in this case we're going to move forward because 1 minus 7 is not bigger than zero and then what's going to happen is we're going to see if this value right here is actually um bigger than minimum value so in this case 1 is smaller sorry 1 is smaller than 7 so in this case the new minimum value is going to be 1. and then we're going to move forward and see if five minus the current minimum value is bigger than zero in this case it is five minus one is four so total is now four and then we're going to um see if this value right here is less than the current middle value which is not so we're going to move forward we're going to see if after we um like finish and then uh get our basically added to our total for the profit what we're also going to do is also have to reset our minimum value okay because we cannot use this anymore we cannot use anything that's past this anymore okay because we once we sell it we have to like buy again so by a different stock so what's going to happen is that we're going to make our minimum value equal to our current value so it's kind of like resetting we're going to restart again so we're going to move to the next element we're going to see if this value right here minus the current minimum value is bigger than zero in this case it's not so we're going to increment by one uh and then we're going to see if this value right here wait hold on my bad um we're gonna see if this value right here is actually the new minimum value in this case it is we're going to set three as our middle value and we're going to move forward you can see if this value right here minus our minimum value is bigger than zero which should which in this case it is so we're going to minus six uh we're going to uh get uh the profit which is six minus three which is three plus four which is equal to seven and then we're going to see if this uh we're going to reset we're going to get our minimum value equal to the current positions value which is 6. and then we're going to move forward we're going to see if this value right here minus the minimum value is bigger than zero in this case it's not so uh what's going to happen is we're going to basically pass and then after we iterate the array we just return the total which in this case seven so it's very similar to the first one we're just going to try to implement this in code our first step is to get our length which is prices.length i believe this question still doesn't okay so it does have a constraint okay so the constraint is that the length is uh less is bigger than or equal to one so in this case what we can do is we can say if n is less than two we can still just return zero because we need a buy point we missed sell point and then what's gonna happen is we're gonna have our total which start at zero min is going to start at the first element of the array so we're going to iterate the entire array starting from index one and then we're going to pick this part right here so then we're going to do is we're going to get our profit at the current position so the profit is going to equal to prices at i so the current element minus the minimum value and then we're going gonna check to see if profit is actually bigger than zero if it's bigger than zero then we're going to uh add profit to our total so total is equal to total plus profit and then we're going to get our minimum value is going to equal to our current element right here so pro prices at i otherwise we're going to get min is equal to the minimum value between min or prices at i okay so basically once we've done that we can just go into return total so let's try to run the code okay so basically in summary we're trying to do this trying to get our profit if a profit is bigger than zero we're going to add it to our total and then we're also going to make our minimum value equal to the prices so the current element of the array so that we can reset and then start over just like how we start at the beginning we basically get our minimum value is equal to the first element of the array in this case we're going to get our minimum value equal to the current element of the array and then do that so let's try to submit and you can see we have our success so let's try to think about some time complexity for this one and again the time complexity is linear and the space complexity is constant because we only have two variables here now there's another solution and if you look at this basically every time when we find a element that is bigger than the previous element we can just get a profit and we once we get a profit which is one in this case we're going to add it to our in this case our total and then uh our total right so once we add it to our total um we can continue to do that if the previous element is bigger then the if the current element is bigger than the previous element then we're gonna add it at one to the total or added add the difference get a difference and add it to our total so if we were to change this to the solution that i just talked about what we can do instead is we can just ignore we can we don't have we don't need the minimum variable we can just start at again we can start at index one we're going to get our profits so profit is equal to prices at i minus one we're gonna see if profit is actually bigger than zero if it's bigger than zero then we're going to add profit to our total okay once we add the profit to our total we're going to continue to do that until we get our total so if we were to run the code and we still have um so you can see this is how we improve the solution um 100 faster so you can do it this way or you can do the other way but the time complexity again is going to be linear we just remove couple variables and then try to make the process a little shorter and that's it | Best Time to Buy and Sell Stock II | best-time-to-buy-and-sell-stock-ii | You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104` | null | Array,Dynamic Programming,Greedy | Medium | 121,123,188,309,714 |
523 | Hi gas welcome and welcome back you have given my channel and have given a wait okay what we have to do is to find a morning whose size what should be the list you are ok it can be more than you and all its elements Ka Sam is your multiple of KV. If you find someone like this in the morning then you will return true and vice versa. Okay, so let us understand this problem through an example. Is the problem ours? Then we will solve this problem. Okay. So what I have given here is what I have given to you, the second one is given to you. Okay, so we have to see if we find someone whose multiple is all multiple off and whosoever we get, what should be its size at least. It is okay if there are two elements in it, so look here, you have 24, what is the sum of 24, what is six, which is the multiple of six, because yours is six, it is okay and it is made up of you and four. So how much is it, let's see its size. In this problem, we have to find the multiple of K. Okay, and if you are the size of all, then here one of them can be 2 + 68 8 + 4 12. one of them can be 2 + 68 8 + 4 12. one of them can be 2 + 68 8 + 4 12. What is your six? If it is a multiple of , What is your six? If it is a multiple of , What is your six? If it is a multiple of , then we will make 10 true. Okay, its size is also ≥ right and this can be your hole too. If you is also ≥ right and this can be your hole too. If you is also ≥ right and this can be your hole too. If you add these five elements, you will get 42. Okay, so what is this also, what is 42 also yours? Is k is a multiple of ok so here also 10 will be true. Now how can we solve this problem so before solving the problem you have suppose 23 ok what did you say on 23 that you have six here. What did you do by dividing it, how did you divide it, what does this operator give, it gives a reminder, you got this five, if I tell you that you have 23, okay, this is today, keep it this way and do not add anything to it here and divide this again and Again we need only 5 reminders, so what would you prefer here? Look, if you add van here, it will be 24. If you divide 24 by 6, you will get zero. If you add van here, you will get zero. Van will be found, if you add here you will get 5, you will get this five, so we need multiple of this six, okay if we tell you here, you add 12 to 23 and then do this, what will you get here also, this is 35, this is six. What will you do if you divide by, then reminder what will you get, you will get 5. Okay, then we will add to 23 and see if here also we get reminder five. So see what will happen here, 41 will be 36 of 66, you will get 41 minus 365. So what will happen here too, if you get five reminders, then all these elements are there, what is six, its multiple is being found, date min, we, the elements like here, you in 23, when he was alone, in this condition, I got five and second. When we want 5, here we see that we are adding this multiple of, then we are dividing by K, then we are getting this five. In the honor case, we are not getting it, okay? This means that if you have already received a reminder and again you get a reminder from it means that you have added it to the element with a multiple of 1, then you are getting a reminder from it. Okay, so this is the concept, in this problem, we will solve it. Okay, in solving this problem, how will we do this, what will we do, we will find the prefix sam and while finding, we will find the reminder, we will see from what again we have got the reminder. Earlier it had received a reminder from, what if it has received the date min, what is ours that it is sure that multiple off has been added to it, then what have we received, we have received a reminder from it, okay, so what do we do now? Let's do that with the concept. Now we have to track whether this reminder was already received or not. So what will we do for that? Will we take the map? Will the map actually be ours? Will it track yours? Before the value of this reminder. Has anyone come from or not? Okay, so this is what will happen, actually keep this reminder and here we will keep a value, now I will tell you what this value will be. Okay, so here we will start from 23. Prefix Sabina. What we will do is divide it by what is yours, what is your six, what will you get, here you will get five, so write five here and what we are going to do here is we are going to add i+1, what we are going to do here is we are going to add i+1, what we are going to do here is we are going to add i+1, okay, why do this in the value now? I will tell you, okay, so where did you get this here? It is found on the zero index, so if you do 0 + 1, you will get 1. Okay, you do 0 + 1, you will get 1. Okay, you do 0 + 1, you will get 1. Okay, after that, what do you do now in 23, if you add 25, divide it by 6. So what will happen is 25 6 WAN will be found here, reminder WAN is already there, isn't it WAN, then simply insert the WAN in it and where did you get it, you have also got the WAN index, so you insert it here, okay what after that? Do this now if you do plus four in 23 then what will you get here 29 Then here if you divide by six then you will get five Here is the reminder ok five is already there isn't this five already where did you get this five Five is found in which index, where is this six, where is this four, till four, this was neither four, which is on index, and this fire is on first, where is this value, if it is van, then what is this that has come. Is your current I greater than its value? Is it greater than the value of your previous five? This is your look, have you got 5 again or if you have got a reminder from Van also then in that condition you know that it is sure that you have added some part of Sam which is yours, it is sure that it is multiple of K, okay then So again we have got a reminder for this, you will be surprised that you have got a multiple of but is that multiple of made up of atlist tu sides, is it made up of atlist tu elements or not? Let's talk about it. What will we do for the sweater? Here we are keeping i+1. What will we do for the sweater? Here we are keeping i+1. What will we do for the sweater? Here we are keeping i+1. Okay, that's why we are keeping i+1. See Okay, that's why we are keeping i+1. See Okay, that's why we are keeping i+1. See how, let me take another example. Then let me understand you. Why are we doing this? Why are we keeping plus van? Look here. Is it 23 or 6? Here is six, you have got multiple of K, but what is it only? It is made up of one element, so will you get it here? What if it was six here, I would find you some sub addict, you are the size. Ka whose sam, what is that, how is it divided or okay, then here only you will get five, which is multiply by 6, but is it made of two elements, no, is it made of one elements, retained falls, so here Look, how will we find this condition here, so what will you do in 23, you will divide it by 6, you will get 5, which is the index of this question, then 0 + 1, this will which is the index of this question, then 0 + 1, this will which is the index of this question, then 0 + 1, this will become one, okay, i+1 is what we are doing here. Zero plus one, okay, i+1 is what we are doing here. Zero plus one, okay, i+1 is what we are doing here. Zero plus one, then what will we do in 23, we will add six, 29, what will we do in 29, divide by six, again you will get five, okay look, in which index did you get this five? Have added you WAN index and also got this I's where is your I is on WAN and where is this five already on WAN, you will also see that 5 is already on WAN, we will understand that there is only one element which is We are a multiple of six, so it means that our condition is not being fulfilled, so what will I do, we will make 10 false there, so we have added i+1 here so we have added i+1 here so we have added i+1 here so that we can get it again on the i. If we get a reminder from us, we can check whether it is from I have given this lesson, is it the value of the previous reminder received, is it here to give this lesson, this five was given on your 2nd, this five was given to you on 2nd. And previous five is on your van, what is the van, you will turn through here, but in this condition you are getting equal, I is also a van and its value is also van, here you will return false, okay so this is also an example. Here I will tell you that term will come to you, so what do we do here, we are giving I plus van in the value so that we are connecting with the fact that the multiple of K that we are getting is what we got from the coming list tu element. It will be okay if it is less, then if it is equal then it is sure that there must be only one element. Okay, so here you have got five and the previous five is on your van, this is on you, so you are van less, so here the return starts. We will do it, okay, there will be no need to be ahead, now what do we do, let us understand this example, what we do here is that we take the map, what have you got, you will do plus six, here there is 25 plus, so where is this van. You have got this van, you have got this van index, you have got this van, you have got it right, this is up to six, we have added it, this is what we have, this is ours, this is you here, and the van that we have already got is also on you. We will understand that there is only one element which is a multiple of six, so what will we do, we will not do anything here, we will move ahead, okay then we will move ahead, so here you will add 2 to 23, you will add 6, and if you add four, then here What will you get on 23 + 2 25 6 What will you get on 23 + 2 25 6 What will you get on 23 + 2 25 6 What will you get on 31 + 35 You will make five from six you get on 31 + 35 You will make five from six you get on 31 + 35 You will make five from six Got a reminder Okay five is already there Is there already a five Okay so is it already five We will understand that we have got the multiple key Look How to get 2 + 6 + 4 2 6 8 + 4 12 Is it a Look How to get 2 + 6 + 4 2 6 8 + 4 12 Is it a Look How to get 2 + 6 + 4 2 6 8 + 4 12 Is it a multiple of K? Here you got five, it means that this part which you have added, here also you have got five, a reminder that this is definitely a multiple. If it is ok, then you have got multiple off key here. So it is made up of > 2 or 3 elements. here. So it is made up of > 2 or 3 elements. here. So it is made up of > 2 or 3 elements. Atlist should be made up of 2 or 3 elements. How will we check this? In which index is this found? Where is your 3rd element, ok? And where did you get this 5, on the van, what is the van from three, if it is less, then what will be the return here, we will true, okay that's it, now let's look at the court part, we will go to the code part and then come back here. Okay, let's understand a little, look at the code part here, what have we done, we took a map here which will track you, why did we do this, now let me tell you another test case, let me tell you here, okay What we will do here is 23 + 2 + 6 Here we will What we will do here is 23 + 2 + 6 Here we will What we will do here is 23 + 2 + 6 Here we will take four Okay now we will take here Okay now if you divide into 23 then what will you get Four here Reminder Right 7*3 21 Here pay four Reminder Four will be four 7*3 21 Here pay four Reminder Four will be four 7*3 21 Here pay four Reminder Four will be four This will be You will get this van index here, you will be on 3 plus 6 31, you will do special zero reminder, where is it found 0, again where are you found, it is found on this index, 0123, so this zero is less than 3, so turn here. You can prove it, this is your special case, what will we do for this, we will keep MP 0 here, okay adervise, the same process will happen as yours, what will we do here, we will add Namsai in all, then we will see whether this will work as a reminder or not. If you divide by , you will get a reminder. divide by , you will get a reminder. divide by , you will get a reminder. No one will remind you because modular operator has done that. We have again reminded, is this already in the map, what if it is not there, then what will we do here, now I will set the value from the key. That is your reminder and I + 1 have been added to the is your reminder and I + 1 have been added to the is your reminder and I + 1 have been added to the value. If you are getting it again, then what will you do, will you check that it is at the value of the reminder that you already have? What is the value? Have they given the lace? If they have given the lace, then we will make the meter true. If you have not fulfilled this condition anywhere, then what will we do, will we turn the turn false? Okay, so I hope you must have understood if you liked the video. So please like share and subscribe thank you | Continuous Subarray Sum | continuous-subarray-sum | Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1` | null | Array,Hash Table,Math,Prefix Sum | Medium | 560,2119,2240 |
169 | hello everyone and welcome to python programming practice in this episode we're going to be covering elite code number 169 majority element this is classified as an easy problem now i'll start with the problem description here given an array of size n find the majority element is the element that appears more than n divided by two times so it appears more than half of the time of the size of the array you may assume that the array is not empty and that the majority element always exists in the array so we're not going to be given an array that doesn't have a majority element there will always be something that is the correct answer and we'll we're given a couple examples here we have a list of 3 with 3 2 3 in it and the majority element here is 3 because 3 appears more than n divided by 2 times so in this case the list is length 3 and divided by 2 would be 1 and a half so three appears more than one and a half times it appears two times and in the second example we have two three ones and then two so in this case we have an array of length what is this seven and the 7 divided by 2 that's 3.5 seven and the 7 divided by 2 that's 3.5 seven and the 7 divided by 2 that's 3.5 so we have to find the element that appears more than 3.5 times appears more than 3.5 times appears more than 3.5 times and in this case 2 appears 1 2 3 4 times so that is the majority element in this case so to think through this problem we're going to pull over to the code editor but first we will check our whiteboard and write down how we might be able to approach this problem so given the way this problem is structured we're basically just given an array and we need to find whatever element occurs the most often it just so happens that the element that occurs most often also will occur at least or more than n divided by two ways but the crux of the problem is we're finding whatever element appears the majority of the time or more than half of the time which is also the element that appears most often so for this sequence i just kind of wrote down at random here the majority element would be 2 both because 2 appears the most times and because 2 occurs at least n divided by 2 times in this case this is an array of length seven so it occurs more than seven divided by two or three point five times it occurs four times but how could we go about finding what the majority element is in code well that seems like it wouldn't be too difficult all we really have to do is keep track of each element and count up how many times they appear so for instance we could just loop through this array and say all right the first thing is two and now we've seen two one time the next element is two so now we've seen two times the next element is one so now we've seen one time and we just continue like that we see two again so we iterate that up to three we see a three so that's a new thing and at some point we get through the whole array and then we're left with a list or dictionary we might use for this in python that shows each value that exists how many times does it occur and then we can just extract whatever the max value is from that and return that as the answer and one other insight we can have here actually is we don't need to wait until we get to the end necessarily in order to spit out the final value every time we're looking to store something in this dictionary we're building up we can check at that point if the value there is bigger than n divided by two already because if we've already got more than n divided by two entries in there it's already the majority element and we don't need to finish looping through the rest of the array we can just return the answer at that point so let's jump back into the code editor and see how we could code up this solution so basically what we're trying to do here is create a dictionary that loops through every element we're given so we're given a list of nums we're going to want to store the results in a dictionary so we'll create an empty dictionary here and then we'll just loop over the nums so for n in nums so first we can check if n is currently in the sum's dictionary if it's not we need to add it and initialize it to a value of one so if n not in sums if it's not in sums yet we will add it as sums n will initially equal one that means we've only seen that number once so far and else if it already is in sums well we just need to increment it by one so we'll take this and just add plus here so plus equals one we're incrementing or counting the value up by one and finally after we increment the value of sums n by one we can then check if the amount of times it's been seen is more than n divided by two and if it is then we can simply return that result so finally we can say if sums n the new value after we increment it by 1 is greater than the length of our input array so len n or nums divided by two then we can just return our current n because that has to be the majority element this identifies what the majority element is as soon as something is bigger than that is the majority element so we can return that so this should be a working solution here so let us submit that and pull over to see what we get as our result its processing so we got a run time of 261 milliseconds faster than 41.6 percent of python 3 faster than 41.6 percent of python 3 faster than 41.6 percent of python 3 submissions so it passed it wasn't particularly fast it seems but it was good enough to get past the solution um and this shouldn't actually be too bad of a solution in theory because we only looped through the list once so this is actually an o of n solution a linear length solution there are other solutions we could do that would be actually more than o of n but might be simpler so i'm actually going to go back to the whiteboard and show what one of those would be just because it's kind of interesting so one insight we could have here where we could make a different solution that is easier in terms of code it'll actually be worse in terms of runtime but the nature of this problem means that if we sort any array that we're given then the majority element is going to exist at the middle of the array for instance if we take this array that we did in our last example and sorted it we'd have one two three four and you'll notice that if you go to the middle of the array so say the length of the array which is seven in the middle would be the floor divide two of that so we'd be what at element three zero one two three the middle element is always going to be the majority element after it is sorted because the majority element has to appear more than half of the length of the array that means that the middle element after sorting is always going to be the majority element and this should be the case even if the length of our sequence here were even or if our majority element was like the max or the min value in the array so that it was all on one side or the other leg so let's jump back into the code editor and also code up this solution that's based on first sorting the input array and then simply extracting the value that is at the middle of the array which would be the length of the array divided by 2 or floor divide 2. so let's go back to our code editor and delete our code and create a new solution well what we're trying to do here is return the sorted version of the input so sorted nums and we want to get the middle element of sorted nums so we want to return the element at the length of nums floor divide two we do floor divide because if it's odd we will get a floating point number here so floor divide rounds down to an integer where we can actually have an index guaranteed so basically we're just sorting it then taking whatever element is at the middle after it's sorted and this is only one line but it should actually give us the proper result here so let's submit this one as well and see what we got for this one this ran in 168 milliseconds and was faster than 93.5 percent of and was faster than 93.5 percent of and was faster than 93.5 percent of python solutions so even though this solution is in theory slower than the previous one computationally the last one was an o of n solution this is actually an o of n log n solution because the fastest sorting algorithms you can do are on the order of n log n that's what a sorting operation takes so in the limits of computational complexity this would actually be worse than the first solution but for perhaps shorter and simpler problems this is actually faster at least on leak code and it's a simpler solution in terms of the amount of code necessary to write and perhaps a bit more elegant conceptually than our first crack at the problem so i hope you found this explanation of this problem useful thanks for watching and keep coding | Majority Element | majority-element | Given an array `nums` of size `n`, return _the majority element_.
The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.
**Example 1:**
**Input:** nums = \[3,2,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,2,1,1,1,2,2\]
**Output:** 2
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5 * 104`
* `-109 <= nums[i] <= 109`
**Follow-up:** Could you solve the problem in linear time and in `O(1)` space? | null | Array,Hash Table,Divide and Conquer,Sorting,Counting | Easy | 229,1102 |
430 | in this video we're going to look at a legal problem called flatten a multi-level doubly linked list so we're multi-level doubly linked list so we're multi-level doubly linked list so we're given a doubly linked list we want to flatten this multi-level double-a link list into a multi-level double-a link list into a multi-level double-a link list into a single level right so you can see here we have an example of a doubly linked list multi-level doubly linked list where you multi-level doubly linked list where you multi-level doubly linked list where you can see the node not only have a previous pointer and a nest pointer but i also have a child pointer so what we're going to do is that we're going to flatten this so you can see this node has a tile node so this child node has been pointed to node7 the snow 7 also has a linked list in this case this linked list also has a has another level right so we want to flatten this into one level so in this case you can see we have no 3 0.07 0.07 0.07 no 7.08 no eight points no eleven no 7.08 no eight points no eleven no 7.08 no eight points no eleven point no twelve point two in this case dot ness is pointing note nine and no nine no ten and four five six right so we're basically trying to merge this list into one list right so in this case to solve this problem and you can see we also have another example like this where we have a linked list like this and in this case this linked list um what we have to do is we do the same thing right we basically find this node in this case this node has a child node of node three so we flattened this so we get note one point no three node three uh also point two note two right because it's a doubly linked list we wanna make sure we have no one the previous null and no three that previous one no two dot previous three right so in this case um to solve this problem we can do is that we can perform our dfs right so in this case what we can do is that if the current node we're going to traverse the linked list of course but if the currentnode.child if the currentnode.child if the currentnode.child is not null we're going to perform our dfs to flatten that right so in this case you can see here we're starting from this node we know that this node is not a multi-level or in this case does not multi-level or in this case does not multi-level or in this case does not have a child so we're going to continue so once we visit this node in this case this node does not have a child so we continue once we visit a node that has a child node so we're going to perform our dfs to flatten that in this case flatten the multi-level right so in this case the multi-level right so in this case the multi-level right so in this case what we're going to do is we're going to do a dfs and we start to visit node7 in this case we're going to do with the fs for this node's child right so in this case we have no 7 in this case doesn't have the child node so we're going to do no 8 no way has a child node so we're going to do our dfs to is its node's child node right in this case node 11 no 11 does not have a child node so we continue node 12 does not have a child node so we continue but the thing is that after we do our dfs it should return the tail node right so once we return the tail node back to node 8 what we're going to do is that we're going to have no a dot we're going to have node 12 right so node 12 is like our tail node so we're going to use this tail node dot nest is equal to current which nest is equal to current which nest is equal to current which is no nine and then we're also going to get node9. is equal to the tail node which is no in this case node 12 right and then what we're also going to do is that we're also going to change node 8 in this case node.nest node.nest node.nest should not equal to node 9 it should equal to node 11. so we're going to get no 8 dot nest is equal to node 11 and no 8 dot child should equal the null right so we basically flatten that and then what we're going to do is we're going to uh basically merge this list into one right so it should goes like this right so no 8.11 no 11.012 right so no 8.11 no 11.012 right so no 8.11 no 11.012 no 12.9 right and then we continue no 12.9 right and then we continue no 12.9 right and then we continue so we have no nine doesn't have a child no ten does not have a child so we coming back to no three no this is the tail note right so now uh the tail note in this case is gonna be no 10 right so no tens the tail note and then note 10 so no three dot nest uh so no uh the tail note dot nest is equal to no three dot next which is no four so we have no ten points to four right so we should have note 10 points to four and no four dot preview should be no ten and then we should get no three dot nest should equal to no seven and we should delete that connection uh we're also going to get no 7.3 it should equal no 3 7.3 it should equal no 3 7.3 it should equal no 3 right so we're gonna continue like this one by one right we're going to perform our dfs if current node has a child all right so you can see the code is pretty simple what we're doing here is we're basically iterating right we're performing our dfs um so we iterate in this case we check to see if current node does not equal null if it's not null we continue to iterate pre is equal to node and then what we're going to do is that if node.child does not equal null right node.child does not equal null right node.child does not equal null right then we have to perform our dfs to flatten its children right flatness multi-level multi-level multi-level uh child nodes so in this case what we're going to do is that we're going to do our dfs will return tail node and then the tail dot nest is equal to right so just like is equal to right so just like is equal to right so just like i mentioned before we're going to get the in this case for example node 12 node12 dot nets is equal to node12 dot nets is equal to node12 dot nets is equal to which is node9 right and then we're going to see if no dot nest that's not equal at all if no dot nest does not if it's not null right because there could be a situation where this node is null if it's not null uh we're going to get .preview is equal to tail right .preview is equal to tail right .preview is equal to tail right so we want to make sure no nine dot preview is equal to no 12 um and then what we're going to do is we're going to modify the head node right in this case the head node is node 11 so we're going to get no a dot necessity no it is equal to node 11.3 is it is equal to node 11.3 is it is equal to node 11.3 is equal to node 8. so what we're going to happen is that once we change the head node modify the head node we're going to reset the pointers so that we're going to reset the pointer so the pointer should points to node 9 and known and then the previous pointers should points to note 11 uh no 12 right so we're starting to traverse starting from here right so after we merge this list like getting no 12. no 9 so our current pointer should points to node and the previous pointer should point to node 12. and the reason why we have a previous pointer here is because in this case if we have a situation where the current node is null right when we hear the previous here and the current is null we want to return the pre and the preview is basically keep track of the tail note right we want to return the tail node so in this case you can see this is how we basically solve the problem and at the end we're just returning head is basically the root note right so this is you could so you can see this is how we solve the problem and the time complexity in this case is basically big o of n we're in this number of notes that we have in our entire um multi-level doubly linked list right um multi-level doubly linked list right um multi-level doubly linked list right and the space complexity in this one is because we're not creating an extra node or an in this case another extra list we're just basically using constant time uh for modification so in this case um sorry a constant space complexity for doing this algorithm right we're not creating another uh linked list or something so the space complexity will be big go of it big o of one so there you have it and thank you for watching | Flatten a Multilevel Doubly Linked List | flatten-a-multilevel-doubly-linked-list | You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\] | null | null | Medium | null |
1,759 | hey welcome guys welcome to miley consuming section so one seven five nine a town number of homogeneous substrings yeah so uh yeah written number of homogeneous substring s thinks the answer may be too large it's a modularity so i type in module and homogeneous if all the characters of string are the same so a substring is contiguous of sequence of character with a string so for example a bbc a b c a and a appears three times a appear one times b two times b one times okay and uh you can see this okay yeah so these problems basically count exactly the same as this number of substrings only once because in this problem you only count how many ones right how many substring of ones and the key idea is that for consecutive once you need to count c times c plus one divided by two okay so this is the results right so basically you just apply the your results apply this code into the more orders more i know the general uh question that you only you count for each a account for each bill account for egc okay so but we need to modify a little bit so for this one that if you see zero that means you see some other than one right then that means you need to stop you need to reset your counter and add your results oh by the way if you haven't seen this problem then i suggest that you see this i will post a link below okay so for this one uh you do have zero but your initialize will be what the reason is that and the answer in this case must be one right yeah definitely at this point you go to one and then you're all of so om is the previous one set to be at zero and then you start iterate the iterator string if you see uh which is not your previous one that means you need to stop counting okay so your red answer uh results answer counter add your account and add one and then insert set to be one right because you need to be reset and the change the previous one to be i otherwise the ct count equally equals to one and finally you need to add the final string and the modulo is okay and then there's a boundary phase that if you only have one uh one letter then it should be one right so this is the code yeah so basically these are i think once you see the first previous question then you can get it okay so see you guys next videos | Count Number of Homogenous Substrings | find-the-missing-ids | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "abbcccaa "
**Output:** 13
**Explanation:** The homogenous substrings are listed as below:
"a " appears 3 times.
"aa " appears 1 time.
"b " appears 2 times.
"bb " appears 1 time.
"c " appears 3 times.
"cc " appears 2 times.
"ccc " appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
**Example 2:**
**Input:** s = "xy "
**Output:** 2
**Explanation:** The homogenous substrings are "x " and "y ".
**Example 3:**
**Input:** s = "zzzzz "
**Output:** 15
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase letters. | null | Database | Medium | 1357,1420,1467 |
374 | problem and the problems name is guess number higher or lower so I pick a number from 1 to n and you have to guess which number I picked so every time you make a wrong guess I will tell you whether the number I picked is higher or lower than your guess so in this we are given a predefined API the api's name is guess where the return type is an integer and the parameter is also integer variable which will give three possible outcomes minus 1 and 0. so if this API call returns -1 the number I this API call returns -1 the number I this API call returns -1 the number I picked is lower than your guess if it returns one the number I picked is higher than your guess if it returns 0 the number I picked is equal to guess so if you take a look at the input it's 10 and the number I picked is 6 so this is 6. so this is basically the input and output so coming to the approach to solve this problem as you can make out from this conditions which are given we're going to use binary search so the start will be like the leftmost range that is one and the end will be the rightmost range that is n so let us start by creating uh integer variable start and start is equal to 1. then int end is equal to M now we'll open a while loop whereas start is always less than or equal to n now inside the while loop let us create the mid variable that is the pivot so to find out mid you'll use the formula start Plus n minus start by 2 so this is how we'll find the mid variable now we'll use the API call which they have given us that is guess which will take an integer variable as its parameter now we are going to check if guess of mid is equal to 0 which means that we have found the target so it means that you have correctly guessed the number I was thinking of if gas submit is equal to zero then we are going to return medal answer under the Asus block let's use case of mid and now we're going to check if glass of mid is equal to 1 now as I mentioned if the API call returns one has the answer then the number I picked is higher than you guess so we're going to shift start to Mid plus 1 which means that the number is greater than mid right so start will start from mid plus 1 now block which means that gas of mid Returns the third possible output that is -1 and it means that the number I is -1 and it means that the number I is -1 and it means that the number I picked is lower than you guess the number is less than mid will set n to um with minus 1 so end is equal to with minus 1 and now outside this while loop which means that we haven't found out the number guess so we'll return minus 1 as the output it's on the chord so we're getting the expected output let's submit the code private and solution has been accepted so the main catches as you can see I've got a time limit exceeded error this is the way you have to find out the mid middle position so start plus uh n minus start by 2. that's it guys that's the end of the video thank you for watching and I'll see you in the next one | Guess Number Higher or Lower | guess-number-higher-or-lower | We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n` | null | Binary Search,Interactive | Easy | 278,375,658 |
1,680 | hey everybody this is Larry this is me going with Q three of the uh weekly contest 218 as you can see had three wrong answers here which make made me really sad um but we'll go over it anyway so conation of consecutive binary numbers to be honest I don't understand why this is Q3 when I first got it in Python uh I actually solved it and you could watch me doing the video I mostly solved it in about like 3 4 minutes uh but instead I you know as you could see on the leaderboard uh I actually it only it end up taking me like 12 13 minutes with three penalties and one of and the main reason why is because piine is too slow um I hope they regrade this but maybe not we'll see what happens but the idea there's the really weird thing is that there's nothing really tricky about it you just have to be really careful about well maybe not using strings like I did um but that's pretty much it you literally get the binary number you can C it and then you do a rowing modular on this number and that's pretty much it um my Java runs really quickly um so literally the way the thing that they tell you to do you just do it so um there's no surprise that a lot of the people uh the top people got very quickly I think I got it pretty quickly and you could watch me my Contest video to see that but yeah so basically I just do from one to end I do this operation which is Con catting eye while modding it along the way um yeah here I get the most significant bit once I found it I put it into uh X I don't um I don't want to I know that usually I go into the details a little bit more and but I don't think there's that much interesting I mean I think the way that I did it is I mean yeah there's some bit shift stuff so maybe prerequisite for reading my code is bit shifting uh but like you know that's not really the point of the problem um and there's really not much to this problem other than knowing that you need to mod every time uh and once you know that you need to mod I don't know to be honest like I'm having trouble explaining this problem because I don't know where people are having issues um in terms of algorithm right cuz there's no nothing subtle about it you just have to be careful right um but in terms of uh I did see I mean maybe not anymore but I did see a bunch of people uh having issues and people on my Discord chats uh complaining about time limited exceeded um so and I could show you my piine three time limit code I actually wrote this a couple of different ways um and I just couldn't get it to be fast enough uh and that's pretty much it like I used the strings so maybe that was a little bit dubious but I had to I actually just switched to Java so I don't know if you're using Pyon you're having issues I don't know what the issue is uh with oh I don't know how to resolve it in Pyon I mean maybe I could do it later and upself but yeah look if I do the worst case it's 6 millisecond where I do it in Pyon 3 at least before during the contest I remember was like 300 millisecond so 400 MC right so it's not even close it's ridiculous I hope they regret it but yeah and also beyond that uh look if you look at my python code for understanding um I don't I mean yeah I could have rewined this so that it doesn't create a string and maybe make this a little bit faster but it's still going to be a little bit um like it's such a disadvantage I think for in a weird way but anyway um I don't know how to explain this problem because if you look at this it is pretty much do what the problem tells you so let me know if you have any questions and I will try to answer them as best as I can uh cool um you can watch me sub during the contest next you could probably watch it on fastest speed because um because I like I said I solved this in like 3 minutes and I just had to convert it to Java um yeah uh okay cool let me know what you think and watch me be sad during the contest next okay test more right so that's do the 32 just do 64 for that what I mean I did it the dumb way anyway okay man why did I do it in a stupid way okay fine for guess I should try a big number uh it time out times out I'm going to be sad yeah I mean it's not hard to guess what the case is but huh why didn't I test it though I mean it's fast enough it's probably just that uh dysfunction I mean this is fast enough but it's really annoying that the test the sum of test cases fail 324 come on okay well it's fast enough come on well this turned out to be a silly contest for me anyway cuz it's going to the Penalty is going to be don't enough it this is dum um so is for all right now it's not even right so much faster so dumb uh hey thanks for watching hit the like button hit the Subscribe button join me on Discord let me know what you think about this problem or other problems and let me know if you have any questions uh and I will see yall next contest bye-bye | Concatenation of Consecutive Binary Numbers | count-all-possible-routes | Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation: ** "1 " in binary corresponds to the decimal value 1.
**Example 2:**
**Input:** n = 3
**Output:** 27
**Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ".
After concatenating them, we have "11011 ", which corresponds to the decimal value 27.
**Example 3:**
**Input:** n = 12
**Output:** 505379714
**Explanation**: The concatenation results in "1101110010111011110001001101010111100 ".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
**Constraints:**
* `1 <= n <= 105` | Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles. | Array,Dynamic Programming,Memoization | Hard | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.