id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
1,765
hello everyone let's solve the code 1765 map of highest peak so it's a very typical bfs problem let's take a look at this problem so we are given an integer matrix this order of size and multiply n and if value is zero that is the length series that is one then it's vertical so the um blue color cell is a word there and we need to compute the height for each cell we want to get the maximum height for each cell and there's a limitation sets any two adjacent cells must have an absolute height difference of at motor one so you know the blue one is zero then the neighbor will give height one for this um left button cell we cannot give three otherwise the absolute difference will be greater than one so we can at most give it two so take a look at another example we have two words here and the height will be zero and we can give all the neighbors of this word cell value one and for the remaining two cells we give value to and from this example we can find is a very typical dfs problem so at first we can iterate all the cells in the input and can push the water cell into our queue then for all neighbors we can assign height one then for those neighbors who are labeled transfer sources one neighbor of and sail one and they have not been visited we can assign height to so we can use dfs here first we can get an and so two dimensional size and we can initialize our result and first we initialize all cells with negative one next t1 here is very useful it can uh it can also be used as a visited uh matrix then we have q we first push all the watch cells into our queue okay then it's very typical bfs code it's a level traversal so first we get all the size of the queue then we will follow this size since for this element they have the same height then i just get every element from my queue and now i will check the uh top bottom left right so four directions you if it's an auto range or if this has already been visited which means the value is not negative one in my results array then i will just skip so sales otherwise we can push it into my queue and we can set the height for this here since it has not been visited okay after this level traversal the content will uh auto increment by one okay so this is called and what's time complexity we know for each cell we visited just once exactly once so the time complexity is o and n and the space complexity is also o and since we're using this result array which is uh oversized and so that's our time complexity and space complexity and we know it's a very typical uh vfs problem so um we need to like we need to have a template then we can use it every time when we solve bfs problem yeah thanks that's it
Map of Highest Peak
merge-in-between-linked-lists
You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells. * If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell. * If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell. You must assign each cell a height in a way that follows these rules: * The height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1.
Linked List
Medium
null
1,187
Hello everyone, welcome to me, the concept of the channel and the playlist of questions has also been started, so you can start there too, where the dynamic is explained from the scrap, there are more videos coming soon. Okay, so this is 1187 hard in liquid. But it is very similar and if you understand it well then it will become very easy through recognition and memorization. This question is ok and I will also tell you why the question is ok. Make is strictly increasing. Google asked this. Let's consider the question as a question. It is a very simple statement. I have given you two words, friend, and what do you have to do? Hey, one has to be made strictly increasing, that means after one, there should be a number bigger than just one, okay, 7 is after 7. The bigger number should be 8, 3 cannot be a, neither can 8 nor can it be strictly both, so what it is saying to you is that you are in the second one, find some element which is the one and replace that element with that element. Okay, what are you saying, if these one operation is done, then in how many minimum operations can you make raven in English? Hey, the same one has been asked, the question is about minimum number of operations and if there is no way to make raven in English then mines. Give one grater, it is okay, so first of all, I will not tell you directly that this is a DP question, okay, first of all, let's try to make it with the normal Giridih method, which is the normal method, okay, so let's start. And let's build our theory, see, it tries to understand nothing from the first example, then after this, we will take another example, in that also we will understand some more things, then we will slowly move forward, so now see what we have to do, hey one. If you want to keep strictly increasing, then here when I came here, this is equal to zero, then this is one, there is no element in its previous, it is fine, this will be the right place, now when I came here, then its previous is in the air. Who is this, then P says, I am going to the previous mother. P = going to the previous mother. P = going to the previous mother. P = Okay, so what is in the previous air, this is the one of the five. Okay, it is very good, it looks strictly increasing, so what did we do by skipping this also? Diya and I have been made bigger ahead, okay if I have been made bigger then what is the previous of I, this is P, okay now three has come, here I have seen some problem, okay, what is the problem, okay brother, now the three that has come is bigger than five. So it is not there, I want 10 bigger than 5, so what should I do? What is the element preceding 3? It is 5, so there should have been an element just bigger than five, whereas here it is three, okay, so let's reduce one. Let's look for an element just bigger than five. Hey, it's okay in you, so hey, I can see two elements which are bigger than 5, one is 100, the other one is 6. Which one would you like to add? If you add 100 then who will have the problem? There will be a problem on 7 because 7 is less than 100 so what would be the best approach that brother, I am greedy, I am just a little bigger than the previous element and I will find the one which is bigger, you just give me a greater element and find the previous element. I will just take six later and I will replace I with that. Okay, so here I have added three to cat's six. Okay, so here six has gone to a. Now put it in i, what will happen? Now I is here, my a is here. And the previous one is here, okay till now it is clear, after that let's see again, I which is seven and the previous one is six, which is fine, it should have been bigger, which is fine, so how many operations did we have to do, just one. Had to do an operation, did n't I? Six was brought here because of the cat. It is very simple. If you keep doing it like this then you must be thinking that yes, this will be done very easily. What did we do Greedy Five? Just bigger lemon than six was found, so ours was made very well with it, so okay, we know one thing from this, what have we found out from this, we came to know one thing that brother, just bigger element than five is here. Had to find just one big element, now every time you will do a little liner search, or else do one less. To find just one big element, you can close the upper board. This is what the upper board does, isn't it just a big element? After searching, it is seen that whatever is yours should be sorted, so I mean one thing, what have we come to know, whatever thing I am coming to know, I am going to write that brother, we will have to sort, hey off you till here. It is clear, okay, now look, now let's assume that instead of 100 and 6, we get 1324. Let's see whether our approach will reduce it or not. Okay, here we tried to make what we just tried to make from the starting proof, if it is made then it is very good. It's a good thing, let's see, it will start from here, it is the previous element, no, okay, then here is its previous element, this is okay, so till now everything is looking fine, see one &lt; 5, okay, is this also one &lt; 5, okay, is this also one &lt; 5, okay, is this also indexing? Keep doing zero, one, three, so we have skipped this one de index also, we are saying that everything is fine, ok, let's go, everything is fine, then we move ahead, if I go here, if P goes here, A, then ok now. There is a mistake here, there is three A which is not &gt; 5, so what I said is that not &gt; 5, so what I said is that not &gt; 5, so what I said is that find the element just bigger than the previous one and see what is the element just bigger than the previous one. If it is not there, then what do you think brother is the solution? If you can't take it out then you return mines one and in the dog question it was said that if it is not possible then return mines one then you must be saying that yes we will return mines one, there are 5 to 10 big elements. No, but you did not pay attention to one thing here, the answer was here, 5 has this previous element, so you were thinking that yes, everything is correct and everything was correct, actually give one, it was becoming five, but let's see. So, let's change this 5 also, see how the answer will come, look at this 5, if I do it, then see the answer will come, brother, the direct solution will not be able to be simple, which Giridih you were trying before. Well, you were given a very simple thing and I became a simple greedy son, so what does it mean that brother, when everything was looking perfect, remember when I was here and P was here, everything was looking perfect. What does it mean that everything looks fine, it does not mean that I will not replace it with any other number, I will try that possibility also, okay, what I mean, what I am saying is that if the i element of one is Greater Dane is the previous one like see here 5 Greater Dane is one so everything is looking right Okay everything is looking right but the style I know I would like to try it is a possibility brother I may not have any problem in the future If the problem I showed you a little earlier is not there, then I will reduce it by one. Let's also explore the possibility that if this also has to be replaced with something, then it is okay, then what will I do in this, so in this also I will do the same thing, it will be 1237. What I am trying to tell you is that even if you are seeing everything correctly, that is, if the element that came is bigger than the previous Helmunt, then still there is at least one option. You can already see what is the first option, flood ahead, which is fine but one more option, I said, we will try, what is the option, we will apply that operation and it is not that the answer does not come from option one, yes, in this example we have used option one. What was done was that if we assume that everything is fine then skip ahead and move ahead, then the answer was not coming here because there was no element greater than five, but it is also possible that the answer is given from option one. It is not possible that we have to do some number of operations in it and we have to do some number of operations in the option tu, so in the option which we had to do the least operation is of tu because we have to apply just greater than the previous element to find it, then we will shorten it. This will make one less posture of mine till here Clear Now let's see the second one What did I say that if everything is looking fine like here the previous air has come here then everything is looking fine one is &lt; come here then everything is looking fine one is &lt; come here then everything is looking fine one is &lt; 5 if it is looking fine Even then, what I am saying is that if I take one of them, I am sorry, it is okay, then I will definitely do this, yes, let's go one by one, what is the option, brother, if there is a skip, then it will give some answer, but what can I say? I am thinking that I will definitely try one more thing, option tu kya ki operation, I will try to do the operation. Okay, the answer that came from that last, what to do is the minimum of option one and the answer from option tu will be my answer till here. It is clear, I am repeating again that see, when do I have the option to make I big like this, look here, I &lt; 1 &lt; 5, look here, I &lt; 1 &lt; 5, look here, I &lt; 1 &lt; 5, I is here, P is here, so this is a very correct condition, strictly. If it is increasing, then I can increase it by doing nothing, right, without doing any operation, I will definitely do that, here is what I am doing, but a little earlier I told you that by doing the option, you also have to do it. If you want the optical answer then sometimes the answer will not come at all. If you choose option one then you saw here that everything was going right here but when you came here and the previous ones came here then If you are not able to find 10 elements bigger than five, then you are stuck here, you will not get the answer from here, PM is sorry, what is the matter now, you will not get the answer from here, that is why I am saying option you are great. The tree is fine, that's why we will have to try both of these, the minimum answer from both will be mine. Okay, so you have seen, this is its sorry point, it is not the story point, so it has become very simple. There is an option that brother, I can skip because this It looks correct to me, right, the current element is bigger than the previous one, so it is increasing, so I can go to the direct option, I can easily run into I Plus One, but you also have to try the option, we remember because I told you in the exam that if you do n't do option one then you can get trapped in thoughts, you have to try the same option too, option one, whatever minimum operation was there in option one, that will be my answer, this is a very simple thing, okay and one small thing. Tell me brother, how will be the base, what will happen to it, you will have zero elements, if zero one zero elements means index I which is outside A is gone, okay then how will be my base, so no they have no more elements, you process and no moral elements you. If there is a process then what will be the number of operations. If it is zero then we will return zero in the last. Okay, it is clear till now, so now let us see how this question of DP happened. See, I am telling you that initially I had started from Giridih. No, I was just moving ahead, simple, okay while going, then I saw that I am stuck there, okay, after that I thought, no, if you want to try both the options, then they have options actually vice DP question, first of all, then simple grid. My example is not less, I did not reduce it in one, after that you will notice that brother, we have two options here, they have options right no and we have been given a clear cut that brother, we have to find the minimum, this is what happens. This is how DP is detected, you can make a tweet diagram if you want, but I think this is a pretty straight forward question, now that's why I didn't find it hard at all, you just wanted to understand why brother simple greeting is not reducing. Okay, then you will understand yourself, it is not good, we have to try both the options, so the thoughts are the same, it is telling us to clear cut and extract the optical answer, if you are okay then if we look at the story point that we have written, then from this Try to make the code, let's see how it will be, then see how simple the story record is going to be, first of all I had given you a clear cut that we do not have to do anything, we have to sort it out, you have to do this also in the sending order. Now I told you why I have to do it, okay, after that what I said was that I will do the result tomorrow, I will make noise in the result, solve it by doing it tomorrow, I was also keeping track of the previous element every time, so my current index is zero, okay. So it doesn't have a previous element, right, so I will take the previous element as this. Okay, otherwise, to make it strictly increasing, I have taken this as infinity so that the minus is greater than infinity, so what is my point that we should try two options. To do simply, first is my index, second is mine, you are okay, if you are N, okay, no operations required, now let's move ahead, after this see what I told you, brother, if the current element is there, if it is greater, it means this sticker is increasing. Right now everything is going well, right, so what will I do, here I have taken a variable named result one, in result one, the result of option one is option rter, it will work, but I am showing it to you, okay. Have you done your operation? Okay, if we have replaced it will require an operation, so OnePlus could have done it yesterday but it was running less, okay, it is quite simple, so very simple decoration memorization is done, how in the year, what will you do, each index. I will try two options, neither your power nor exponential solution is ok, I will store it in memorization, what is the reason that I did not take Tutiya, ok, the power of the tank is given as nine, I have given 2000, so now the value is ok. The power tank is very big and the maximum value is given by nine, so I have stored it in the map, so you should know this region, okay, it is going so big, this is its maximum, so now I will mess it up in this map. With help, first let's write it from memory and see if it is getting submitted or not, after that we will submit it by doing memos. Okay, so let's quickly code it, do our requested and memorization and let's do recency first. Question is quite good, okay. What did I say that first of all we will sort the beginning of are you and off are you? I have already told you why we will do it. Okay, now let's start and make the result equal to this. We will write the solve function. Starting in index is from zero. Both of them are passing, hey, you will add more previous elements, but right now we have previous air, otherwise I have given the ending mother and I have also told you why I have been added, because we are talking about strictly increasing, okay and here. But we will check the result, no problem, let's first see the solution. What was there in the solution? Okay, mine and both are sending, hey one and you are sending, after that these previous ones are also sending and I told here only. Had given that if my ID But it will come out i.e. But it will come out i.e. But it will come out i.e. option one which is mine is one A's power nine plus one. I have given the value of all the elements in the constant which is the maximum tank 's power nine, the power of one will not go, so 's power nine, the power of one will not go, so 's power nine, the power of one will not go, so I have taken Vani's power nine plus one till here. It is clear, okay, the idea of ​​one, which is the current element, if idea of ​​one, which is the current element, if idea of ​​one, which is the current element, if it is bigger than its previous element, then we can definitely skip one, that means we have an option, we will solve the result one, how will we skip, history plus one. Hey, you have done it, okay, and who will be the previous element for the next element, which is the current element of mine, why are you skipping the idea of ​​one, because here why are you skipping the idea of ​​one, because here why are you skipping the idea of ​​one, because here we have not done OnePlus and no operation, come this moment. No operation was done, okay, now let's come to the result of our second option, you make it equal to one A to the power of nine plus one. Okay, now what did I say that what was in the just option, you just find one greater element than the previous element. It is = We have found the element, so we take out the index. After doing this operation, we get the results. We have done one operation, otherwise we will do one plus, after that we will solve it. Right see, why did we do this one plus? Because we did this operation, we did this. Here, there is an assignment operation. Hey, if I get the idea from one, then I will send it here. Okay, it must have been cleared very well here. You guys don't have to do anything. Return minimum whatever you get. The result has come from result one. If this is what he said The value has gone If this does not happen, then you will definitely have to pay increasing tax. If you change any one of the branches, hey baniya re tu, then change the bill reflector in the branch also, which we do not want in this branch. I have made some changes in my 11, okay, but you do not want that change to be reflected in this branch too, okay, that is a problem, we cannot do that, so see, we should not do this, it is okay if we If you are sending buy refinance then okay then what do I do here, I simply remove this, right? What will happen to our previous element? You just have to remove that line. Okay, either way then the element which is mine will become K. Why because hey one's I, we should have assigned are of tu ka's, we were doing it right, now why is he not signing this because brother it will change hey and today even by not doing this, you can find out the answer. The point is that you just have to count how many operations have been done, it is okay because after that, you are going to flood further, okay, if the previous one has happened, what difference does it make to you, for this even if you remove the dog, it will not make any difference to you. Change the previous one because it is equal to ray eye, is n't it? Hey, it is equal to one eye and for the next element, what will be the previous Helmunt, this will be the element, so here I give the previous pulse, till now it is clear, okay. So now let's run it and see, let's do this also with this timing: I think it will give time, yes it will give time, what I told you, two things are changing, so I will make a map, okay, but I will store it. And in the comment which will have one idea and the other which will prevent whatever operation, I will do it in this interest, I will name it MP, it is clear till now, okay, now before taking further, I will first check if mp. 5 Do we already have the result stored for this IDEX and this pref? Please return it to me and if there is no result then all this will happen tomorrow. It will happen tomorrow and I will store it here before returning. Okay, clear till now. And before starting everything, MP will clear the road here tomorrow. Okay, time complexity too, I will tell you right now. Okay, MP will have the map here. Okay, and if we have missed the return statement here, then this is the return. We have written the rest of the things, look at one thing here, we were signing and then sending the prep, you send it directly here and there is no need to do this, you are fine by submitting it. Let's see let's see then able tu pass, which date is cases and this was the previous element, so remember now how many indexes can be there, so as long as the length is, that is, let's take the size of one, if it is M, then it is okay, so many statuses will be M. * And for every element, the statuses will be M. * And for every element, the statuses will be M. * And for every element, the previous element which we were looking for, where were we looking for it, we were looking for it from you, okay, so in the worst case, you are N, sorry, so M*M cents will be total, you are N, sorry, so M*M cents will be total, you are N, sorry, so M*M cents will be total, okay and in every state, I am upper closed. I am writing, look, if you take my mother's size then people will put it here, then do it tomorrow in every tomorrow.
Make Array Strictly Increasing
print-foobar-alternately
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
Concurrency
Medium
1203,1216
199
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is binary tree right side view so in this question we're given the root of a binary tree and you have to imagine yourself standing on the right side of it and our task is to return the values of the nodes you can see ordered from top to bottom so the return type is a list of integers and we have to list the notes which we can see from the right side so let's take this example and see how we can solve this question so let's start with the first example we are given the root of a binary tree so initially the root is here now we know we are at the right of the binary tree and we have to return a list as our output so declare the list and whatever notes we are looking at should be returned as the output we start from the top to bottom order in the top there's only one node so add it into the output now we come to the next level in the next level from the right we can only see this node we can't see this node because this is blocking it so add that into the output now in the next level we access this now we can only see the rightmost node we can't see this node because this node is blocking it so add this into the list and we accessed all the levels so we get our final output so we know we have to travels level by level so BFS is going to be a good approach to solve this question so let's take a dry run and see how we can Implement BFS so here you can see to implement BFS I have taken a q because we have to access level by level so create a current node which is initially empty and what is in the top of the Q it is one so consider it as a current node now we have to keep track of how many nodes are present in the current level Q has only one so the size of the Q is the current level size so one is the size now pop it from the Q and add it as the current node so one is the current node now how do you go to the next level you check if one has a left sh yes so add it into the Q check if one has a right sh yes so add it into the Q now calculate the size of the current level size is a q Q size which is two now take the topmost element as a current node so topmost element is two so current node is also two and this will be removed from the Q now check if two has a left child no check if two has a right child yes so add it into the Q now the current node is the topmost element in the queue it is three so current node is three check if it has a left child no check if it has a right child yes so add it into the Que Now pop this current node from the beginning now we finish this level now before going to the next level we have to add the current node into the list so initially I didn't add one into the list because we already accessed that before going to the next node now the currect node is three so add it into the Q now go to the next level now take the topmost element now calculate the size of the Q is two it means in the current level also there are two nodes so five and four are in the Q so those are the elements in the current level which is size two now take the topmost element is five so current is five now remove it from the Que check if five has a left child no check if five has a right child no so nothing will be added we go to the next element is four so consider it as a current node so current node is four so four will be removed from the Q now check if four are the left child and four are the right sh no nothing will be added into the Q and now whatever is present in the current node will be the rightmost element in the current level so that will be added into the que before starting the next level now before starting the next level we can't start the next level because the Q is empty it means we finished all the levels so whatever is present inside the output will be returned as the output which you can see here 13 4 is the expected output which is matching here now let's implement the same steps in a Java program coming to the function given to us this is the function name and we are given the root of a binary tree as I said the return type is a list of integers so first let's declare the list as our output so I create a list of integers I'm going to name it result and this will be ar list now let's check if this root is null if it is null we can return the result which is initially empty so if root is equal to null we can return the result now let's declare a q because we have to implement BFS and this Q is going to contain tree noes I'm going to name it q and implement it as a link list now let's add the initial root into the Q so q. add of root now we have to iterate until this Q is empty so while Q is not equal to empty we keep iterating now inside this Q we have to start off by creating a current node which is a tree node I'm going to name it current node and this will be initially n so using this current node I can extract one node at a time at every level so I need a variable to find out the number of nodes in the current level I'm going to name it size which will give us the size of the current Q which is indirectly representing how many nodes are present in the current level now we use a for Loop to iterate through all the nodes present inside the current level so I is a iterator which will start from zero and it will iterate until the size of the array Now using this current node I extract the topmost node from the Q so q. pole will return the node and also remove it from the queue now we keep iterating forward using this current node I have to check if the current node if this was initially the current node if it has a left CH only then add it into the cube so if the current node. left is not equal to null only then add the current node. left into the Q so q. add of current node. left now let's do the same if the current node is here check if it has a right side only then add it into the queue so if current node do right is not equal to null only then add it into the Q so q. add of current node. right now this for Loop will happen for all the nodes present inside the current level now for example if we are at this level current node will start here and it will go here now before going to the next Loop we have to add this into the output list so make sure outside this for Loop add the current node into the result so result. add of current node. Val now we can go on to the next level so this will happen for all the levels and in each level before starting the next level we add the current node that is the rightmost node of every level into the result and now finally outside the Y Loop once we access all the levels we can return the result as the output now let's try to run the code there's a typo here this has to be capital n and the test case are being accepted let's submit the code and our solution is accepted so the time complexity of this approach is O of n where n is the number of nodes present inside the binary tree because we are accessing all the nodes exactly once and the space complexity is also off n because we're using a q to implement BFS that's it guys thank you for watching and I'll see you in the next video
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116,545
92
hello Shak speaking uh as part the commitment uh yesterday I said that we are going to solve this problem and it's medium problem uh up to today up to date we have solved easy problems but now it's time to solve some medium problems and it's reversing Ling list so my plan is to divide this solution into two part in the first part I want to give some basic understanding of Ling list and how to reverse it so how 32 4 is reversing 43 2 we need to understand that otherwise it will be tough to solve this problem so in the first part uh we are discussing how to reverse it in the second part we'll deal into the solution excuse me so in the first part uh this is some predefined or predefined Logics uh if you run this logic line by line it will reverse it okay simply reverse it so how it is reversing say these five lines of code are responsible for uh head and tail okay so initially head should be that and tail should be that okay it is supposed to but we want to reverse it head will be here and tail will be here okay so how we are implementing that you see Temp and we are taking some extra two variables for as a helping hand to make these things happen another one is temp and another one is pre previous so this is the extra variable temp equal to this do hit I mean temp will indicate the head now it is one okay and head is this do tail so head will be occupy the place of tail this do tail equal to Temp this do tail also point to one temp will point to one and tail will point to one both are this tail and both are pointing one I mean head previous equal to null and we are taking another variable and it's initially null as it is out of our uh loop okay so now it's time to start the loop so for one uh when the loop will run it what will happen give it a serious consideration I mean next equal to T do next so next equal to t. next okay so for one next will be two t do next equal to previous D do next equal to previous so now it's time to happen the magic will happen and uh the poter will reverse okay now saying t. next equal to previous so it will indicate so our reversing has been started okay previously it was pointing to this direction now it is pointing to this direction for this code t. next equal to previous T do next equal to previous so it's pointing to previous to reverse the direction now previous equal to Temp so now previous equal to Temp and temp equal to next so after the first iteration we are getting this scenario so now go for second iteration and it is true so one is done now it is two for two next equal to Temp do next okay next equal to temp. nextt so what is saying next equal to temp. next and temp. next equal to previous t. next equal to previous now it's time to reverse the pointer temp equal to next now it is pointing here so temp do next equal to previous equal to Temp temp equal to next so upon the completion of the second iteration we are getting this scenario now it's time for three two is done and for three next equal to t. next I mean t do next t. next equal to previous so T do next equal to previous sorry t. next equal to previous okay prev equal to Temp previous equal to Temp temp equal to next so upon completion of for three we are getting this scenario previous is pointing here temp is pointing here next is pointing here both two are pointing four and previous is pointing three you see how the magic is happening so three is done now it's time for four so for four next equal to T dot next so next equal to T dot now it is pointing null and we are out going outside of this Loop scope and t. next equal to previous so it will be like that and previous equal to Temp temp equal to next and both of these are pointing null temp equal to next both are pointing now so our Loop is done but we are reversing our list okay so hope that will make sense and I have a code written over here so how it is reversing I have 1 2 3 4 so if we run the code say note you see this is the code is the link list okay so this is the structure Constructor and I have some push reverse okay so if we run the reverse so it's reversing so before the reverse it will 1 2 3 4 now it is 4 3 2 1 okay 4 3 2 1 I hope that will make sense so this is our first part in the second part we will solve this problem so and another thing is that if you start to solve this problem you have to have basic understanding what is link list what is a stock use everything so I hope that will make sense so if this is the main logic if you understand this uh you can solve this problem okay this is the brain or structure for reversing a link list so I hope that will make sense in the see you in the next video and tomorrow we will solve this problem so if you like the video since I have made the problem very Crystal Clear easy to understand so if you like the video please like share and subscribe stay tuned stay connected and uh if you fail to understand this problem uh hit the comment box okay thank you very much see sir
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
1,631
Hello hi everyone welcome to my channel it's all the problem pass with minimum fat so you are doing preparation for the upcoming like you are given its tours of sizes in favor of vs in the top 10 most to travel to bottom right corner bin tere ab them face to face Boss subscribe to the Page if you liked The Video from this App Posted By Coming From This Point Is Sudhir Verification Ko Form From This Degree Subscribe Over All Subscribe Seervi Number of Columns and Columns in Between 1200 subscribe to the Page if you liked The Video then Hindi Maximum Valley of Speed ​​and Power Hindi Maximum Valley of Speed ​​and Power Hindi Maximum Valley of Speed ​​and Power 600 Remover Difference Vikram 2067 Solar Maximum Volume Minimum Can Go Up to RS 600 What Can We Do Will Solve This First Using Difficult Street Light for Electronic and Start Doing Things Will Take Channel Subscribe 0 Points From Subscribe We Do We Call The Will Check This Path In This Gram Satisfied With Differences In Hindi Hello Friends Benefit And Can Have This At Least Value In This World Can Do Subscribe To The Limit Video Subscribe Seervi 100 From Which Will Reduce 2018 From Hero to na tu na no the meaning of this is we no part of the middle from defying all the giver of life but different from toe Lesnar is to vs break after twelve winter medicine and again updater volume two to two lotus ayurveda india servi will Start From 0001 Party With Difference Like This Point To Channel One Kiya Beyhadh Aapt Sutrapat Will Stop When They Sneeze On To Distance Sudhir Vats And - 1m Columns And C Columns Sudhir Vats And - 1m Columns And C Columns Sudhir Vats And - 1m Columns And C Columns In This Invasion Subscribe 21 August 2002 and subscribe the Channel will start from next subscribe To My Channel Direction approach from going into the note Someshwar check weather it has been agreed and also it is not avoid this video and audio recording video subscribe from absolute power subscribe for 9th and 11th Which Will Not For Class 9th That Is Good Is Dish Limited Ok And Gold Be Party Matrix Related Agree With U Kid Did Not Limit Candidate Age Subscribe Into Consideration For This Is Not Need To Look For Meaning In Life Is It Is Subscribe Now To For Simple And they will end up paying back so let's why new in soup in flights from english me hai na ho abhi add the first inductive time beer starting from more than 200 settings on it from 90 to its diplomats in the capital of a number of research And Capital C Fuel Chau Ne Why Not They Will Also Term To Degrade Mix Breed Basically Not In The Object Will Mark Vegetable Of Sciences You Are Which Boat This Is Not Withdraw Its Different Directions Like Raise Hair Members Film Direction surplus difficult-2 subscribe com difficult-2 subscribe com Rich and destination coordinate and what is equal to see minus one is the best wishes pimp tours in the destination with Indian no know fit for appointment of this for rent in to-do list from simple college director in to-do list from simple college director in to-do list from simple college director in the user can they know what we Will Do Subscribe Zulmi Express D0N0 Advised Subscribe Now To Check The Satanic Verses And Subscribe And Avoid And Also Not So Let's Get Rid Of Subscribe To Izzat Kiss Fee No Tolerated In The Water Can Also Check The Value Will Wake Up Side Content And They Will Make The Match David With U The Effigy No Record To Limit In The V Shape The Video then subscribe to the Page if you liked The Video then 200 Here This Is The Customer Say Laddu For This NCP According Extracted Subscribe To Hai So It's Accept What Is The Time Complexity Of Situations Where You Can See This Method Will Run Every Time From Sydney With Love I Am Also Delhi - 110 As The Time I Am Also Delhi - 110 As The Time I Am Also Delhi - 110 As The Time Complexity Solution Of R Ashwin Adheen Login Specific Acid Subscribe Like This Problem Graph Minimum distance from to-do list What Problem Graph Minimum distance from to-do list What Problem Graph Minimum distance from to-do list What is the distance from Subscribe Thursday Subscribe Chinese slices all the distance with maximum volume and nice youth setting distance of Light this Video then subscribe to the Page if you liked The Video then subscribe to the Page Tu Varide Ka Word Excel Koi Three Flight Dissolves In The Digestive Thanks For Watching A
Path With Minimum Effort
number-of-sub-arrays-with-odd-sum
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**. A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route. Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._ **Example 1:** **Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\] **Output:** 2 **Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3. **Example 2:** **Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\] **Output:** 1 **Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\]. **Example 3:** **Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\] **Output:** 0 **Explanation:** This route does not require any effort. **Constraints:** * `rows == heights.length` * `columns == heights[i].length` * `1 <= rows, columns <= 100` * `1 <= heights[i][j] <= 106`
Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.
Array,Math,Dynamic Programming,Prefix Sum
Medium
2242
388
so let's talk about the longest absolute file pack so this question is pretty long and might be misunderstanding for some point but i'm just going to dive into example and then you will be able to see what happened so here is it so you have a string so this is your string and then this string is actually represent this diagram so uh what do you actually need to know first is actually uh for n line for the end line you will have to go on the next uh next path and then for every single path you have the slash t is actually representing your level of your folder or your file doesn't matter so for this folder sub directory one this is actually level one and this path you have two to two slash t so this is uh the second level and this should be have three right and here one two three right so this is pretty easy we just parse the inline and then for every single inline string right you will have to have uh slash t at first no matter what right and then it's either the file path i mean it's either file or a folder name right and then you just have to um basically just have to know what is your current level based on this uh based on this slash t so um if you have two slash t this is actually give you like uh the second level right again how do i know it i just have to count the number of the slash t so in the string you can use last index loss index off this is actually a pretty good method so if you have only one slash t the last index of this is actually what this will give you zero this is because uh this is the file path right and then uh you are starting from slash t anyway right and you only have one right so this will give you zero and for this one you will give you uh give at least index which is what uh los angeles your one two right so uh determine how many slash t uh stash t you have you will be able to know how many uh i mean what is your current level and let me just jump into how do you actually know what do you need to do so you need to have a stack so stack is pretty easy you will just have to store the length of your folder and basically like when you start from here and then you go on the subdirectory sub directory one right and you go on the file one then when you go back to the subdirectory tool right you need to pop the uh popular file from the uh subdirectory one right and basically this is pretty easy like you'll give you three you'll push directly one into the stack right but you only you also have to push the slash right so three plus one so this is the level one i mean level zero doesn't matter so you'll go on the subject sub directive one then you'll have a seven plus one and then later on you have you'll have file one dot est and then you'll have a four five six seven eight nine so nine plus one and then uh for this situation if you have a dot you don't need to pass one this is because you know this is file this is not a path i mean this is not a folder so you have a max uh you are just storing uh the land of the stack right and then somehow your pop right your pop uh your pop knife first because this is not this is belong to subdirectory one and when you pop the knight then you also have to check okay if subdirective two is in the subdirection one no right so you'll pop so you just add subtlety two into it so this is what seven plus one right seven plus one and then so on right and this is a x plus one i don't know what's the means and then you find the dots then uh you put y in there and then you find the longest length and this will be a solution so it looks pretty hard and but when you call it should be too easy so i would have a stack new stack and then i will have a map equal to zero and then also i need to push my the default value is zero so uh at the end i would just return the max no matter what right and then i would just traverse the stream so uh i need to pause right so split by slash n so i was split by slash n and then uh this will be the current string right for the first one and then all right let me just have it more space so i would say in level is equal to what uh string.index last image sorry oh what happened okay and then i will have to find out what is the length of the uh folder so the length of the folder or i mean the photo file doesn't matter so then it's actually equal to what the stream.length minus the stream.length minus the stream.length minus level right so you will have this right and this will be what this will be slash t and this is uh the first string this is actually one this is actually the level one right this is not level zero uh level zero is uh dir right so you need to plus one right i uh for this one you will give uh zero because uh the index is actually uh at the front so it's actually zero then i will have to uh okay so for the first one the dir for the first one let me just go back to uh dlr first because you are you'll push dr first right if string dot contains dots you will do something this is actually deal with max but if you don't right i basically just watch that push you push dr plus and slash that yes slash right yes so it's actually the length of the uh i mean the lenovo string with all the slash t plus uh your current level which is what um stack up key i mean current length right so this is current then let me just make it older so the first one the default value is actually zero so zero plus three right plus one so this is the uh the first level and this is your second level but be honest this is actually the first level because this is the first slash t you have right so uh i will have to check so step outside so stacker size is actually uh determine how many how uh i mean the level order so if you push one in there i mean this is the first level right i mean but you push the push default value zero so zero one two right so if uh well step of size is actually greater than level plus one uh this is actually mean right uh this is actually means when you add uh sub32 right your level is actually what y right because this is actually return zero plus one is one and then one plus one is two but the step the size is actually zero uh one two three right so you need to pop right so when you pop then this will be your current um current level and the stack the size is always include uh the default value so it's actually zero one two three i mean one two three four i mean the size is starting from one right one two three four and then this is actually two so you need to pop this and then i will have to update my max so max is actually go to uh max comma and then i will have to pick my current length plus the length of the string i mean the length of the file right and this will be it looks pretty hard to understand it but if you do have any question um just leave a comment and i'm gonna run it so i don't want making a typo okay i do have typo oh yes i do like that semicolon anything else okay i do have typo again split okay this is string okay what else oh and please okay here we go so let's submit it all right so let's we'll talk about the timing space complexity so for the stream basically you traverse every single stream right so this is all of friend the land of the input and then the space uh the worst case you i mean you definitely have to add every single string i mean the integer into the stack right so i would say all of them but you can say constant doesn't matter but uh the time is developing it's definitely all of them and again this question is considered uh difficult be honest because it's actually related to math and also the stack so if you have any question leave a comment below and i try my best to help and i'll see you next time bye
Longest Absolute File Path
longest-absolute-file-path
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have `dir` as the only directory in the root. `dir` contains two subdirectories, `subdir1` and `subdir2`. `subdir1` contains a file `file1.ext` and subdirectory `subsubdir1`. `subdir2` contains a subdirectory `subsubdir2`, which contains a file `file2.ext`. In text form, it looks like this (with ⟶ representing the tab character): dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext If we were to write this representation in code, it will look like this: `"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext "`. Note that the `'\n'` and `'\t'` are the new-line and tab characters. Every file and directory has a unique **absolute path** in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by `'/'s`. Using the above example, the **absolute path** to `file2.ext` is `"dir/subdir2/subsubdir2/file2.ext "`. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form `name.extension`, where `name` and `extension` consist of letters, digits, and/or spaces. Given a string `input` representing the file system in the explained format, return _the length of the **longest absolute path** to a **file** in the abstracted file system_. If there is no file in the system, return `0`. **Note** that the testcases are generated such that the file system is valid and no file or directory name has length 0. **Example 1:** **Input:** input = "dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext " **Output:** 20 **Explanation:** We have only one file, and the absolute path is "dir/subdir2/file.ext " of length 20. **Example 2:** **Input:** input = "dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext " **Output:** 32 **Explanation:** We have two files: "dir/subdir1/file1.ext " of length 21 "dir/subdir2/subsubdir2/file2.ext " of length 32. We return 32 since it is the longest absolute path to a file. **Example 3:** **Input:** input = "a " **Output:** 0 **Explanation:** We do not have any files, just a single directory named "a ". **Constraints:** * `1 <= input.length <= 104` * `input` may contain lowercase or uppercase English letters, a new line character `'\n'`, a tab character `'\t'`, a dot `'.'`, a space `' '`, and digits. * All file and directory names have **positive** length.
null
String,Stack,Depth-First Search
Medium
null
662
today we are solving maximum width of a binary tree given the root of a binary tree we need to return the maximum width of the given tree among all the levels where the width of one level is defined as the length between the end nodes where these end nodes have to be non-null nodes to find out what exactly non-null nodes to find out what exactly non-null nodes to find out what exactly are these null nodes we need to compare this tree with a complete binary tree where in a complete binary tree each node except for the leaf node is supposed to have two child nodes in this example tree we notice that node C is missing a child and this missing child is the null node this node cannot be the leftmost or the rightmost child in that level but if it's in between the nonnull nodes like here it can definitely be counted towards the width so the width at each level for this tree is at level one withd is zero because there is only one node we need at least two nodes to calculate the width for level two there are two nodes so the width is two for level three there are three nodes but there is a missing node as well so the total width of level three is four and we need to return the maximum width among all the levels which is four from level three so we return four let's look at another example here is a different example to find the width at each level we have to first convert this tree into a complete binary tree this is the complete version of the same tree so the width at level one is zero because there's only one node with that level two is two level three is three and level four is seven we did not use the null node over here because the leftmost and the rightmost nodes has to be non-null nodes so we can nodes has to be non-null nodes so we can nodes has to be non-null nodes so we can get rid of this null node at the bottom right and we return seven because that's the maximum width do we really have to convert the given tree into a complete binary tree before we could calculate the width at each level no because all we need is the count of the non-null we need is the count of the non-null we need is the count of the non-null nodes hence we do not have to convert the given tree into a complete binary tree how do we get the count of the null nodes at each level to find out let's number these nodes starting from zero at the root node if we take a closer look at these indices for nodes we can notice a pattern index of the left child is 2 * the index of the left child is 2 * the index of the left child is 2 * the index of the parent + one and index of the right parent + one and index of the right parent + one and index of the right child is 2 * the index of the parent child is 2 * the index of the parent child is 2 * the index of the parent plus two we can verify this for any other node in the tree index of this node is 2 * 4 + 1 and index of this node is 2 * 4 + 1 and index of this node is 2 * 4 + 1 and index of this node is 2 * 5 + 2 once we have these indices is 2 * 5 + 2 once we have these indices is 2 * 5 + 2 once we have these indices it's easy to find the width at each level all we have to do is index of the rightmost node in that level minus the index of the leftmost node in that level plus one which is four I apologize for the typo here this should have been four at level four index of the rightmost child is 13 - 7 which is the index of child is 13 - 7 which is the index of child is 13 - 7 which is the index of the leftmost child + 1 gives us the leftmost child + 1 gives us the leftmost child + 1 gives us seven let's try to apply this relationship in the original tree and look at the indices again let's go back to the original tree here is the original tree again let's apply this formula to the stre we start with index of zero for root node index of left is 2 * 0 + 1 is 1 index of right is 2 * 0 + 2 * 0 + 1 is 1 index of right is 2 * 0 + 2 * 0 + 1 is 1 index of right is 2 * 0 + 2 is 2 and we repeat the same index of left is 2 * 1 + 1 which is 3 index of left is 2 * 1 + 1 which is 3 index of left is 2 * 1 + 1 which is 3 index of the right is 2 * 2 + 2 is 6 index of the right is 2 * 2 + 2 is 6 index of the right is 2 * 2 + 2 is 6 index of left is 2 * 3 + 1 is 7 index of left is 2 * 3 + 1 is 7 index of left is 2 * 3 + 1 is 7 index of left again is 2 * 6 + 1 is 13 so to calculate again is 2 * 6 + 1 is 13 so to calculate again is 2 * 6 + 1 is 13 so to calculate the width at each level all we have to do now is index of the right most child minus index of the leftmost child + 1 so minus index of the leftmost child + 1 so minus index of the leftmost child + 1 so 2 - 1 + 1 is 2 - 1 + 1 is 2 - 1 + 1 is 2 6 - 3 + 1 is 4 13 - 7 + 1 is 7 and we 2 6 - 3 + 1 is 4 13 - 7 + 1 is 7 and we 2 6 - 3 + 1 is 4 13 - 7 + 1 is 7 and we return seven so to solve this problem we can apply bread first search starting from level one and process these nodes level by level at each level we calculate the width by getting the index of the rightmost child minus leftmost child + one and we repeat the same for child + one and we repeat the same for child + one and we repeat the same for all the levels so the runtime complete complexity of this approach will be o of n because we'll be adding each node once to the Q and we'll be popping the same node once out of the cube the space time complexity is also o ofn because in the worst case we'll be adding all the nodes to the CU let's write the code for this algorithm let's initialize the max width to zero and we have to do breadth for search starting from the root node let's add root node to the Q root and index of the root node we start with is zero while the Q is not empty we process all the nodes at this level so let's call this length of this level is length of the Q to calculate the width at this level we need the index of the left node which is always the first element in the queue at that level so left index is the first element of the que this one now we go through each and every node in that level for's goore in range length of the level we pop the node and it's index let's call this right index q. pop from the left of the Q let's update the max withth if the new width is greater than the previous width new width is Right index minus left index + one next we add the child left index + one next we add the child left index + one next we add the child nodes to the next level if the node has the left child we add that to the Q node. left and the index of this node will be index of the parent node which is right index into two * + one we do the same if there is a * + one we do the same if there is a * + one we do the same if there is a right node we append node right and the index of the right node will be right index which is the index of the parent into 2 + 2 and we repeat of the parent into 2 + 2 and we repeat of the parent into 2 + 2 and we repeat this for all the levels and finally return Max width oh there is a typo here let's fix the typo let's try to run this code the submission goes through if you found this video to be helpful please support by liking the video and subscribing to the channel and I will see you in the next video thank you
Maximum Width of Binary Tree
maximum-width-of-binary-tree
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. It is **guaranteed** that the answer will in the range of a **32-bit** signed integer. **Example 1:** **Input:** root = \[1,3,2,5,3,null,9\] **Output:** 4 **Explanation:** The maximum width exists in the third level with length 4 (5,3,null,9). **Example 2:** **Input:** root = \[1,3,2,5,null,null,9,6,null,7\] **Output:** 7 **Explanation:** The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7). **Example 3:** **Input:** root = \[1,3,2,5\] **Output:** 2 **Explanation:** The maximum width exists in the second level with length 2 (3,2). **Constraints:** * The number of nodes in the tree is in the range `[1, 3000]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
1,510
hey what's up guys this is sean here again so let's take a look at today's daily challenge problem which is number 1510 stone game number four okay so this is the fourth problem in the stone game theory so again alice and bob are playing a game and with alice starting first so now this time they're not the peak they're not picking the stones instead they're trying to remove the number of stones and the rule of removing the stone is they can only remove the stones with the square number of the stones which means that they can only remove the stone with 1 4 16 right and then 25 36 so that's the options they can do to remove the current stone okay so and it asks you to return basically the boolean to tell us if this number of stones can alice win the game otherwise false and assuming both players play optimally right and then it gives you the few examples here so i mean if you guys have seen or have done the uh the previously stone game problems you know basically this is another like stone game theory right basically one player plays it plays first and the other one will play the next and assuming both players will play optimal okay so for this problem you know we have like and then what's going to be the base case right so like this problem is telling us right so when the number is zero so who's playing the dp basically the dp0 is always empty this one is false okay so it means that at with zero remainings the player who is playing will be i mean we'll lose the game okay right so that's why we have dp zero equals to false how about dp1 here right so dp1 is true right because this player can just take one can take one and then the zero will uh the zero one will be uh the false that's why because he can take one and to leave zero at i mean the other players with false that's why the current player will be true right so for the same thing we mean two is what i think two is like it's false yeah two it is it's fast so why is that because this player you know remember each player will try to play smart optimally so play optimally means that as long as there is a chance for this player to win the game he will go to that direction right and if all the possibility moves for this player give him a of give him well i mean will not make him win then he has no other options but to accept his failure for example this one because he only has one movements right here has one moment that's why which is one that's why idea he will he'll get false right and then how about dp3 here so dp3 is i think something like he can also do a the only movement he can do is one but since two is false of course so t is true because two is definitely a loose and that's why making three here is a win here so p here is four so before what do we have it can either go we'll go with one or it can just go with four right so with four is definitely true here because he can just remove everything that's why remember playing out optimally means as long as he can win he will go that direction right so now with this kind of in mind here you guys probably can see the dp transition function here right so with dpi here so this one means that you know if this player can win with this remain uh this stone remaining so what's going to be that so if any dpk is false k is what k is from one to what one to the square root of i right and probably plot plus one something like this because that's the only thing he can right he can go and then we'll return true for this one otherwise false yeah i think that's it you know that's the basic state transition function for this problem and then we so with that we can simply use either top downward or bottom up you know let's try to try top down here so this top down is pretty straightforward we have our current right the current is like this and then i we simply return the dp dpn okay i'm going to use like a trick here to help us re do that the caching here for the top down so that we don't need to write that you know the memorization stuff like i said so the current if current one is zero and then it means that okay so this one is current is definitely a loose which is going to be returning false otherwise right otherwise how are we going to check the current one is for i in the range of what from one to um to end of the square root of the current and do we do a plus one that basically that's the range we can that's the basically the other possible stones we can take with the remaining one right and among all those remain those possibilities as long as if there is like a dp after taking this i we have i uh two right that's the remaining stones as long as there's like uh a state that can tell to make the other person a lose you know we will go to that direction which means we find a winning strategy right and then we return true here otherwise you know if there's if and if there's no way the current one any of the strategy will make us a win so like i said we have to admit our failure here accept our failure which means we'll return fast with the current one right and as you can see that's why we can simply return the n here so return n means that you know is the current and can we win or not basically this one is it's always is telling us a true or false and with the current state we can use the uh the next the previously state or the next state to telling us if we can find a guaranteed winning strategy right for the current number here yeah so that's that and we can return run the code here submit yeah cool so it's accepted right so about time and space complexity right so the time complexity is the uh you know in total we're gonna have like uh we will have like in total off n cost here and for each of the off in car and we'll do it like this right so that this is going to be uh what it's going to be of n times yes uh and to the 1.5 yes uh and to the 1.5 yes uh and to the 1.5 right the power 1.5 which is the n times right the power 1.5 which is the n times right the power 1.5 which is the n times uh square n something like this right that's going to be the space time complexity and space complexity this is the time space complexity is the o often that's the number of the uh the dp cost okay so that's that okay it's pretty straightforward right so i'll just quickly write the bottom up so for bottom up is pretty straightforward so the same similar idea here so we're gonna initialize with everything with m plus one here okay so again so for the top down right so from current state we're trying to go to the next state and we're getting the result from the next state with the base case and for the bottom up right what we're doing here is where we are like looking uh we're looking back backwards right we're going we're looking back basically you know so with the current dpi here how can we set how can we determine if the current dpi is true or false similar as this one okay since we know that dp0 is false right so we know the dp 0 is false all we need to do is just like we're just using the same formula here so we need we didn't have a k here i think in the range of uh i'm going to copy this thing here right so square i here so basically at the current with the current i here can we find any previously state that is a guaranteed loose for the other person right be so that you know if this dpi is the dp i minus k to the power of square two right the power of two it is a false okay then we know okay since this state can give us to make the other person a definitely lose well that will just go we'll just uh go with that route right so basically we'll simply check set this one to true i mean if none of this works basically they will it will stay at its fault since we are setting everything at fast first right and then in the end we simply return the dpn okay yeah here we're starting at stone one because for stone zero we already know the answer right that's why we just start from one here yeah i'll just run this yeah i don't know why it's taking that long let me submit it one more time here oh sorry i think i know why because uh we forgot to break it that's why it's so slow here okay yeah so now it's much faster because you know like since we already find a winning strategy there's no point to try other scenarios right because as long as we know there's a winning strategy can guarantee us a win we'll definitely go with that so that's that and as you guys can see here right so here so this one is the top down okay and this one is the bottom up right so as you guys can see the top down use a lot of much more memory than the bottom up even though they have a similar running time here so why is that this is because you know we will they will need more space to store the state the status or the callback information for each of the recursive call here while in the top in the bottom up solutions all we need is this dp array which is the o of n the space right so that's the everything we need actually even though you know in the top down in theory it's all of n but in the reality is much more it's much more than that than the o of n because we'll because we have we didn't count the space we need to keep the state of each of the recursive call that's why you know if we can use like the bottom up try to use the bottom up because it's much more space efficient you know okay so as now as you guys can see it doesn't this is uh much clearer right so the space time complexity this is a we have o in here and later on here we have like what times o we have an end time n times here right square of n cool yeah i think that's it for this problem you know it's a pretty straightforward problem the only difficulty for this problem is that you just have to be able to understand the i mean the concept of this game theory you know i highly recommend you guys uh try to solve the other three stone game problems even though those three problems are for different uh strategy and we'll have a use of different uh solutions yeah but i it's worse it's worth doing it will help you understand the game theories i mean how what does this kind of optimal uh play optimal means right and i as for this problem is that as long as we have a winning point a winning strategy we'll go with that and otherwise we have to accept our failure and we'll repeatedly use this one to help us to determine if this current player can win or not right by looping through our options here cool i think that's it for this problem thank you so much guys uh for watching this video stay tuned see you guys soon bye
Stone Game IV
find-lucky-integer-in-an-array
Alice and Bob take turns playing a game, with Alice starting first. Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer `n`, return `true` if and only if Alice wins the game otherwise return `false`, assuming both players play optimally. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** Alice can remove 1 stone winning the game because Bob doesn't have any moves. **Example 2:** **Input:** n = 2 **Output:** false **Explanation:** Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). **Example 3:** **Input:** n = 4 **Output:** true **Explanation:** n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0). **Constraints:** * `1 <= n <= 105`
Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them.
Array,Hash Table,Counting
Easy
null
897
hello let's start with another interesting problem so they have told us that given the root of a binary Source tree rearrange the tree in order so that the leftmost node in the tree is now the root of the tree and every node as no left child and only one right child so let's understand this using example so basically this is our binary tree and we have to convert it to this so five uh is our root node and it will start and first it'll uh check for left elements so left three is there then three will check for it left two is there one two will check for its left one is there okay so basically what happens in order travel same thing so one will be um put first so one should return first and then one will check for its right nothing is there so we'll go back two then two will check for its right nothing is there null is there so it'll return back and then it'll go back to three now three has a right element four so four and four has nothing in Left four has nothing in right so four then four will be alloted after three and so on it will return to five will um check its right so six and then six will uh check its right now um before allotting it will check its left so left element is there seven so when seven returns then eight will be allotted and nine will be allotted basically this is what we have to do so another example is given five and seven so basically you have to go to leftmost first one and then you have to check um back so five and then seven so this will what be allotted so let's understand the logic of this code hello so let's start with the logic of the code so let's declare this as our root node okay this is our root node now what will be a strategy is uh see we have to U check elements in order right so our strategy should be to check everything to the left of this node right so first we'll check everything to the left of the node because left only smaller elements are stored right so everywhere you can see suppose three was the root node left to it is smaller element two right to it is bigger element four right so our strategy will be to just check everything to the left of it so starting with five our root node we'll check everything till the uh left note is reached U that doesn't become null so five will go to three will check to two and two will check to one and then one becomes left of one is null so it'll return back and then we can uh add one okay so one will be our first element that we are adding now next element that we should add let's see how we'll obtain that so now one has uh one we have got now to one's right we'll check now to one's right nothing is there right one's right has nothing so we'll just return and then we'll add next element so now we'll add two okay now we have added two now going back now two's right also nothing is there so that will also return and now we can add three okay now we can add three now uh three is Right four is there okay so we'll check for four if Force right if Force left has anything Force left has nothing so we can add four right four is clear we can add four now we'll check Force right nothing is there so we can return back so then this will also return so now for the root of three left side is also written right side is also written and then we'll go back to five so now five is for five side left has returned right so we can add five so next we'll add five so this is separate not to confuse so this is what we have to return this is the thing we have to return and this is our actual uh binary tree okay now to five left everything is clear so we can add five uh in our uh tree now going to five's right is six right so uh five's right has six now checking six left so six has nothing in left so it's left will return then we can add six okay so six is added now checking to six right we'll check 8 is there right so8 is there so8 will check its left first so it left is seven now to Seven's left nothing is there so it'll return so this has return so Seven's left is nothing so we'll add seven now going back so now uh eight left has return right Eight's left was seven s's left was null that returned so then seven return Then seven was Eight's left that is written now we'll 8's left is clear everything is written so we'll add eight now moving on to Eight's right so eight right is uh 9 so we'll add N9 okay now we'll return back so Eight's right has written after Eight's right has written eight will return back to six and six will return back to five and then five will return back to our function so this will be our strategy now for this we'll have to add another um pointer also so we'll call it uh zero sorry another node we'll have to add so we'll call it zero because see something has to hold this right something has to hold this initially so that we call pointer and something has to Traverse throughout right when we are going left we are going right so something has to travel so that we'll call head so initially We'll add zero so that something is there to hold uh the initial value so this should be a strategy so you'll write the code then you'll understand it better so let's start coding for this so basically uh let's start with what we have to do first so first let's declare a recursive function where you're going to use recursion so I'll just call it binary s short form for that I'll just call it bstd so I've declared a recursive function and I'm going to pass to that my own root okay and then I have to return something uh back from this recursive function that will be the output right I'll send the output back which will get printed so I have to basically send the starting node so basically this is what we have to do now let's uh declare the recursive function but before declaring the recursive function bstd I'll declare a head and pointer node so I'll declare head and pointer node so tree node star head declare it set and new uh so uh I'll declare to its Constructor variable I'll have to pass values to declare it so this is the way to do it so Tre node star head is equal to new Tre node and I'll give its value zero so that you can give any random value doesn't matter it won't even matter in the last I'm just uh declaring it so that it holds the topmost node and now I'll declare pointer for traversing so declaring the pointer which going to Traverse throughout so tree node star pointer I'll just call it PTR for short and it's going to start with head okay so then this is going to uh so pointer is going to hold and um head is going to uh Traverse okay so my head is going to Traverse throughout and my pointer is going to hold this head pointer initially so that it doesn't get lost okay now let's uh move on to declaring the recursive function so in C++ you'll also have to function so in C++ you'll also have to function so in C++ you'll also have to declare the type so I'll declare it as void so vo BST and it's receiving uh root node right so I'll have to give three node star root so that's what it is now let's start with this so first condition will simply be if root is null whenever root becomes null right you have to Simply return okay so this will be the first condition now uh when we have got hold of the root node it should check left side it should check if left side any value is smaller than it right so because it has to go in order wise so this should be the order through which it has to go so it'll just check if uh left side of its value is smaller like five will go to three first three will go to two will go to one and if left side is cleared then it will go back to our root node so you have to keep on checking if the left side um has values or not so we'll have to uh do this recursive call so BST of we'll have to do root left Roots left so it'll keep checking until it becomes null it'll return so after it is return that means left side no more smaller values than that are there okay then we can uh store this value into our um binary tree so to store that value what we'll have to do is so heads right so head is the topmost right so head's right that is to the zero thing we going to attach now we going to attach one in this example so to zero we are going to attach one so one would have returned back and come so now we have to attach one so heads right that is we are going to declare new TR node and we are going to give the same value that has returned so Roots value basically and will allot a new uh root that will attach to one and its value also will be stored so zero is attach to one now this is our bin T Zero's right is holding one now we'll also have to make head is equal to head Star right so that it can go to next time it will allot something it can go to this okay now we'll also so left has returned and it has come back to the root now root has to check if right side also some elements are there or not and so for checking right side we'll have to again give BST and we'll have to give root right just check recursively again if the right side has any values or not and again the same thing will happen right so right node uh notes will get cleared off so basically this should be our function and uh finally it'll return so you can give a return here in the end if you have any confusion so that you know after the right side has returned then um everything is cleared and it will go back to the next note you can even avoid this return because it's just a void function so anyway after the statement it's any going to read the end of the uh function and it's going to return automatically okay now what we have to return so we have to return the pointer element that is holding the top but pointer will be holding zero right because pointer is Reed as head and head is holding uh this U root that has zero in beginning so basically you should return pointers right so that it starts from one so that you'll have 1 2 3 4 5 6 7 8 9 return and I'll run and check if it works and I'll submit and check see it's working
Increasing Order Search Tree
prime-palindrome
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9\] **Example 2:** **Input:** root = \[5,1,7\] **Output:** \[1,null,5,null,7\] **Constraints:** * The number of nodes in the given tree will be in the range `[1, 100]`. * `0 <= Node.val <= 1000`
null
Math
Medium
2202
1,019
hi guys how are you I hope all you are doing good welcome to the learn code easily so today we will solve next create a node in linked list and this is our next question in our stack Series so I hope you have already accessed my stack series because we are I'm solving the numbers of question we have done the easy level question and we have moved on to the media level question and in the medium level we have sorts of the questions so if you haven't accessed the playlist access it and if you like the content then like the video and subscribe the channel so there are two series I have made one is the uh stack and second is the easy level so you can access both of them so let's move to what I want towards our question is just mention my point here next crater not the greatest one okay so for three five four but for seven there is no so that's why here it is zero because we are not able to find for two it's seven so if we have something 4 comma 5 comma 6 so here what will be the output will be 5 comma 6 comma zero so here 6 is less greater element for 5 but for four caps how uh so let's wait a minute let me know so let's do our question foreign so here we have given that so first what we have the load list okay so the link list can be any number it could be increasing it could be decreasing it could be combination of okay so we are taking one of the linked list so that is so let's take this here so if we have a one comma 5 comma 2 comma 3 comma 6 comma 10 okay so now this is so uh it is a list but we have linked list okay so we have an English something like this one okay so first we will Traverse this one we will Traverse and we will store uh we will store all the element in a list so that is my list so ignore this one just take this one as your input okay so this is not input what you need to do first step you need to Traverse so this is the first step what we do we need to Traverse now the second step is we have list okay now we will take one of the uh you can take the stack as well you can take this one as a stack so let's take as I stack I have stored already even in stack now we have a stack I will take one of the list I have a snack okay now I have the I have resultant list okay so all three are listed now how we will solve so I have one five two three six then okay one five two three six ten now I have EA I have this one I have like this one but or you can just take this one as one five two three six ten so one five two three six ten so I will go from backward Direction okay so now I have a second stack uh I this is a stack now this is list and this is the resultant list okay and what will be the output of this one let's say let's write the output will be for one we have a five for five we have a six for two we have a three for three we have a six four six we have a ten for six we have a ten one two three four five one two three four for ten we have a zero okay so I hope this is clear so this is output so we are going to store this one here in this list okay so first of all I first of all what I will do I will check whether my list is empty if my list is empty so in the list I will store one and in the resultant I will store 0 I am I will write here again 5 this is 6 this is 3 this is 6 this is ten and this is zero so as so our resultant is going to be a story in this manner from back by Direction so four five so what I need to go into the backward Direction so first I will check if my list is empty yes so I will store 10 here and resulted in a result is zero now I will compare my this one because I am going in a downward Direction and this is an upward Direction and this is the upward Direction so if my value 6 is greater than 10 yes that is so before inserting first I will get the value from the list so I am just inserting here L of minus one every time this is the L minus 1 and this is the condition for inserting in this one for condition of inserting in this one is this one so simply I will insert 10 here now I have insert the six now when I have come to 3 so list of minus 1 that is 6 is greater than what three huh so I will insert here uh 3 but with but before inserting three first I will get the value from the list 36 now I will commit to so 3 is greater than 2 yes so first I will get the value that is 3 then I will insert 2 now I will came at 5. list of minus 1 it is 2 that is greater than the current value of Stack that is 5 no so I will pop it out now at this place it will come 3 again I will pop it out now at this place it will come 6 okay when it will be 6 yes it is correct so before inserting here uh six is greater than 5 yeah so before inserting five first I will get the value what one what will be the value 6 then I am setting here 5. now 1 okay so it is correct so first I will get the value that is 5 then I will insert the value that is one so here we are storing we are working on we are working like a step so here we are inserting one element one and we are popping may or may not be we are popping but we are not inserting one element more than once okay so this is our output 0 10 6 3 6 then 5 I hope this is clear to you so yeah um as it is first I need two Traverse so head to America so first click as well then as I stack then we have a resultant list okay foreign but before going to the next we need to insert the value in the our list now this is done now I need to run one of the loop that is l that is I greater than 0 so we need to go from the backward Direction okay so that's why I need to initialize my pointer to the end of the list so this is them now my second Loop is if my stack does not request to empty and if my step key value my stacky value again or eight minutes later score mm-hmm ultimately okay foreign if that is less than list of emre list because we are working on this one as a stack so this is the cellist which are storing all the values so Industries so when we are restoring when our this is list foreign so this is list this is stack so let's so because I have taken the same name this is list now my stack so um so if my uh if my stack otherwise foreign us foreign so that is it is current value is greater than stack of minus one because my current value is a bigger one so I need to pop every time from the stack s foreign minus one foreign so that will be three so yeah fourth reasons foreign first I need to get the value from the stack that I have told okay now I am getting the value now in the stack I have only minus five so first I will get the value then I'm storing them so let's try to run and here is okay l dot open next head of head is equals to head dot next okay minus one because we are I have already told that we are installing in so storing this value in this manner so I need to reverse it as well so this has been run let's try to submit it has been submitted as well so I hope this is clear this is big offend solution and big off and time complexity uh spaces as well because we are so we are taking big offense solution and we are running only once we are popping and pushing all the uh one element once in a stack so this is bigger of any time complicity as well I hope this is clear if you like the video Please Subscribe the channel and comment in the video and like the video as well I will meet in the next video with the next video till then bye take care
Next Greater Node In Linked List
squares-of-a-sorted-array
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Array,Two Pointers,Sorting
Easy
88,360
1,669
all right let's talk about the merging between linked lists so you are given two linked lists this one and these two and there are sets of m and m so you have to remove this one no from eight from a note to b note and then put these two in their place so basically like um you are giving a and b in this one and then you have to remove and then basically you have to connect the one before you remove two at the end you have to connect your list to uh list2.nx to the rest of the node uh list2.nx to the rest of the node uh list2.nx to the rest of the node after you remove right so uh this is supposed to be easy just have to think about it because uh the problem is how do you determine the pointer right so uh basically you need to drivers right traverse from this place to this place not this place because when a equal to 3 this is irrelevant to the linked list right you have to say a equal to two somehow all right or when you traverse right you don't want to traverse at this point but for the end you have to traverse at the end so uh you can create a full loop and then um for the first one you have to create two uh just in case you forgot because uh this one you don't want it right so you want to know uh you keep a record for here so this will be let me say s and you will still keep traversing and then you want to get rid of this right and then you want to find out why so new uh new connection be honest and i'm going to call n right here so when i have these two know i can actually just comment let's start next to list2 right and then when s2 dot uh dot next equal to the end and they actually turn in the end to the end so this is pretty much it and it does take a while to just um find out the next point to be honest so i have a list no i'm going to say formation song comment on install okay unless i go to this one and connect and i'm going to just um okay uh let me do this later so i when i traverse i'm going to traverse from one to a and then i increment so the reason why i started from one to a this is because um i don't want this i don't want to traverse on one to two i mean from zero to two right because if i traverse from zero to two i already uh i already skipped this note right so if i traverse from one two uh one two three right well from one to three i will stop at this point if i travel traverse from zero to three uh i will basically end at this point but i don't want to be and i will say connection star connect all right so at this point my comment style will stop at this point and then i will create another one which is from that n from net okay and this command end will just temporary equal to connect stop first then i will just keep traversing my connect uh command valve i mean sorry from a to b right and there's here's a for loop so i will say commit star dot vowel to i listen to the bi plus and i will say connect this is connect right on next and you go to comment on the next all right so afterwards uh my end will be at this place right so if you don't know why i use less than equal this is because i don't want this note if i say less than i will keep this note and basically this is how it is right and my connect start about this is two right so i'll just keep traversing right and at the end uh after i know my starting and end i'm going to connect the linked list with link the list 2 right so i will say connect start.next right so i will say connect start.next right so i will say connect start.next it's going to be list2 now if i know the list i'm going to traverse the list 2 to the end so while this 2 dot next is now uh i cannot go through the end of the list 2 which is a no i need to make sure my last node is still valid right so let's do the list two dots and at the end i'll say this 2.x equal and at the end i'll say this 2.x equal and at the end i'll say this 2.x equal to connect okay right and after i would just have to return this one it does uh it does look a little bit confused but just think about it so let's talk about timing space so for the space i only create two a variable so i'm going to say constant and for the time you do have to traverse the this one and these two completely so every single note in this one right you need to traverse every single in these two you need to traverse so time it's going to be uh all of un i mean n1 i'm going to say n1 represent this one plus and two so you have to determine which one is greater so the maximum between this one and these two right because i traverse uh traverse my this one individually traverse my list to individual and this is pretty much the solution and just have to think about that when do you actually break i mean if you want to go really uh specific for the time you have to know that when do you break and then this leads to the length is actually shorter than the brick i mean the this one down length when you break so this is pretty much the solution and i will see you next time bye
Merge In Between Linked Lists
minimum-cost-to-cut-a-stick
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Array,Dynamic Programming
Hard
2251
382
Hello friends today I am going to solve liquid problem number 382 linked list random note I have also created another video solving the same problem using o of n time complexity but o of one space complexity now in this video I am going to solve this problem using of 1 time complexity and um using off and space complexity so let's see how we could solve this problem before that let's see the problem statement so we are given a single linked list and we need to return a random node value from that linked list and each node must have the same probability of being chosen so now we are given a solution class and we need to implement these two functions the first one is the solution function which is the Constructor and the second one is a get random function The Constructor is passed ahead argument and we need to initialize our object using that heat and in the gate random function we need to choose a random node from the linked list and return the value of that node so how we could solve this in um constant time complexity but oau of and space complexity so let's look here so initially what are we going to do is since this is a linked list we always start from the first right so let's suppose I want to reach a second node I want the value of the second node we cannot just uh use index signal just like in case of array that has the valid indexes 0 1 and 2 N that would give me the value of this second node instantly in of one time complexity however since this is a linked list we start from node 0 and we keep on iterating until we reach the node at index 2 right so this basically would take in the worst time of and time complexity and in case of array where we have the indexings that would only be in O of one time complexity right because we have the indexes and we can always access the value of the array at that index using the index indices right so that is what we are going to do we are actually going to convert our linked list into an array and then get the value of or um value at a random index and that would be our final answer so what we need to do is we need to first of all create our array so that is what we are going to do in our Solutions function and then in kit random we are going to generate a random um integer a random index that would be in the length of this array so that would be less than three and between 0 so how are we actually going to generate that random number so in JavaScript we have a math dot random function we are going to use that method random function to generate a random number however in JavaScript this method random uh function only generates a random number between 0 and 1. so how are we going to get a value at in value that would generate a value between 0 and 2. so basically what we need to do is we just need to multiply this whole thing by the length of our array so that would give us the random number that we need to that we need between 0 and the length of this array so how is actually that working so let's just suppose uh the random number generated is 0.3 and once we multiply a generated is 0.3 and once we multiply a generated is 0.3 and once we multiply a random number with any of the number the resulting number will always be random so let's just multiply it with the length of this array which is equals to 3 and the result would be equals to 0.9 3 and the result would be equals to 0.9 3 and the result would be equals to 0.9 so in this case we are going to only choose the use the floor value of this integer because we know 0.9 index doesn't exist because we know 0.9 index doesn't exist because we know 0.9 index doesn't exist right so we are going to use the floor value that would be equals to 0 so at index 0 we have the value 1 and we return that value what about we have a random number that is 0.7 if we multiply random number that is 0.7 if we multiply random number that is 0.7 if we multiply it by the length of the array we get the value to 0.1 right and since we are value to 0.1 right and since we are value to 0.1 right and since we are using the floor value we get the value at index 2 and that's equals to three what about we multiply it by one so if we multiply it by one actually it doesn't return the value one the random will never return a value when it will only return of value 0 to 1 exclusive so uh the max value we could get is 0.9 uh the max value we could get is 0.9 uh the max value we could get is 0.9 times 3. so that will return us a value equals to 2.7 so the floor value will be equals to 2.7 so the floor value will be equals to 2.7 so the floor value will be equals to 2 and that will be our last element actually since it's re it's from the value from 0 to 1 the last value could be uh zero point nine that would still be less than three so our floor value will always be equals to 2 for that case and we will never exceed the length of I mean we will never exit go out of bound of this array so that is what we are going to do we are going to use the random method random function to generate a random number and then multiply it by the length and that would give us the random number and we are going to use that random number to get the value at that index so let's create our solution so first of all we are going to create an array from the linked list so um let this that array be our new array now we will iterate over each of the value in our head and add those to our array now once we have added these to our array we have our we have done create to done with our Constructor function now we are we need to get a random value so let random value will be equals to so we are going to use the floor value and then we are also going to use the random function from JavaScript and multiply it by the length of the array so this dot array that length gives us the length and this would return as a random value now we are going to iterate over that random value until and unless we reach that index so starting from I equals to 0i is less than random value actually less than or equals to random value I plus and um we actually do not need this so now that we have our random value we are going to return the value at that index so we are going to return this that array at Rand value index now let's try to run our code and check if everything works fine awesome let's submit it great so as I already told the space complexity for this solution is of uh the get random solution is of one time complexity and space complexity is also of one however um yeah the get random function since it uses an array which takes an external length so that is of n space complexity but the time complexity is reduced to all of one and this solution this is also of an space but uh diam complexity is also of n however since the solution will only be called at once in the beginning and the gate random function will be the function that will be called most of the time as you could see in this example that we are only calling the solution function one and the gate random most of the time right so uh we would that is why we are um solving the problem in of one space complexity we should give us the most optimal solution
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
252
so today we are going to talk about this question meeting rooms so uh let's see the description for this uh question so given an array of meeting time uh meeting uh time intervals can uh consistent for starting at the ending time so uh let's see this example um so uh the first value is the starting time of the meeting and then the second value is ending time of the meeting so this question is asked to determine if a person could attend all the meetings so let's see the example over here um the uh the starting time of this meeting from zero the ending time is eight and then another meeting is a uh to ten so in this example we can see um there's no over uh overlapping so uh it will return true so it's not uh so this example is not a conflict at eight so that's why this one um return true let's see another example so um let's see here so uh this meeting okay so this meetings data uh started okay just one second okay so this meeting started uh zero and then ends at 30 and then after this meeting started and then another meeting started at a 5 and then and that's at 10 and then another meeting started at the 15 and then the 20. so we noticed that um the starting time of this meeting is five and then the ending time of this meeting the 30 that means the uh the second meeting is actually overlap with the first meeting so uh th this will return uh false because uh he here actually have a overlap here but for this example we can see the eight and eight so the first meeting ends at eight the second meeting start at eight so there's no over left here so that's why this one will return to true and then this one return to false okay let's look at this uh example like um uh let's draw the land okay just one second yes which we can just draw the land here oh um okay so let's explain in this way let's uh look at the first uh let's look at this example let's look at the uh first two uh interval available here so this is the first one this is second one right okay the first thing we need look at it is the ending time of the first interval and the starting time of the second interval okay for us to detect this uh two this um this ending time under this starting time if they are overlapping is very simple so if the starting time of the second one is before the um the ending time of the first meeting that means is the uh overlapping okay that means is uh overlapping that's very simple right very simple in that case that means there's a overlapping rate so but in this uh example the ending time is a three for the first meeting and then second meeting the starting time is a three so that means there's no overlapping right so in this case we return true okay so now my question is do we have to like uh compare the and the time of the first meeting and the starting time of the third meeting do i have to um do we have to compare this to um actually we need to do sort the input uh the studying time of the first meeting study in terms of the second meeting starting time of the third meeting says input we just need to actually sort the input of the meetings so after we start the meetings we know that the um the third meeting is not earlier than and then the starting time of the third meeting is not earlier than the starting time of the second meeting so um that's why we need to do sword first and then we just compare the next meeting the starting time or next meeting uh with the current one with the and the time of the current ones so uh in this way uh there's no way this the starting time of uh this uh interval uh will come uh come before this interval because we uh we know that this uh the this interval starting time is going to come after uh this interval starting time so we don't have to check uh the starting time of this one under this one so now we just check this interval uh let's use this color okay we just need to check this interval and at this interval because we just checked this the first interval and the second interval now we check the second interval and the third interval okay and when we're tracking we notice that the starting time of this interval is to come after the starting time of this interval so there's no over uh lapping right so we just need to compare the each uh agent pair of the intervals like the first one second one and the second one with the third one we just compare the uh agent uh pairs okay that the that's the basically the solution is okay so this question basically the idea is the basically idea um the basically the idea is gonna be like first we're gonna sort the starting time of each intervals and then compare the agent again to the interval pairs okay so the time con complex conflected for this problem gonna be because we have to sort we need to sort the uh starting time of the intervals so the uh the time con complicity gonna be uh o n log n okay so this is uh basically the solution okay so in this particular question uh we haven't started the first step we're going to sort of the uh each uh interval okay um yeah the uh the this is a code so uh here as a corner case so if the interval equals to none or the interval equals the length equals to zero then we just simply return true and then we saw we sort this array uh but we just sorted the uh yeah we started this array um the start time of the uh interview okay uh interval okay from here um just put the interval and we knew a comparator and the type is inter array here and then we just uh compare uh a and b and then yeah and then we return this kind of the on the fun it basically and basically here we just uh kneel and uh comparator here and then we uh we put the input as the inter array and then we write as a compare uh kind of the starting time a and a b and then uh and then return this and then this part is we need the starting time of the first interval so the starting time of the first interval we call it um prev and then we start from i equals to one we started from one and then this part is smaller than the interval length and then the current one the first current of line should be interval one okay so the and then uh if the pre one greater than um the rule and here if the um previous ending time greater than current starting time they then will return the false otherwise we return true yeah this is careful the code let's try uh run the oh okay yeah sure this is code yeah uh it will work i need to actually login um thank you for watching uh see you next video
Meeting Rooms
meeting-rooms
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** false **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** true **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti < endi <= 106`
null
Array,Sorting
Easy
56,253
1,026
Hello hello guys welcome on donkey week singh krishna singh difference between noida and system subscribe must subscribe veer channel subscribe must subscribe like and subscribe subscription thanks a drama b r country and give another problem the number of verses result subscribe And subscribe The Amazing subscribe Video subscribe to jhal and ads and will Twitter The Difference Jai Hind is saal par method ki not known s ki both what is nal dhund ki datt means the minimum maximum benefit hai ki shuddhi etc minimum should be from It is maximum that we are going to get from Android that Nav Vijay should rather die in the 8th Jai Hind, the vacancy date of Veer Vidya is not valid till she will return on the day, so it is true that Nav Vihag will live a long life. Left and Right Safari Trees Plants Particular Note Loot Nau Have the Maximum and Minimum from Left and Right Se Zulu Padh subscribe Video Ko 2.0 Right 0 From Bolte Minimum Picture They 2.0 Right 0 From Bolte Minimum Picture They 2.0 Right 0 From Bolte Minimum Picture They Value The Ko WhatsApp Laptop Vansh A Right To One Ke Nav Vihag Spelling Soen This Point To find the difference which will be shravan ko maximum of the current value and 9th maths of that apps loot ki main aaj whatsapp chalu difference between minimum and value jhalawar loop me note aap salut between that and not valid a religion which has a different half fuel Again no subscribe with us in these maximum bill maths notes of flash lights off mode of this first a hindu saint vincent plane mode turn on that ramesh neema hai ko whatsapp aur sunao bhaiya taken care for the condition and will win this code subscribe school main Suresh working find laxmi 10th shergarh submit dance classes thanks for watching see you
Maximum Difference Between Node and Ancestor
string-without-aaa-or-bbb
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\] **Output:** 7 **Explanation:** We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. **Example 2:** **Input:** root = \[1,null,2,null,0,3\] **Output:** 3 **Constraints:** * The number of nodes in the tree is in the range `[2, 5000]`. * `0 <= Node.val <= 105`
null
String,Greedy
Medium
null
48
Ae House Today Will Really Good Problem remove those voltage delhi-110002 matrix juice. voltage delhi-110002 matrix juice. voltage delhi-110002 matrix juice. Match Inkrice the Givar 12345 600 Subscribe button Click 052 Ashes Subscribe Electronic 12345 600 Tips 8085 600 Tips23 Solve Thinks 12345 60 First River System 0460 Friday Health 100 Per Cent Or Arranged Tractor Hai Loot Yesterday Morning Reverse Twitter After The Goddess Can Do I'm Just Milk Transformer Tricks Latest Tips Oak Versus Culprits To Tomato Size In Available On Okay What Happened That A That 24 waterloo scientific fennel let's prohibit the mother of j&amp;k what typing district two aaj tak remove this conic program start kar do joint committee code hey man first very doing this letter left this record warning rule please that first sex a stagnant 19 OK Software Reversing Number Six Digit 789 The Four Five Six And Chronic Tuition OK Applet Initially 5050 Friends Above Inch Sewing Distance Me So This Time So Initially Vishnu Old Will Put This Lineage Children From 0 To All Dual Apps That I OK Shot This Is One 90000 depend on the decision that 108 steamers 401 to 600 800 oil uses for this point injustice will welcome a the fact that reduce luto min pimple 182 miles 389 to after the run from whose pay i english dip nothing ji tomorrow 2nd shubhra tips of 210 That much interest is 10000 to 120 nothing but 1031 OLX Swift not welcome clear and one vihar national budget 1212 ride to 16 to reduce fat guy 10896 subscribe The Channel Please subscribe Thanks
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
1,027
Hello friends welcome back to me channel once again so here we are going to talk about today's daily problems question of lead code which is lead code medium level question and its name is Longest Arthritis Progression Men's Right so here you Whatever the name of the question is suggesting to you, the same thing is being told to you by the question statement. The only thing here is that in the question statement, it is telling you in a big way what else is there. If you read by the name of the question, then you will understand the overall thing. If you go to A then what the statement says is that you have a wait called errors and what you have to do is then find the longest automatic six in which now if you do not know in your big then in the big of automatic sequence tell you. Such a sequence, such an arrangement of numbers where the difference between the previous number and the current number is the constant relief. As if we talk, okay, here we have written a support first example, so you will see here like this. Actually, we calculate the difference here, it turns out that if we talk about let, then 6 - 3, we take this difference is then 6 - 3, we take this difference is then 6 - 3, we take this difference is difference minus next number, you are the previous number, current number, you are the previous number, actually, three's, now three's. The difference which is there is a constant. Look between any two numbers. 9-63 12 - 9 3 So this difference 9-63 12 - 9 3 So this difference 9-63 12 - 9 3 So this difference is a constant. If you add a different number then it is no longer there. If I remove 17 then it is P. Okay. So the arrangement of numbers in this manner is called an arithmetic sequence. You have to find an arithmetic sequence in this manner. When we are talking about the longest, there is more than one in it, you have to find the longest. Simple, you have to print its length. You have to find the length. Retirement is here, sequence is not being asked, right, so this is the basic and definition for you, mathematics in the larger part of the sequence, what is the sequence, in the larger part of it, we have seen that its question is basically that of only one line and if we go into short If you say that this is not a line, the name of the question is the same question actually. Even if we had not given the last statement, if we had directly looked at the sample, we would have understood that yes, it is ok, we have to extract the longest arithmetic sequence and length from NMPS and return it to you. Right, no one, so now let us first understand this thing, here are one or two points which I will say that you must understand. Okay, first of all, from what we saw about the difference, you have to understand one point, if I tell any two numbers. Write it down, write it down any two numbers, it's okay, it will always be one because if you build it on us with two numbers, then through continuous development, it will build on one and whatever difference may come, because there is no comparison with it can be compared with anyone else. If you don't want to be equal, then these two numbers will always form. Do you understand? Now when we write down two numbers, we have assumed that it is okay, let's go, what do we do, how to do it, let's take this example. 947 ok remove it like this 9472 and 0 I think this is ok now what we did is we know that it will be of number two so now we are in a way this is the logic we are discussing we can call Brit force kid off because we Here we will check each leg, okay, understand, 94 if we look here, this is one leg, this one is you, and its length is here, you are okay, we talked about the third number, asked the lay in mines, which is the third here. The number is required to be yours for the sequence. Okay, so this is your third number - 1. Okay, so this is your third number - 1. Okay, so this is your third number - 1. Okay, none here. We are fine here. Either I remove this example, otherwise you will get confused with the negative. Let's leave it. We talk about this, let's take an example of our own, no one 97 Now this example is in you with difference, you are right, possible seven, six are present, so 761, you are right, there is difference, now here is the point of understanding which you You have to pay attention, look at this, if we are writing together like this, then now you must be seeing this difference is actually -2. Note, this is this difference is actually -2. Note, this is this difference is actually -2. Note, this is -2. If you look here, then nine seven -2. If you look here, then nine seven -2. If you look here, then nine seven is a part of you, the second difference is one but this seven is five. What we were seeing here is like this difference is made on this, if you are somewhere, then actually this is not 75 alone, it is not only 975 you will become the whole of the whole, what have you done, 97 made a separate part, 75 a separate part has been cut, when you By combining both of them, dog will become like this 975 one you will be formed with the difference of minus tu. Sorry then this will become you and here what will be the difference -2. You have to here what will be the difference -2. You have to here what will be the difference -2. You have to understand this thing. First of all understand that with two you will always become one. Whatever be the difference, but when we are adding the third element, it will come from the difference of the third element with the second element, only then it is your thing that the difference we are giving is the constant of the consecutive element. So the third element is if we want to add five then if we add it then we will see whether the difference with seven is of five and from the same whether the difference of nine is with seven or not then if it is then it will be your part and what will be this element in it. It will be added in the ISP and what will be its length Increase / 2 Okay now see when we are Increase / 2 Okay now see when we are Increase / 2 Okay now see when we are adding the five then we do not need the nine is done earlier, okay it has nothing to do with the nine before this. If there was any element before, then it has nothing to do with it. When five to five comes, it will only check its previous element, why because it only wants to take the difference, it has nothing to do with who its previous element is, it is obvious to it. If this previous element is this is our previous element, then this is this previous element, this is its previous element or its prevention is all set to automatic, it is defined, according to the formula, it is okay, this element has to be a part of you, for this you will get it checked from the person next to you. Okay, the one next door is his doctor, mother, take it okay, what is the conclusion from here, okay, so now what is necessary to understand here, look, now here we are seeing nine with four, we saw that two is automatic, two are the length only. It will always happen if their value is two or more than two, then now we will see nine with seven, then this will also give two, of nine, we are seeing with you, only two will give, of nine, we will see with 10, two will give the difference of this. Story or story will have to be stored for each one, what is the difference for this eye, we have kept it now since we are on four seven, how much is the difference on four seven, we will see from three, already till four. Is there anyone whose difference is with three? If not then it will be only two. Okay, let's change its color and it will be better than the previous one. So what do we do here? If it has a difference, then I will update it. I will quickly this will be your -5 this will be -2 this will be -7 quickly this will be your -5 this will be -2 this will be -7 quickly this will be your -5 this will be -2 this will be -7 this will be your plus one right now we go to the next when we will check with seven okay we checked with nine checked everything after that Now if we want to check from seven then we will see that if 72 is five then sorry minus five is fine and 72's -5 is fine but till seven the 72's -5 is fine but till seven the 72's -5 is fine but till seven the element seven is last, there is no -5 here element seven is last, there is no -5 here element seven is last, there is no -5 here so we have left it. Now we are looking at seven with 10, so this is three is not there, it is not left, I think, I made some mistake I think, the difference between 4710 and 47 is your way, I get it, and I saw that there is a first one of three together, whatever it is, I am present of three, so we will basically catch its length from here and here at this position, we will make its length plus one, okay. So till here the length was two, here the length will become three and what will we do at every time, if we go on maximizing then our maximum will also keep coming along, so now understand this carefully, what we have done, what have we done from I. Started checking, it is going to your full size and when the second loop is going on, it is checking with Eye Plus One. Okay, it is checking with Eye Plus One. If you look at it in this way or you can also in the other way. You can do this, you run it behind, it will come from both sides, it is running and we are calculating the difference here, now when we are calculating here at each point, then the difference at this point is each number. For each index, basically I need a difference of one, so here you can also create one, by the way, here I have basically done the map of Okay, one thing you need to keep in mind, then Dil Dun, here the constant is thousand, so your maximum. Eric will be formed or the difference that will be formed can go up to 1000. If your minimum difference is zero then most max you will be max one thousand one element. So even if you are taking it then it will not become any big. It is not your right nor complexity in memory. I will not even understand this, it is okay, I will show you the code so that you can understand it a little better, so first we calculated its size and we checked the size if it is ≤ 2 then it is further checked the size if it is ≤ 2 then it is further checked the size if it is ≤ 2 then it is further because like two or two. If there is more work then till then it is just there, whatever is there will remain with you. Now what are we doing, we have placed the map in the vector. Okay, I will basically keep the difference on this particular index. The particular index is telling that there is a map there. How much length do I have till now on this particular difference? If there is no length, a new difference has been created, then it is obvious that you will always write it in, so we are initially going with the max length here, it is not right. If there is more than one, then something or the other has to happen, so we have kept the max lens, now we are checking, this is the outer loop, basically this is being checked inside it, okay, here we have found the difference. Main current element of I - K we have found the difference. Main current element of I - K we have found the difference. Main current element of I - K - - - Take out the previous one and come to the diet point difference. I am checking in the map whether this difference has already come with some length or not. If not then here we will put it on the index with this difference. Will send two. Come on, this is the first time you have met this difference. If you have met me for the first time, then you have to give it to me, then the length has become you. If you have met before, as it was, it is okay. If it is 17, then look at this. What is current, your eye is basically here, this is your basically behind, this is on your seven, these are three eyes, right eye is the difference of 10-73, but we saw 3 right eye is the difference of 10-73, but we saw 3 right eye is the difference of 10-73, but we saw 3 or not, then when it becomes 47, what did he do? If you look carefully at 7, we have updated it in the last index, then it is okay on the latter, we have updated it on the 7, so here on the 7, for the first time, it has been updated on the 7, it is okay, why did we hit it like this, yes? Basically this three would have been added on 7 and when we came to ten, we checked in K. If the mains is fine in the back, then we checked in K. If we have got three, then from here we will update the difference which is the difference on this rectangle. Picked up from win, picked up from seven, we did two and plus one and sent it here otherwise we are signing there, do you understand if I write fresh one done here this example is okay here But let me write down, see what happened to you in the first team, when you got 47 yesterday, it was seen here that your difference is three and if you did not get it, then since this was the time when it came and it was K, then the difference here is sorry length which is 2s. Okay, when you checked your 70th second then it came and it came to the right and here also we found the difference day, so we checked in the second whether the difference here is with three or not and we found out that it is two lengths. Now I have made 4710 one, so here I will make 2+1 length of you into three lengths here I will make 2+1 length of you into three lengths here I will make 2+1 length of you into three lengths and think of these three as mixed, we have made 4710 one, now this is the right thing and in this way, what is yours, then here we We will also update the max length. Okay, so we will update the max length. Our maximum length will be determined and the same question was being asked to you, I too am confused in the beginning, there was a little dot in it, but after sleeping a lot. Ok, this is the question finally which I got to discuss with a good serve to tell you to understand then I discussed it ok your dot there must be nothing in it but steel if any dog has to be played then you can comment in the below box. Or clear the disco and if you have any other question which you feel you have doubt in or anything else, then you can always share the link of the question on the discount server. If there is a code then share it there. Maybe we will discuss there, okay, rest of this is all we keep in this video and I hope you have seen my blog page which is bandimagic.in. you have seen my blog page which is bandimagic.in. you have seen my blog page which is bandimagic.in. If you have not seen then definitely visit it, here we have given some good- Good things have been added and now good- Good things have been added and now good- Good things have been added and now good things are being added. Okay, I think every week I am adding something on this, so stay tuned, you can also subscribe to it. If you have a subscription newsletter, then when There will also be a new blog, it will be basically published there and you will know immediately.
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
849
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you've not liked the video please like it subscribe to my channel so that you get notified whenever post a new video without any further due let's get started so the problem is maximize distance to closest person a very interesting problem you are given an array representing a row of seats where seats i is equal to 1 representing a person sitting in the ith seat means if the value is one means there is a person sitting on that particular seat it's seat and if the value is zero means that seat is empty so there is at least one empty seat and at least one person sitting so there will be an empty seat and there will be a person sitting in that row and alex wants to sit in the seat such that the distance between him and the closest person to him is maximized right means the distance between alex and the person which is next to alex that distance should be maximum means alex wants to sit as far as possible right so we need to return the maximum distance to the closest person so if we see this test case this is the test case given means over here one means that here a person is sitting and one means like wherever one is that means a person is sitting right and whenever zero is there it means that seat is empty this seat is empty the seat is empty so we have to sit uh alex have like has to sit at a seat such that distance between alex and the person should be maximum so see if alex sits here alex it's here then the distance between alex and this person is like one only like they are at the same uh they are sitting together so this is not the maximum distance if suppose alex is sitting here then also the distance between alex and the person is one right if alex sits here then also the distance between person and the alex is one but see if alex is sitting here if alex sits here this is also an empty seat then the distance between the closest persons this is one closest person so distance between alex and the closest person will be two so in both sides from both sides so the distance maximum distance will be two alex can sit here because this seat will if alex sits here then the distance between alex and the closest person will be maxim if c if alex sits here let's say we take alex is sitting here then you will say that okay this distance is one but this distance from alex to this person this is three then obviously so we will not consider like this because see we have to find the closest distance between the pers with the person and the alex so over here it's one even though this is three but since that this is uh less uh this is uh minimum this is less distance now one so we have to like consider both the sides from left also and from right also and then from that we have to take the minimum because these are more closer so this seat does not give us the maximum distance right so we if you understood the problem uh you this might come into your mind that okay so we have to take we have to consider distances from both left and right so this is one observation which we can make from this test case so i hope you understood the problem so the output for this will be 2 y 2 because we need to return the maximum distance we have to return the maximum distance and the maximum distance will be when alex will sit here if alex hits at this position at this seat then in both the directions the closest person to alex i will have distance two right one two so i hope you understood what the problem is let's see how we can approach so see just pause the video and think that if you have to find out like for each over here for each position we have to find that what could be the minimum distance from both left and right like for example if alex is sitting here what will be the distance of alex from this left person and for what will be the distance of alex from this right person if we have both these values then we can obviously simply find out what is the like minimum what is the closest distance right so just pause the video and try to think how you can do it so i hope you have got some approach and if not don't worry let's see so see what we will first discuss brute force approach and then we will go to the optimized approach so we have one and zero this is the test case see what we incurred from the approach like what we incurred from the discussion that we have to find out like suppose one is here means he at this seat a person is sitting these are the empty seats in between right so for each of this empty seat we need to know if alex sits here then what will be the distance of alex from this one this person and what will be the distance of alex from this person let's say this is one and this distance is four so the distance between alex and the closest person will be one why 1 because we will take minimum of this left distance and write a distance why we are taking minimum because see even though this is this person is far away from alex but this person is closest to alex so we have to take the closest one because we have in the c in the answer we need to return the maximum distance from the closest person this could not be an answer 4 will not be because if alex will sit here then this is also a person sitting next to alex now so that will also consider so minimum of left distance and minimum of right distance we have to take right so here it will be one minimum will come out to be one so alex will not sit here let's say alex sits here then the left distance will be two and the right distance will be three then your minimum will be two and if alex sits here let's say alex sits here then again distance will be three here and it will be two so maximum distance between alex and the person could be two right so now let's see how we will uh do this so we need to find out left distance and right distance every time so what we will do is we will have two arrays left distance array and right distance area so see for each of this empty seat like for this empty seat we need to find out what is this distance between this empty seat and the closest person and what is the distance between this empty seat and the person which is here like the person which is closest so what we will do is we will make an array we will have a area of same size so let's have a area it will be size same size of this area 4 5 and 6. right and this will be right array 0 1 2 3 4 5 and 6 right so initially let's give a maximum value seven size this is n is equal to seven the seven elements just give any maximum value let's say we are giving seven initially right now see we have to find for this position like when we are here we need to find out what is the distance between this seat and the closest one to the left closest one so over here we already have one so the distance will be zero only between this sheet and the one is zero right so means if over here arr of i is already one a r of i is already one so over here the left distance array will have value zero then over here this at this position this is zero so we need to find out what is the distance between this seat and the closest one so it will be the previous distance of this seat plus one that is if it's not there if it is sorry if it is one over here one will come else what we need to do is the distance will be left distance i minus 1 plus 1 y plus 1 because we are this like this is one distance we are taking the previous value and we are adding 1 in it so what is the distance till the previous value plus 1 so here it is 0 so here it will come one so see distance between this 0 and the closest one is 1 then similarly for this 0 we will take the previous value and we will add one so this will become 2 for this 0 it will become 3 then again 1 we got so distance between this seed and the closest one is 0 when one will come will write 0 for this 0 it will be 1 and for this one again we'll have 0 for this one y 1 because 0 plus 1 so this is the left distances for each of these seeds right like for example for this zero the closest one to the left is at distance three right similarly what we will do is we will find for the right so for the right we will start reversing from the end of the array because we need to find the right distance so for this uh same logic right here it is one so the distance will be zero distance between this seat and the closest one so they are here one is only there so it will be zero only then for this zero it will be right distance of i is equal to right distance of i plus 1 here plus 1 will be there plus 1 so index will be i plus 1 because this index will take no right so this will become 1 so you see distance between this and this is 1 then 1 x again there so we will write 0 then 0 is there so that will become 0 distance between this 0 and the closest one to the right so this is 1 so 0 plus 1 then for this 0 it will be 2 1 plus 1 then for this 0 it will be 2 plus 1 3 and for this one it will be 0 see so we have found out for each of these seeds so for example if you see this seed for this the distance of the closest one to the right is one and the distance between this seat and the closest one to the left is three 3 right so i hope you understood what we have done now simply we need to consider which is the maximum we have to find the maximum closes this is now so maximum closes distance we have to maximum distance to the closest person we need to return which will be minimum of left distance comma right distance so there might be a confusion that why we are taking minimum see minimum why we are taking is we need to consider all the cases now see when we are over here three when we are at the seat although the distance between this is here it's one and here it's three we will not be taking maximum of left distance and right why we are not taking maximum because then the answer will become three but three is not ideal answer because although the distance between these two are three but the distance between this and this is one so closest is this distance we have to give the maximum so maximum will be minimum we will be taking minimum so if you see all these so the minimum will come out to be two like zero minimum of one comma three is one uh and then we have to basically take maximum of all the minimums now so we over here 2 we will come we will take 2 so 2 will be our output so maximum of minimum of left comma distance and right distance so this 2 if the alex will sit here then the maximum distance will be two in both sides so this was an approach if you are not able to get it don't worry this is not an optimal approach it was a brute force approach generally when we think uh see this problem this approach comes into our mind so time complexity for this is often and space is also often because we are taking errors now let's see one more approach which is the optimal approach and if you are having trouble understanding the previous approach don't worry this approach you will completely understand so let's take this test case again 1 0 and then we have 1 0 1 see over here we need to find out the like where should alex sit so as to get the maximum distance from the persons right if alex will sit here then alex will get maximum distance from this one also and maximum distance from this one also alex if alex sits here then alex will not get maximum distance from this one will be closer to alex so this is not correct seat for alex right so see when you are checking this out you when you are checking this what you see we you will see that we are checking for the consecutive zeros if there are like see if there are is one is here and there are many zeros in between these are many zeros in between and then one is here then what you will see is if alex will sit in the middle of these all zeros in the middle of all these zeros then obviously the maximum distance will be there between alex and the ones right so just pause the video and think how you can use this point to think of the approach so see what we are doing is we are checking the consecutive zeros between ones between these two ones if we know the consecutive zeros how many are there one two three four five six seven and eight we if we know that there are eight zeros between two consecutive ones then we can divide this eight by two four so we will now we will know that okay there will be maximum distance of four alex and the ones in both sides 4. so this is one approach you can use similarly in this case also in this test case which we were seeing over here if we see the consecutive zeros how many maximum consecutive max consecutive zeros are there zeros so over here there are three consecutive zeros so three divided by two 1.5 just take the ceiling c value so 1.5 just take the ceiling c value so 1.5 just take the ceiling c value so this will be two so there will be maximum distance of two of alex and between the ones right so this is one way of approaching this problem very easy right we just need to check out the maximum consecutive zeros and we'll divide them by two so maximum consecutive zeros divide by two there is one problem in this approach right one problem see if we take this test case 0 and 1 take this test case so in this test case what will happen is uh over here if you see you will find the consecutive zeros those will come out before and you will divide it by two so the maximum distance will be two so but this is not a correct answer why is not correct answer because alex will sit here because there is only one so alex will obviously sit as far away possible from that one because we have to find the maximum distance so in that case 1 2 3 and 4 so answer should come out to be 4 but we are giving our answer as 2 according to our this algorithm according to our this approach which we were thinking when there were con zeros between two ones so this is an exception so in order to avoid this could be in this case also like if one is on this side if this is the case then alex will obviously sit here now as a far away possible from this person but according to our approach the answer will come out to 5 divided by 2 it will be 5 other consecutive ones so it will be 2.5 and it will be 3 it will be 2.5 and it will be 3 it will be 2.5 and it will be 3 so according to our assumption alex should sit one two three alex should sit here but alex is sitting here right so i hope you're getting what we are missing over here so in order to avoid this there is one way we can avoid this c let's take this test case we have zero over here and then we have one and then we have zero um take one here and this is the test case which is given so just do one thing pause the video and think that what we how we can avoid the earlier problem we were getting so earlier problem was that sometimes there were prefix zeroes these are prefix zeros like before this one sometimes there were suffix zeros that is after this one suffix and sometimes there were middle zeros which were between two ones so how you can avoid this so just pause the video and think see over here if you see these are the prefix zeros these are the middle zeros and these are the suffix zeros right so let's take one more zero here now if you see how we can get to the answer so answer for this will be here obviously i alex will sit here because i'll if this is the maximum distance between from the closest person right so what we will do is we will have three variables prefix which will give us the prefix zeros over here prefix zeros are one two three four five then we will have a variable which will give us the middle zeros let's say it is a max zeros which is in between so it is one two three four and one variable we will have which will give us the suffix zeros so fix zeros which is three and then after that what we will do in order to find out the maximum distance five will be as it is we will take five as it is four will take as it is do we do you think four we have to take as it is no we will not take four as it is because these we have we saw earlier that when we have middle zeros in the between we divide the consecutive zero count by two because that will be the distance between alex and the zeros so for this we will divide max zeros by two that will be our distance max zeros by two and suffix we will take as it is because alex can sit here so this is the distance between that so what we have to take at last is we have to take maximum of whatever the prefix zeros we have whatever the max zeros divide by 2 we have and whatever the suffix 0's we have so this will give us our answer so here maximum of 5 4 divided by 2 will be 2 and 3 so the maximum distance will come out to be five so alex will sit here one two three four and five so this is the max distance between alex and the closest person so i hope you understood this approach is very simple just we need to take care of the prefix zeros and the suffix series so let's quickly try iron let's quickly uh dry iron on this test case which was given in the question one zero one so one zero here it was one right let me do the indexing so zero one two three four five six okay so now see what we'll do we'll have three variables prefix zeros initially take it one minus one so fix zeros take it minus one and max zeros which will be the middle zeros minus one and one zeros variable which will tell us the count current count of zeros initialize it with zero so see we will start the traversal one come so here see if you see before what were prefix zeros whatever prefix zeros prefix zeroes were the zeros which were before the first one this was the first one and before this one all the zeros were the prefix zeros but over here this is the first one but there was nothing after before this now so there will be no prefix zeros so what could be one case that if one we get one so see this is the sudo code which i am writing if we will get array is 1 either we will get 1 or we will get 0 else we get 0 right when we get 0 we will do one thing we will just increment 0s variable zeros plus but when we get one means we need to check whether we need to check that if the previous sorry prefix zeros prefix 0's variable is equal to minus 1 means here like we got our 1 but the prefix variable was minus 1 means there were there are no prefix 0s so just do one thing prefix zeros make it zero there are no prefix zeros right then there will be else which we'll see afterwards so then just move i this zero we have zero so we'll increment zero's variable it will become one then again we get zero increment this becomes two again we get i zero make it three then we get one right we get 1 again so we will go in this if now the prefix 0s are not minus 1 so we will not go in this if we will go in else now what we need to do we need to update our max zeros these are the max zeros so max zeros will be maximum of whatever the current value of max zeros and the zeros variable these zeros so this will max zeros will become three and see we got these consecutive zeros now after this one we will get again consecutive zeros so for that we again have to make this variable zero so that we can get the consecutive zeros after that so this over here we will do zeros is equal to zero again initialize this variable to zero again we will traverse so we will get again zero this will increment and again we get one so again we get one and prefix value is not minus one so we will not go in this if we'll go in else max zeros will update with the zeros value if it is greater but it here we have three and this is one so we will not update it and zeros we will again make it zero so we have to reverse this c we have to reverse this and after traversal we have to update our suffix zeros to be zeros variable why because it may happen that after this one there will be zeros so for that our zeros variable will have the zeros which are after this one but over here it there were not right there were not so after that so fixed zeros will be zeros uh whatever there are uh count in the zeros variable so this was our approach and after that what you just need to do is you have to return the maximum of prefix zeros suffix zeros and the max zeros divide by 2 divided by 2 so this will be the closest distance maximum closes distance all right so i hope you understood this approach and the try run so let's see the code quickly java code will be in the description so you can check that also and just quickly see the code we are taking three variables prefix suffix and the max and this is the zeros variable initialize to zero and the rest are initialized to minus 1 then we are taking this for loop we are traversing if the seat is 0 just increment 0's variable else what we were doing see in the else we were checking if the prefix 0 is minus 1. if prefix 0 is minus 1 update prefix zeros to be zeros so yes over here you need to make it zeros right because whatever the current zeros we have to update that in this else what you need to do update max zeros with zeros and again after this just update your zeros to become zeros again and at last after this for loop so fixed zeros will become whatever goes are there at the end and we will return maximum of these two and this so i hope you understood the approach the time complexity for this is o of n single traversal and o of one we are not taking any extra space right so this is the optimized approach other approach was also will also get accepted but that was not an optimized approach if we take the space complexity i hope you understood the all uh like both approaches and the video was quite lengthy but if this video was helpful please like it subscribe to my channel and i'll see in the next video
Maximize Distance to Closest Person
maximize-distance-to-closest-person
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
null
Medium
null
746
hey everybody this is larry this is day seven of the june eco daily challenge hit the like button to subscribe and join me on discord that means that we're coming up on one week congratulate yourselves a little bit uh one fourth and a little bit less of the way there uh anyway today's problem is min cars climbing stairs so you're given an away cost for cost survivors the cost of the i've step you once you pay the cost you climb one or two steps okay so you start you either start this index with the next zero or index or step of index once or you start on a 10 or 15 and then you go one or two uh steps up or just up i guess but uh okay start at zero stepping only once and skipping okay i mean this is pretty straightforward um as far as um dynamic programming problem goes um you can do it forward you can do it backwards um however you like really um it's just about defining this recursively or you know if you want to observe yourself with bottoms up or whatever um this is probably a good time to practice it um yeah i mean i think this is it's just phrasing itself in terms of everything and now that i have all the information we can just go okay you know let's define the min cost of instead of my keyboard of current step and if step is equal to what uh the top four okay do we don't have to pay on the top pay that cost and go to the top okay so we don't um so okay so let's set up n is equal to the length of cost so if this is on the top four we're done right it does return zero um otherwise you know we just have to re we literally just transcribe the problem because we're doing it um in a brute force kind of way really except for that we memorize that's how we i always try to teach it is that trying to figure out a way that you're doing brute force in a way that you're reusing results so that you're able to just memorize it and that's basically what i'm doing here is that okay once you're on the i've step you can either climb one or two steps right so the cost is equal to oh whoops i guess this is the name of the thing so okay c is equal to uh cost of the step otherwise and then here you can climb one or two steps after you pay that cost right so yeah so because this part isn't going to be different we just want the minimum of uh going one step or two step and then we just return to see that's pretty much it i guess you can you don't can actually go directly but yeah and then at the very end it's returned from either you know the problem tells you right you either could start at step zero or step one and that's pretty much it and of course this isn't going to run fast enough because i mean i kind of gave it away which is that you need to memorize um and also of course make sure that um this is our bounce i mean there's a couple ways to do this but um it's fine either way which is that if step is great then you go and damage that is outbound so you return uh maybe just like infinity and i always write this because i like i don't know i'm weird i like to keep having an int because the full version of infinity is as you might know um did i miss read this one maybe i misunderstood this one hang on okay there's regards of i've stepped honestly once you pay the cost you gotta climb one two so why can't you climb this is zero and then take two steps do i misunderstand this huh this is very confusing actually maybe i misunderstood this i mean clearly i misunderstood this a little bit because i also got it wrong here okay maybe i just really misunderstood this form so you have one you have you pay the cost so one two three four five six that seems right i have five here that's a little bit awkward huh did i think i'm misunderstanding this farm a little bit okay so you why can't you start at zero index zero you paid the cost 10 and then you go two steps and now you're in the top and this explanation is garbage so i mean i'm still wrong here i don't know why i'm getting five instead of six am i misunderstanding something really weird maybe i am so we skip costs of three so we go one two three four five yeah five is right what right where do we get six from am i really misunderstanding this because of the i've stepped on a still because five should be right but i'm wow maybe i'm just really like maybe my english is really bad today am i misunderstanding this one so i think i'm right for some problem but maybe it's not this problem of course with course of i is the i've caused with course of i is to so again you know this is a good reminder that i am solving these live clearly so if it's a little bit slow just fast forward and i don't know i mean you know the drill so i still get comments about uh i should explain the problem earlier but i'm like i am having this live i'm sorry but anyway so okay cost of i is the cost i said once you pay the cost you can climb one or two steps the top of the four i see i think i might get it now i think it's just at the top of the four is to think that is higher than this step right so i think i get it um so if so instead of this it should be this okay um and i guess this is a one i guess but i think yeah i think this is fine uh it really disrupts my fault but i think it's just um they could have used one line to would explain it i was just really confused by the english uh maybe you know maybe well i mean you know i have days where i don't anguish very well so i guess it is what it is but okay um i mean sounds good anyway so moving right along to what we were going to say which is that of course um this branches out twice um without memorization this is going to give you an exponential thing right so given that n is at almost a thousand we don't even have to go that far we just go you know maybe big enough maybe this should be big enough and it would already give you a time limit exceeded as you can imagine um so then the next step no pun intended i'm a little phased now because of this as and as we usually do on this channel as you know um the next step is just you know recognizing that okay well we use the step you know the inputs for this function uh step is going to happen multiple times so let's save it down so we can write is cached as you go to force and we look at the number of possible inputs and this can go up to uh from zero to n so it's going to be n plus one size and cash is equal to doesn't really matter i guess just infinity times n plus one as well and then now you can start caching it um which is that if this is cached of step return cache of step otherwise at the very end we do is cached step is equal to true and cap and then we just cache the step right and that's pretty much it uh yeah time limit exceeded and then now hopefully everything will be right and as i did something silly yeah it looks good so let's give it a submit and looks good yeah so the number of possible inputs to min cost and this is of course um i probably should have mentioned in the beginning because that was the first thing i thought of but i forgot to mention it which is that obviously this is way um the complexity is way much the same as fibonacci right um which is of course technically you know you can say it's two to the end but technically that's not true um it's actually uh you know fee to the end of phi to the end or something like that um but ah that's close enough right whatever but anyway my point is that in here step can go from zero to is that zero no i will oh how are there right there zero to n which is means that there's big o of n uh and each one of them takes over one time so it's going to give us o of n time in total and also all one space each input so it's going to give us o of n space in total so this is pretty straightforward pretty elementary um and you probably need to know it because well look like i said this is at its core really very much related to fibonacci and in a lot of kind of ways and that is really fundamental this is only a slight step up in difficulty so you definitely need to know this for a competitive point of view for impressing your younger sister whatever you need to do um anyway that's all i have for this problem hit the like button hit the subscribe button join me in discord hope you all have a great week and i'll see you tomorrow bye
Min Cost Climbing Stairs
prefix-and-suffix-search
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index `0`, or the step with index `1`. Return _the minimum cost to reach the top of the floor_. **Example 1:** **Input:** cost = \[10,15,20\] **Output:** 15 **Explanation:** You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15. **Example 2:** **Input:** cost = \[1,100,1,1,1,100,1,1,100,1\] **Output:** 6 **Explanation:** You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6. **Constraints:** * `2 <= cost.length <= 1000` * `0 <= cost[i] <= 999`
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
String,Design,Trie
Hard
211
937
this is little to question number 937 the other day tiny log file this is a gesture let's get into it I don't think this is a good eating question I think this is to check syntax ability so I think that is reason why there is a lot of some down anyway let's get it all right you have inaudible logs each log is a space diminutive string of words for each log the first word in each log is on numerical identifiers and either each word after the identifier will consist only of Rocky's Raiders work each world after the identifier will consist only of digit we will call this to bed Peppa riotous of logs letter Rock n digit log letter longest except identifier the consist of later and then teaching nogi is only consists of digit contains did log first is available each guaranteed that each lock has at least one word after his identifier due to the log so that all of the rarer rocks comes before any digit love the radar ops are ordered for next Co graphically a glory identifier with the identifier used in case of types the DT log should be put there or in the order they turn the final order of the logs okay let's check it example one longest this one is a dishonest identifier and then consists of only digit so this one is the digit log and then this one is the except identity fire dishonest character so this is letter law and did you look better or better go so in case of letter look we needed to assorting with their lexicon great khali okay ae and then a and art at the same and the sea jet so dishonest first so let one at camp and then let three zero this one is the does not care because this one is identifier and then next two is we need to put digital order after that and then digital order is needed to order wanna know that body so just located first and then rust okay how we can do it okay I will use socket function and blocks and then I will use our use order function key and helper function and then I will create a new function definition helper and then we say flaw and first I was fit to team male named this one is ID and this one is Theta - Rita why are the Spree because only - Rita why are the Spree because only - Rita why are the Spree because only theta or the odors consistent a post and then haha ID second and that before that we needed to check it is later or digit so our orders cases like this so I was pretty idea is log and spirit week in space and one mean is divided only one so the puppies to so first this is the identifier this is a delimited string yet this is delimited string and then this is first part and that is a second post fattiest Heidi and I got a body's beta and then I will check which one is later better block this if later Cheryl is vigil pair in this case retrologue is I will this is the first and then I will show T beta and ID earth I return next of located next of later log and then leggins I just put okay looks good okay there are only one iteration with no extra data storage ah okay there are one extra taste to it because I split alone so I can say it take a linear time with the linear space thank you
Reorder Data in Log Files
online-stock-span
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits. Reorder these logs so that: 1. The **letter-logs** come before all **digit-logs**. 2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. 3. The **digit-logs** maintain their relative ordering. Return _the final order of the logs_. **Example 1:** **Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\] **Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\] **Explanation:** The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ". The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ". **Example 2:** **Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\] **Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\] **Constraints:** * `1 <= logs.length <= 100` * `3 <= logs[i].length <= 100` * All the tokens of `logs[i]` are separated by a **single** space. * `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
null
Stack,Design,Monotonic Stack,Data Stream
Medium
739
1,687
hi everyone myself Bish and today we will see about the with delivering boxes from stor reports number uh L question and it is comes under the hard category and we'll have to properly understand so the question is arriving like you have the task of delivering some boxes from Storage to the airports and only one ship how the ship has a limit on the number of boxes and the total weight and that it can be carry and you are given array boxes where box of I is equal to Port of it box containing the port and weight number and this three integer like fors count Max boxes max weight and after that we have this three condition which we have to be maintain while writing the while giving the solution over the course the points is you can see force is the port where you need to deliver the first box and B is the weight box of I box then second point we have Force count is the number of force okay third point we have a Max boxes and max weight are the respective boxes and weight limit of the shape okay or each like I can say for each shap this max weight and that port number containing like this is the limitation after that it will be not containing this weight so the boxes need to be delivered in order and they are given so the ship will follow these steps the ship will take some number of boxes from the boxes CU not viting the max boxes and make max weight constraint second we have a for loaded box in order the ship with having a trip to the port of the Box need to be delivered to and deliver it if the ship is already in the correct Port no trip is needed okay and this is very important condition because we have to be the question is asking about the boxing to minimize the count minimize the trip count I can see so this is the very good point which we have to be keep in mind because if we are in the same port and having the multiple boxes not I can say the weight they are containing different the same port like one of this contain in the port one we have one weight two weight three weight and they asking total this weight we have to be need so why we are going to the other port to making that weight we are taking the same port number and taking that weight to optimize and to make the big quality and within the less number of counts in the trip point of view I can see so this is a very good point which we have to be uh validated test in the coding and the third question the third point is like the ship that make a return trip to storage to take more boxes from the queue the ship then take make a return trip to storage to take more boxes from the que it means like we have a requirement six if one four is containing only two weight we have to be maintain the four also so for making that uh value it will be go and come uh to maintain that weight so that's why the this point is giving like the shrip sorry the shrip that make a return trip to storage to be take more boxes from the line by line like if already have a two when we are taking first time then again we are going to other P taking the two value or taking the four value so making the those wees in the que and sumission and delivering the solution over there so coming to the like input wise we can check we have a boxes three boxes 1 comma 1 2 comma 1 and each boxes containing the port number and weight number you can see in the first we have a port number one weight is also one port number uh two weight is one port number three weight is one okay and here giving like force count equal to two and max box is equal to three and max weight equal to three so it will be given like already limit uh we have to only take the both count which is equal to two Max boxes we can use the three because already you can see we have one two three boxes and max weight which we have to be check or which we have to be achiev that is three so this is the condition and have to be validate test each uh each time which is not violating this condition so we are getting the output for as how we can see the ship take all the boxes in the que goes to Port one okay then Port two then Port one again the return to storage four trips so the total number of trip is four okay we can see we have a total weight requirement is three okay when we are going in the first boxes we have a p count one and weight is also one so in this we are getting the one weight only we have requirement the three okay and if we are going in this after that we can see we also have another weight which is again in the same P so we are taking those one also so coming from this to this but we have to be following the line by line order first in first out type okay so if we are taking this one okay we are maintaining the one then coming to the port uh two we have a weight one okay then it will be after taking that weight we are right now having a two weight total and there is remaining max weight we have to be three so we having a two already and for the third one purpose we are going in the port number one in this you can see Port we have one and the weight is also one so 2 + 1 equal to one so 2 + 1 equal to one so 2 + 1 equal to 3 uh it will be easier for I'm using a marker so we have this first box second box thir third box so in this we have a one count of weight we also have a one weight here one 2 three like we have this max weight three so that's why if we have that Advantage we can see if we in the same port and we have a requirement for the more weight so we can take that Advantage we will take this like we have a one here again we have a same vot number and weight count so why we will choose this one we will choose preference wise this one because we don't have to take the more trip because the major concern we have to minimize the trip count so that's why you can see first here one it will be like if we are in the same port we can take this 1 2 3 and for this 2 comma 1 purpose we had to take the one round count one trip count so that's why we can see we have a four trip which will be making our max weight three so you can see already given goes to Port one then Port two then Port one again then return to storage so how many trip will be taking here so the total number of trip is four or this one you can see one then here we also have a two and here again we have a one because one and three we can check uh it is in the same port so we don't have to go again and again so from this one we have a three plus 2 comma 1 purpose one comma so addition so it will be total comes under the four count for next you can see we have again Max boxes three which we can take for count three and max weight we have to maintain the six here also we can carry only three boxes Max to Max and the weight which we have to be maintain that is six and Port counts three total we have a three ports 1 3 2 Port one port three port two so total unit number for the port purpose we have three so how we have to be achieve the max we six so how many trick which we have to be take so first of all we have to be always try to like go those boxes which we can maximize like we don't have to go again and again like if I'm getting the uh in the same port now port number one weight then again two weight then three then four so we will taking those Advantage nothing to go to other platform or other ports count to maximize our weights so the Shri take the first boxes goes to Port one then return to the storage then sh second third and fourth you can see second third and fourth goes to Port three and return to storage because you can see port number three again we have a three bit port number three again we have a one so we will utilize this opportunity we rather than going to the port number two so in the port three you can see we have how much weight 3 + 1 4 + 1 5 so ultimately we weight 3 + 1 4 + 1 5 so ultimately we weight 3 + 1 4 + 1 5 so ultimately we are getting the more weight at the port number this so four I can say uh to 4 1 4 5 6 six value we are getting from sorry 1 2 uh 2 + 3 5 five at which we sorry 1 2 uh 2 + 3 5 five at which we sorry 1 2 uh 2 + 3 5 five at which we are getting from the port number three so if we are in the same port we are not taking the like return trick so all we can consume so it will be taking the two trip and 1 comma 2 also taking the two trip and till now which we have to maintain the max weight six so you can see we have a 3 + 1 4 + 1 5 and can see we have a 3 + 1 4 + 1 5 and can see we have a 3 + 1 4 + 1 5 and again we have to be maintain the six number weight just you can see so the first box goes to Port one return to the storage two trip then ship take the second third and fourth box it goes to 4 three then return to storage road trip because it will be not go again and again from the port number three so that's why it will be taking one because you can see 3 and we are waiting getting the maximum weight from this report number so it will not go again in the storage so it will be going first second to count it will be going first time then it will be choosing all the weight and then it will be written so again 2 plus 2 how much we have a four count then we have to utilize the max three boxes then third we can see we are going at the port number two then return again so again it will be taking the two trip for going and coming 2 + 2 4 + 2 6 so for going and coming 2 + 2 4 + 2 6 so for going and coming 2 + 2 4 + 2 6 so that's why we are getting the yes six output understood I can again maintain what we are trying to say this from this three to this 3 one we are taking the two counts only because it is you can see we have a same platform a same port 3 so from this we are getting the two trip for one is going one is coming similarly for this two put so total we have a six so coming to the coding part which we can uh write first we are taking the length so that is from this boxes length then we are having to uh take the trip count so calculating the trip variable then wait then start okay so we'll start uh applying the loop on that length or max weight which we have to be uh Target or achieve we can say and equal to Z and less than n Plus+ then weight equal to less than n Plus+ then weight equal to less than n Plus+ then weight equal to weight plus boxes of end of I update the weight and Tye count when adding to the box it means like when we have a requirement six when we going in the port one we are taking the weight two we are maintaining in the Q then again we are going in the same port so which we don't have to take the most over there so again we have to what the weight we are consuming from the port two we have to be adding the port one not in that G but our resultant value so that's why we are like updating this box of end of one and the condition which we have to be check like if the current box exceed the weight limit remove boxes from the start of the window otherwise we have to be like lost this type of things then next we can see we have to P the costage of this so from this cost variable we are calculating the cost of delivering boxes within the current window so and minus start plus one then we can say we have to check the previous box as a different destination and one to the cost so that's why we are also maintaining the condition here if our end is greater than zero and boxes of end of zero is not equal to boxes of last from the starting that's why we are maintaining the increment over there cost plus you can see we just we are taking all the condition and our previous box is a different destination so we are maintaining this condition and uh making the trip count over there so just you can see trip Plus cost and ultimately uh how much am we are getting from this operation we have to be return and that will be have to be optimized or minimized I can say so that's why we are returning the trip here in this question so uh I think most of the doubts right now you clear yeah if you think I can make from my side as a delivery over there so I'm happy and I will do and apart from that if you have any question and doubt please comment it down I will be happy to share it thank you
Delivering Boxes from Storage to Ports
the-most-similar-path-in-a-graph
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a **limit** on the **number of boxes** and the **total weight** that it can carry. You are given an array `boxes`, where `boxes[i] = [ports​​i​, weighti]`, and three integers `portsCount`, `maxBoxes`, and `maxWeight`. * `ports​​i` is the port where you need to deliver the `ith` box and `weightsi` is the weight of the `ith` box. * `portsCount` is the number of ports. * `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship. The boxes need to be delivered **in the order they are given**. The ship will follow these steps: * The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints. * For each loaded box **in order**, the ship will make a **trip** to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no **trip** is needed, and the box can immediately be delivered. * The ship then makes a return **trip** to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return _the **minimum** number of **trips** the ship needs to make to deliver all boxes to their respective ports._ **Example 1:** **Input:** boxes = \[\[1,1\],\[2,1\],\[1,1\]\], portsCount = 2, maxBoxes = 3, maxWeight = 3 **Output:** 4 **Explanation:** The optimal strategy is as follows: - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. So the total number of trips is 4. Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). **Example 2:** **Input:** boxes = \[\[1,2\],\[3,3\],\[3,1\],\[3,1\],\[2,4\]\], portsCount = 3, maxBoxes = 3, maxWeight = 6 **Output:** 6 **Explanation:** The optimal strategy is as follows: - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. - The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. **Example 3:** **Input:** boxes = \[\[1,4\],\[1,2\],\[2,1\],\[2,1\],\[3,2\],\[3,4\]\], portsCount = 3, maxBoxes = 6, maxWeight = 7 **Output:** 6 **Explanation:** The optimal strategy is as follows: - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. **Constraints:** * `1 <= boxes.length <= 105` * `1 <= portsCount, maxBoxes, maxWeight <= 105` * `1 <= ports​​i <= portsCount` * `1 <= weightsi <= maxWeight`
Create an array dp where dp[i][j] is the min edit distance for the path starting at node i and compared to index j of the targetPath. Traverse the dp array to obtain a valid answer.
Dynamic Programming,Graph
Hard
null
1,903
welcome back guys so today i would be discussing the problems of weekly contest 246 and i would be doing so in english only so yeah do watch it and also those who don't give lead code or don't like lead code so what they can do is they can click on the problem link in the description and they can try to submit few problems and by doing this they will get familiar with the lead code platform so that they would be so that you can you could be able to do better in competitive programming and also for interview purposes and etc so let's begin with the first problem so the problem is that we are given a string and what it is a number so what we have to do is we have to find the largest valued odd interior so how we can do this now let's see the approach like how the number is order even we see by the last digit like it is 52 so how you will check that the number is order even you check last digit only like whether last digit is divisible by 2 or not if it is divisible then the number is even otherwise it's odd so like the all the other digits don't matter only the last digit matter so what we have to find is the longest string which is which will be the or which will be odd so we have to check like which last digit we can take so if we can take this last digit like if it is the last digit is odd then the whole string will be the answer if not then we will check one less than that digit we have to remove that digit because if we don't remove that digit then the number would be even so let's see from the example like the number is 5 2 we have to find the largest and largest string which is odd so what you can do is like or how we check that the number is order even from the last digit makes it order even so it is making the whole number even we should discard it if we would take it then it would if we want to take it then in any substring it would be last and if it would be last the number will be even but we don't want that so we will cancel this so yeah now we will look for the for this string that whether we can take this string or not so what we will do we will check its last digit like whether it's odd or even here it is even so again we will move leftwards because we cannot take this digit also because it is also even so till here the substring we cannot take and we have to take the substring as long as possible so first digit we will always include and then we will check as i told earlier like only the last digit matters in determining whether the number is order even where this is how we will move forward so now let's see the code this is how uh i have written the code uh the things that i told i have written in that we only see like i have started from the reverse because the last digit matters and if the last digit is odd then i would break and that whole substring would be the answer because that would be the longest substring that would be odd because if you move more ahead then the last digit would be even that's why only like we moved till here where the position is odd like here i will break and at which index i will break i will note it down then i will create a string from starting from zero till that index and then i will return that string that's it thank you very much
Largest Odd Number in String
design-most-recently-used-queue
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** num = "52 " **Output:** "5 " **Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number. **Example 2:** **Input:** num = "4206 " **Output:** " " **Explanation:** There are no odd numbers in "4206 ". **Example 3:** **Input:** num = "35427 " **Output:** "35427 " **Explanation:** "35427 " is already an odd number. **Constraints:** * `1 <= num.length <= 105` * `num` only consists of digits and does not contain any leading zeros.
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
Medium
146
328
in this video we're going to look at a legal problem called all even linked lists so we're given the head of linked list uh we want to group all the odd indexes together and then followed by the even indexes notes so in this case the first note is always going to be odd right so the first node and the second node is going to be even node uh even index right and the index number is going to be even number so in this case we're just grouping all the odd nodes with all index number together first then we're going to group all the odd uh even node indexes together right so you can see here we have one three five and then we have two four right so one three five two four then here you can see we have the same thing so we have two point three point six point seven and then it's point and then those seven is pointing to no one pointed no five point no four so it's pretty simple right so in this case we're trying to solve this problem using a constant space complexity and time is the big o of n where n is the number of nodes we have in the link list so how can we solve this problem right so in this case to solve this problem uh is very important to um basically getting the first node right in this case the odd link list as well as the even linked list because we pretty much like the goal to solve this problem is pretty much we're getting this node uh node 2.03 no 3.06 node uh node 2.03 no 3.06 node uh node 2.03 no 3.06 node 6 pointing no 7 and no 7 basically points back to node 1 and no one points back to node five no five points two no four and no four points and all right we're basically going to have a two list one is the odd linked list and we're also going to have a even link list but we're just going to use a pointers to define them and we're just going to change the way how they point into right so basically we're just going to change this note right here instead of pointing the 1 we're going to point to which is node 3. which is node 3. which is node 3. so we're going to delete this connection right here and then node 1 it's going to point to the .net right so in the .net right so in the .net right so in this case it's going to be which is it's going to be which is it's going to be which is node5 so we're deleting this connection right here and no three in this case is going to point to no five dot nets which is no six we're deleting this connection right here no five is pointing to no six dot nets which is this one right here and you get an idea right so no 4 is going to point to which is null to point to which is null to point to which is null and at the end we want to get no 7 point to no 1 right so in this case we keep track of two pretty much two lists right we're pretty much breaking this current list down to a to list so that we have a odd link list right and we also have a even link list at the end then what we're going to do is we're going to get the tail node of the odd link list points to the head of the even linked list in this case we're just getting no 7.01 we're just getting no 7.01 we're just getting no 7.01 which is what we have here no 2.03 no which is what we have here no 2.03 no which is what we have here no 2.03 no 3.06 3.06 3.06 7.1.5 pi 7.1.5 pi 7.1.5 pi 2.24 right so pretty much we're just 2.24 right so pretty much we're just 2.24 right so pretty much we're just going to like get the tail note of the even linked list points to the sorry the tail note of the odd link list point to the head node of the evenlink list and then let's take a look at how we can do this in code it's pretty simple problem so first we're going to do our base case right so in this case let's say if we have a situation where so just you so you know i submit the code is success but basically what happens is we do a base case right in this case if head is equal to null or is equal to all we can just or is equal to all we can just or is equal to all we can just return head right and then we're going to create our uh our list in this case we have our odd list which has is pointed head and the even list is points to head.nest and the even list is points to head.nest and the even list is points to head.nest right so in this case we have a two pointers we have one pointed points here the other pointer points here these are the headnote of our two list right and then we basically again we're basically breaking our current list down to two individual lists but we're not creating any space we're basically just breaking it down so that we have two head headnotes even list headnote and all this headnode then we're just going to have our current pointer current odd which is the current pointer for the odd number right for the odd indexes even pointer is going to point to the even uh indexes for the link list that we have so if they're not equal to null right if both of them are both of that's not equal to both of that's not equal to both of that's not equal to null then we want to make sure that we're getting the right so we're getting the right so we're getting the right so first what we're going to do is we're going to get the so this is going to get the so this is going to get the so this is the current odd pointer points to even on even current even right current even nest so this node.nest so this node.nest so this node.nest and then we're going to get current odd is equal to current autoness which is going to get this node instead of pointing to here we're going to get this point here so this is the current odd and this current even and current is equal to current odd on this is equal to current odd on this is equal to current odd on this which is going to be this node right here so in this case we're getting the odd um or i just say even.nest or current um or i just say even.nest or current um or i just say even.nest or current even.s which is equal to current even.s which is equal to current even.s which is equal to current autonest and the kernel even is equal to current even.nets which is going to be point even.nets which is going to be point even.nets which is going to be point here we're going to continue to do that right for make sure that you know there could be a situation where we have a current node the current odd on this is equal null right so we want to make sure that both dot net does not equal null so that at the end we can have the tail node of the odd list right the odd list so that we can be able to get the tail note of our list point to the head node of the um in this case the evil list so in this case that was what i did here and at the end we want to return the head node of after we reorder the link list so in this case it's going to be the head node of odd list so i hope this code is really simple like document the whole thing and the time complexity in this case is going to be big of n and it's going to be number of those we have in our linked list and the space complexity in this case is going to be constant so there you have it and thank you for watching
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
1,561
hey guys welcome back today we're going to go through legal problem 1561 maximum number of coins you can get let's take a look at the problem first there are three n piles of coins of varying size you and your friends will take piles of coins as follows so in each step you will first choose any three piles of coins not necessarily consecutive so it might get a bit confusing and tricky here so the first step is that mu as a participant to take three coins out of this given coin piles and then of your choice alice will take first so alice will pick the pile with the maximum number of coins and then the second person is your turn so you pick the next pile with the maximum number of coins and bob will be the third person your friend bob will pick that last pile so each time you pick three piles or three coins as takes first one you take the next one and bob take the last one so this is the rule to play this game repeat until there are no more piles of coins so the number of coins is three n so it's divisible by three so it makes sure that everybody gets equal number of coins in the end that is n given a number given an array of integers piles where pi's i is the number of coins in the i ipad in the i've pile it actually what it means is the value of the i've pile that's what it means return the maximum number of coins which you can have so for example given this pile a total of six coins two four one two seven eight the output is two is nine so let's take a look at the explanation how it works first you pick this triplet two seven eight the maximum one is eight so alex picks this one and then you pick seven the last one two is given to bob then the remaining one is one two four and also in this example um i don't know if they intentionally misordered this triplet because 278 is here and then the next one should be two for one but instead they put one two four this is this might create another layer of confusion but it doesn't really matter because all of the three people they are picking by the maximum value so the four is the maximum in this triplet so alice will pick four and then you pick two bob will pick one so in the end you get seven plus two that is nine that is the maximum that you can get take a look at the second example two four five so there's only three coins so alice will pick the first one which has the maximum value which is fine then you pick the next one which has the maximum value which is four so output is full okay now let's take a look at example three for this example what we can do is that if we don't do any pre-processing we can just take a do any pre-processing we can just take a do any pre-processing we can just take a look at this one what it does is eight seven so nine gives to alice we take eight so that is eight plus now six five and one so six is going to give to alice and then we pick five and next two three and four so we have to get three so in this case we're going to get 16 apparently it's not super ideal if we don't do any pre-processing don't do any pre-processing don't do any pre-processing it's going to give us the number that we can get i as a participant of this game is going to get the maximum value is 16 instead of the correct output which is 18. so let's just quickly think about how we can approach this problem should we do apply a sorting to the given input what's going to benefit what's going to bring us if we apply sorting to this given pile first before we do any processing so that's if we solve this given pile it's going to give us the minimum number is going to be coming first and the maximum number is going to be put in the very last towards the end of this array and what i as and participant of this game can take is always the middle one right so the minimum one will be given to bob and the maximum one will be given to alice so whatever is left in the middle i want to take the one as far right as possible because far right that means the better the bigger one the calling with bigger value right that means the biggest one will always be reserved to your artist but then i can take the second biggest one the smallest one will always be given to bob if we can think of that will make things a lot easier so we'll sort it first and then we always pick the second last from the right end and then we can add all of them up that will give us the correct answer i hope that makes sense if that test now let's put it into actual code all right first let's solve this array it's called piles now we'll have two variables one or just coin j which is going to give us a count say because every person there's a total of three n piles and three participants three players are involved in this game so whenever i picked three whenever i picked n coins so at that time i'll just break out so another one is so i is going to start from the second last element right so that's going to be piles let me call it land piles length and then -2 so the last element is going and then -2 so the last element is going and then -2 so the last element is going to be l minus 1 so the second last element is going to be l minus 2. then i must be greater than 0 because we will be like right in the one third point of this entire array because for the very first one third part is going to be reserved for box right so i greater than zero is good enough it's not precise but it will be good and then because we will have a break in the for loop so this um i greater than zero it doesn't really matter we can actually remove that later on and then here i is going to be decremented by two at one time why because the first one the current biggest one will always be reserved to alice all right so that's why we start from the very right end okay now i have another variable called points start from zero now coins will just add up all of the values and then next what we want to do is that we want to make sure that j we will increment j that means i as a participant of the game have collected one more coin so i'm going to increment j if j equals to len divided by three that means so the given piles of coin is three n so that means i got n coins already at that point we can just break out and return otherwise we'll just also return as well this is the entire algorithm so now let's hit run code and see if it's going to work all right let's accept it now let me hit submit should work might not be very ideal all right accept it um it might not be very i know you see it's 25 or 25 um but at least this is one way to get the problems up and i thought it's very straightforward now let me just remove this condition we don't really need it should work as well because we break out here oh unreachable statement i don't really need this because it's going to break out let me just hit submit again all right it's also oh it's actually faster 100 okay let me just hit submit again to see if there's any difference all right now it's it shouldn't make that big of difference because we always break out from this if loop from this if condition it breaks out directly just hit it one more time yeah this sounds about right it shouldn't make any difference all right this is the way that i pre i approach this problem i hope it makes sense uh because there are three participants we always reserve the biggest one the coins with the biggest value maximum value to alice and the smallest one to bob i take the middle one so that's how we can solve this problem i hope it makes sense if it does just do me a favor and hit the like button that's going to help me out tremendously and help with the youtube algorithm as well and don't forget to subscribe to my youtube channel as i have accumulated quite a few little data structure algorithm tutorials on amazon web services certification exam tutorials so hopefully i'll just see you guys in just a few short seconds that's it for this video thank you very much for watching
Maximum Number of Coins You Can Get
rearrange-words-in-a-sentence
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the maximum number of coins. * Your friend Bob will pick the last pile. * Repeat until there are no more piles of coins. Given an array of integers `piles` where `piles[i]` is the number of coins in the `ith` pile. Return the maximum number of coins that you can have. **Example 1:** **Input:** piles = \[2,4,1,2,7,8\] **Output:** 9 **Explanation:** Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with **7** coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with **2** coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On the other hand if we choose this arrangement (1, **2**, 8), (2, **4**, 7) you only get 2 + 4 = 6 coins which is not optimal. **Example 2:** **Input:** piles = \[2,4,5\] **Output:** 4 **Example 3:** **Input:** piles = \[9,8,7,6,5,1,2,3,4\] **Output:** 18 **Constraints:** * `3 <= piles.length <= 105` * `piles.length % 3 == 0` * `1 <= piles[i] <= 104`
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
String,Sorting
Medium
null
1,297
hello everyone so today we are going to see maximum number of occurrences of a substring so we are given an input of a string s and three integer values max letters min size and max size so we have to return the number of substrings we can form from the string yes but the substring can be formed with following rules the rules are the number of unique characters in the substring must be less than or equal to max letters and the substring size must be between min size and max size let's understand the problem statement with an example here is our first example so we have to form substrings that satisfies these conditions so let's consider our string a b and a b c and a b so the minimum size must be three so let's start considering the first three characters a b and the size is three and the maximum letters used here is two so this substring satisfies the condition next start from the second character and the next three will be the minimum size and it does satisfy the condition that is two maximum characters and minimum size of three and maximum size of four so now a b occurs one time and a b a occurs one time and the next substring is bab again this satisfies the conditions so bab also occurs one time so the next thing is abc this is not satisfying the condition since the letters used are three but the maximum letter should be used or two so ignoring that moving on to the next character from b c a again this is not satisfying the condition the next substring is c a so this is satisfying the condition so the next is a b so a b has already been occurred in our set of substrings so we just increment the count to two so now the string ends so if we compare aab occurs twice this is the maximum occurrence out of all substrings we got so our output is 2 so this is a problem statement says so now we are going to approach this problem statement in two ways that is we are going to have two different algorithms explained in this video so let's see our first algorithm is the same method i explained previously that is we're going to consider a substring of min size and check whether it satisfies all the conditions and if it satisfies the conditions we are going to add to a hash map and its occurrence so once we populate all the substrings with its occurrence finally we are going to check which is the maximum and return the value so simply in our algorithm we gonna iterate through the string from 0 to n minus min size why because in the last min size if we consider this substring there is no elements left to add to the substring so we are going to iterate until this only so that we just move the pointer to check all possible substrings of size min size and then check if that substring satisfies all the condition or not if the substring satisfies all the condition then add it to a hash map that is the substring comma its occurrence so when we find the repeated substring we gonna increment its count and also we have gonna have a value result where every time a new substring is added we're gonna compare the result value which is maximum if the result is maximum we leave it otherwise we're gonna update it with a new result so this is how we gonna do our algorithm let's see the code now here is our code for the problem i explained so at the first line we are simply checking the basic conditions whether the length of the string is 0 and max lettuce is 0 then return 0 if not we are declaring a hash map to store the substring and its occurrence and through the loop we just iterate it till length minus min size and take the substring from i comma i plus minus x that is we are going to check the substring of min size and we are having a method is valid which will return a boolean value if it is valid true then put the value to the hashmap and increment its counter if it occurred already and side by side we calculate max value and then we return the max value inside this valid method we have a hash set where we gonna add the characters we convert the string to the substring to the character array and add the characters to the hash map as we already know hash map will save only unique characters no duplicates will be saved so by the end if the size of the hash map is less than or equal to max size then it satisfies the condition one and the length of the substring is less than or equal to max size then this condition as well is satisfied so it returns true or false according to that but there is no need to check max size in this case at all because anyways we are considering the substring of size only of min size so there is no option to for it to go more than the min size in the algorithm we have discussed we just consider the string of size only of men size but there will be no test case fails because for example if you consider the min size is 2 and the string we get will be a and a occurs twice in the string that is again equal to 2 so it is considered it is of size 2 or 3 or 4 the occurrence is gonna be same so instead if we don't want this method to follow we have another method which is a two pointer method or a sliding window method that will consider string substring of each and every length and then find its occurrences let's see that algorithm now so here is our second approach which is a two pointer approach or a sliding window approach in our previous algorithm we considered substrings of only of min size but here we are going to consider substring of size starting from min size ending with max size between any lip so let's have two pointers at our first character that is i'm having my i and j here at a fit at a first character so my eye moves every for every iteration it is a scanning element which moves to check every character in the substring so this j is gonna determine from where to where our sub string resides so simply i'm gonna check whether from first i to j whether it forms the substring that satisfies all three conditions if it satisfies i'm gonna add it to the hash map that is the substring and its occurrence as usual at the end i'm gonna check which is the maximum substring and return the result but the method to check is a bit different here that is once the substring is not formed then move the pointer i to the next character and check whether from i to j it forms a substring again if it is not satisfying move the pointer again if it formed a substring it form a substring then instead of moving i move the pointer j to the next element to check whether any other substrings present in between and we gonna get uh two elements help that is the one is the integer value letters which is gonna count the number of letters in that particular substring to check whether it satisfies the max letters condition or not and to help counting these letters we gonna have an integer array count which helps to count the number of characters in that substring so let us go for a dry run of this algorithm using this example and see how we can code it as i said we're going to keep track of few variables the first one is an integer array ch which is going to have the character count so from we are going to initialize the integer to 26 so that it can hold all alphabets in our example we just have three characters so let us assume we have three characters and the other one is letters so for every substring we find we gonna update this letters variable and we gonna have an hashmap so in our hash map we gonna store the substring and its occurrence so for every substring we check we gonna update all these variables so first let us have our pointer i here at a and j also here at a so we check whether our a satisfies this condition or not a is not satisfying any of this condition so move the pointer to move the i pointer to next alphabet so now our i is at second a it is checking whether a is satisfying any of this condition or not it is not satisfying the condition so move the pointer to the next character so far we have crossed two a's so first while we were at first a we should have updated the a to one and the letters to 1 because the letters will update only if we find a unique character so far we have come across two a so i am updating a to 2 and now our i is at b so we found one b and it is a unique character from the substring so i am updating the letters to 2. so now let's check whether from i to j it forms a substring or not s the i to j it was a b which satisfies all three conditions so now i'm adding a b to my uh hash map and i'm incrementing the counter to occurrence to one let's move the pointer i to the next character now i is at a will update the values here now we have three a's so i'm updating this to three and one b as usual there are no unique characters so letters will be the same let's check whether the substring from i to j satisfies the condition the letters are two maximum letters and the minimum size is three satisfied and the maximum size is four satisfied so we are adding the character a b a and the occurrence is one so next since it is no for four characters there can be a chance that there is a shorter substring between this so i am going to move the j to next character so every time we find a substring we are going to iterate and move our j now our pointer j has moved so every time we move a pointer we have to update these values now if you see there is a one a remote that is the this character is remote so now we are going to decrement the character from the character array so now our a becomes two and the letters become is still two because a did not move to 0 if the a move to 0 then the a is completely removed from the letters then we have to make the letters also decrement in our case we have we still have a in our substring so we are not going to decrement the letters if you see a b is again a valid substring that is going to be added in our hash map so our pointers keep on moving so for every movement we update these array and the letters by incrementing the characters and incrementing the letters if it is unique and decrementing the characters and decrementing the letters if the array becomes completely zero so all the possible substrings will be added and its occurrences will be iterated so at last we will find again a b and a b will be twice here and we will be sending the result as this so now let's directly go to the coding part and see how we gonna code it here is our previous algorithm i have submitted the algorithm and it submitted with 50 millisecond so let's type in the second approach and check how much how long it takes to execute as i said i'm gonna declare an integer array ch of size 26 to make the count of the letters in our substring and the math that is going to store the substrings and its occurrences and integer letters and finally number of occurrences is our result which is what we are going to written let's initialize the values of letters and i'm gonna declare two pointers which are going to iterate through the string that is my pointer i and j which runs through the length of the string and i'm gonna take the character of the string and increment the counter so we're gonna update our characters count in c h and also check if it is a unique character for that i'm incrementing the character array for that particular character and if it is equal to 1 that is it is incrementing for the first time then it is a unique character then i am going to i trade the variable letters to keep count of the unique characters in the substring now i'm going to check whether the substring satisfies the rules that is if the letters in that substring is greater than max letters or the length of the substring is greater than max size if it violates the rules then there can be a chance of a smaller substring within that substring so what i am going to do i am going to iterate the pointer j and move the pointer j and again gonna check if that has a different substring or not for so if i iterate the j i said so if in case a b c if my pointer j is moving from first a to second a then i have to remove the traces of first a right so in that case i am going to remove the traces of previous characters and i am checking whether that character completely removed from the substring that is i'm gonna decrement the character at j and i am going to check whether it is become 0 that is the completely that character removed from the substring if it is completely removed then we have to remove that letter from our substring as well so i'm gonna decrement the letters and i trade the j and move to the next letter so every time we are checking whether the substring is greater than match letters or the size of the substring is greater than max size we just move the pointer to the next character before moving the pointer we are removing the details of that character from our array and letters now if we found our substring that satisfies all the condition and we already checked two conditions if it is not violating these two condition then it is satisfying those two conditions our third condition is it should be of many it should be greater than or equal to mean size if that condition is also satisfied then we're gonna add it to our hashmap we took the substrate and we're gonna add that substring to our hash map and we want to check if that substring is already there or not if it is already there we gonna iterate its occurrence now we are going to update our number of occurrence that is our result here every time we found a new substring so now once we found our substring we are updating the hash map as i said and finally we are going to decrement we are going to move the pointer j so as usual we want to remove the traces of the character where j is pointed and then we are going to move the pointer so now we decremented the occurrence of that particular character in character array and we are checking if that is equal to 0 then we update our letters as well and moving the pointer j so now that's all done we are going to return our result yes now our algorithm is done let's run yes accepted let's submit this algorithm is also taking nearly the same time so thank you
Maximum Number of Occurrences of a Substring
maximum-number-of-balloons
Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules: * The number of unique characters in the substring must be less than or equal to `maxLetters`. * The substring size must be between `minSize` and `maxSize` inclusive. **Example 1:** **Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4 **Output:** 2 **Explanation:** Substring "aab " has 2 ocurrences in the original string. It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize). **Example 2:** **Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3 **Output:** 2 **Explanation:** Substring "aaa " occur 2 times in the string. It can overlap. **Constraints:** * `1 <= s.length <= 105` * `1 <= maxLetters <= 26` * `1 <= minSize <= maxSize <= min(26, s.length)` * `s` consists of only lowercase English letters.
Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon".
Hash Table,String,Counting
Easy
null
149
Good evening friends, today we have brought the next lecture of computer series in which we are going to solve the questions of Max Point Channel Line which is the problem of heart category and today our de tu hai date is this 8th of January 9. Ordinance is given in Let's Start which There will be one point, we will represent it on the open axis plane and if there are points in the se state line, then we know the slope. If all the three points in the se line have equal slopes, then let us see the concept of slope. Not good in this typing so let's do something simple, whatever I have told you, if Okay, this is clear to us, now we move on, we will take the second point, then the third point is the approach which is accepted because our consonants are according to what we speak. Okay, Fardar, we will also bring the optimized version of it, but today its roots. Let's get someone accepted, which will be the number of points We are showing which will be our next step, which is the first point, we are going to travel to it After doing both the points, here we will take the total variable and account variable. From the first two, because we have taken our 2 points, we have taken the points inside the line that we have and we are going to call the stroke between these two, so we are going to skip these two points, so we are going to pass the condition. I = Sorry, all three points have to be done End OK [ End OK [ End OK Points of J and I are too long From there onwards, we are doing X3 - onwards, we are doing X3 - onwards, we are doing X3 - X2 and White is doing 3 - Y2 Now it is and White is doing 3 - Y2 Now it is and White is doing 3 - Y2 Now it is better to equal these two. We have found them in cross multiply. If slow is equal then we have found our third point. Okay so this condition will be satisfied if you will find it. We will try to write it cleanly. We have to do Indonesia. Okay so C. Its in D max function max of maxi and less ok that's all there was no two in this video it was a bit lazy the code for it had to be written it was a bit tricky and you will meet again with the optimus version of it tomorrow ki puri
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
923
hey what's up guys uh this is chung here so let's take a look at today's daily challenge problem uh number 923 threesome is multiplicity right so this is a very interesting like three-sum problem three-sum problem three-sum problem this is like a little bit of variation of that so given like an integer array right and the integer target you we need to return the number of tuples ijk such that i smaller than j smaller than k and the three numbers the three sum is equal to the target and in the end we need to do a modular for this one right so for example right we have this array of this one so the target is eight and the answer is 20. so how do we get 20 right so we have a different of combination so we have one two five one three four two four and two three right so with one two five how many combinations we have how many uh maybe occurrences right we have eight because we have two one right two one and two and then two five so two times two equals eight right so that's why the total uh occurrences right for this one to five is eight right and then similarly for the rights for two one three four is eight and then two to four is two three is two right so that's why in total is twenty cool and uh so the constraints right so the length of the arrays are like three thousand and the number range is it's only uh 100 right cool so i mean for this three sum problem you know we can always try to solve this one with like uh like a two pointer technique right which means that you know we will sort this array first right and then we fix the first number right and then we will try to use a two pointer to find the remaining two numbers right but for this one you know it's a little bit different because you know the um there are few there are like a few uh special cases right you know let's say we have this one and one right let's we are at one here right and then uh just with two pointers so we'll have like the pointer the left pointer pointed at two right so and the right pointer pointing at five right so from here you know we want to know right so we know okay one two five they are they're like a valid uh tuple right but we want to know how many twos and how many five because we don't we want we don't need to worry about ones here because you know once we move to the second one here we'll add like a similar number of two and five again basically since we have two and two five the total combinations for the second and third number is two times two right because equals to four and so for the first one we don't have to do the multiple multi multiply multiplication we can simply move this uh cursor's cursors one by one because the first time we had four and second time we also have four that's why we can also have eight in total and the problem is that you know one every time when we find like a match right for the second and the third numbers we have to somehow move this cursor right because we want to know how many numbers how many uh same numbers for the first number for the second number and is how many numbers for the last number that's why every time we have like a match we'll basically we'll move the uh we'll move the cursor right until uh until the next number is it's different then we can just use this count right this 2 times 2 and find the total combination of the second and third number right but there is like also special case for the second and third number which is this like example two here so in this case the third the second and third number they're the same they're both two so in this case what we have is simply the we have the combinations of the number we have c 4 2 in this case which is the 4 times 3 divided by 2 times 1 right which is 6 in this case yeah so this is the only special case we need to be careful so when the second and third number they're the same we need to use this formula to calculate that right and cool so with that being said you know let's try to implement this the first approach real quick you know to be able to use a two-pointer you know to be able to use a two-pointer you know to be able to use a two-pointer technique uh first we need to sort this array right like how we solve this three-sum problem like how we solve this three-sum problem like how we solve this three-sum problem and then we have the uh number equals to length of array right then we have the answer equal to zero so for i in range of uh n minus 2 because we need at least two numbers for the second and third number right so we have num one equals to array i right and then target so the target is like what is the target uh subtract minus one right and then we have left and right pointer so left equals to i plus one right and the right equals to n minus one that's going to be the two pointer and while left is smaller than r right so we have a few cases so the first ones if the l plus right is greater than the target right and then we simply decrease the right pointer as if the total is smaller and this one we increase the left pointer right and now we have house if here right so now the uh starting from here right uh we find a valid tuple right here we just need to calculate we need to track two scenarios right so the first scenario is like this one if the current l does not equal to this one right that's the uh this two five or three two or three four case right so in this case we need to find we need to move the cursor so that we can find the uh the total number for the current number right so that's why i'm going to have a count one and count two right equals to one so to move the left cursors i do this so if the while left plus one is smaller than r right and the left equals to the left l plus one right and then we increase move the curve first i increase the count by one and also move the left cursor by one right similarly for the right so while uh left is smaller than r minus one right and then the r is equal to the r minus one and this so for this one i increase the column two by one and then i decrease the right pointer by one okay and then in the end i'd simply do a count one plus times count two right and then after this one don't forget to also increase the left pointer and decrease the right pointer right so else is else what means the uh the left the second number and third number that same then we simply need to use the that formula right the total length of this one which is what which is the uh which is r minus l plus one right basically we have a total length here so we have a length equals to l r minus l plus one right that's the total length of the for example this one right we have l pointing to here and r point into here that's why you know we the total length for this one is this and if we use the second formula that's going to be the uh the length times uh length minus 1 right and then divided by what by 2 right actually this is two times one right that's how we do a c and two right cool and yeah and here we simply break actually right because you know since the l and right they are the same right there's no we don't need to move the cursors anymore right we can simply calculate the results okay and then here i just do uh return the answer after doing the modular with this one right plus seven return the answer dot modular than this mod right okay submit cool so it works right i mean so for this as you guys can see so the time complexity for this one obviously it's uh it's of n square right because we have a first for loop for the number one and then for the second third we have a two pointers that's going to be another o of n time complexity that's why the total is o of n square right and so can we improve this right the answer is yes i mean if you look at this the range for the number so the range of the number is only one 100 right so which means that it give us like another basically approach to what we can see we can simply do a count right i mean we can do a count for each of the numbers which means that you know we simply do a count equals to the counter of this array here right and then we simply loop through the uh all the possible combinations for different numbers right and for let's say we uh we try all the possible combinations for the first two numbers right and then we have a few we have three cases so the first one is the num one equals num2 basically n1 equals to n2 equals to n3 so that's the first scenario if we choose like three numbers right and then the second scenario is what second scenario is that you know n1 equals to n2 but does not equal to and three right and then the third one is the n1 that's not equal to n2 and that's not equal to n3 so only we only have these three scenarios when we try to choose three numbers from this count right and we just need to consider the all the three scenarios at once so what i mean by that is no okay so assuming we have a count here right so from this count here you know we have we this discount only stores the count for distinct values right so if we just uh select those first two numbers the answer is starting from zero right so we have four i in count right and then for j in count basically the i and j are the first two numbers they could be the same right so let's say you if all the numbers they are all like two right and then the target equals six right so in this case is we simply just select those two numbers a three twos from this uh array here and so that we can get six right that's why you know i simply select uh i and j basically i try all the possible combinations for the first two numbers and then for the third numbers we have like what target uh right minus k minus i minus j and we have this k here so like i said the first scenario is this one so if the i is equal to j is equal to k it means that you know we have we simply do what c n three right and what's the c and three right that's the uh so we have a count i right and then times count i minus 1 right times count i minus 2 and divided by 3 times 2 right and the second scenario is what it's like this one so there are two numbers are the same but the third one is different right so which means i equals to j so for this one we have what we have this one of this one divided by two and then we times uh k right basically we're selecting the uh do a c we're doing like a c uh see this uh count i right cn2 which is this one cn2 and then we times the third number the count for third number and here i only checked i and j i didn't you know but someone said okay so but the m1 equals to n2 does uh does not equal to n3 what so how about n1 equals to n3 it does not equal to n n2 so how about this one right actually we don't need to worry about this one because as you guys can see we are enumerating all the possible scenarios uh for this uh i and j which means that the i and j could be unto an o there's another case where the uh the inj is on one and n3 right in that case actually we don't want to double count right and yeah that's why you know we only compare the first two numbers right n one and n two so that you know when there's an one and three here you know it's already uh covered because we look through all the possible combinations so similarly for the last scenario which means that you know n1 does not equal to n2 does not equal to n3 and how can we uh handle this scenario right so let's say we cannot use this basically we cannot use this one right you know we cannot do i that's not equal to j that's not equal to k and why is that you know let's say we have 1 2 and three right so let's say there are like this three numbers here you know and if we check if we only use this one right basically you know one two three we'll count it uh count as a valid uh scenario and then two one three will also be counted again right and then three one two right basically all the permutations of the three numbers they'll always be counting here but you know actually there are other we should only consider those three numbers once because you know the other doesn't does not really doesn't really matter all we care is the number itself the value of number itself that's why we have somehow find like to limit that you know one way of doing it we simply can do this we always try to do a decrease right or we do a increase so that we did this one will basically guarantee that as you know for three distinct numbers we only count them once right and so for that we have answers dot uh this one right this one count j and then count k right so similarly i also need to do this one in the end right so run the code accept it and submit yeah so this one this time is much faster and why is that because the value of the number is only a vision 100 so which means that the length of the count is limited to 100 so that's why we have this kind of uh so first we do a count so do a counters we have n here right so that's the end and then we plus what plus the uh this one right a an acid for loop for this uh distinct values which should be a 100 square so that's the time complexity for the second approach which is simply do a count and then we consider all the scenarios and we'll and the only thing we need to be careful for the second approach is that we don't want we do want to double counting double counts the combinations right for both for the seconds and the third scenario cool yeah i think that's pretty much everything i want to talk about for this problem yeah thank you for watching this video guys and stay tuned see you guys soon bye
3Sum With Multiplicity
super-egg-drop
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanation:** Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. **Example 2:** **Input:** arr = \[1,1,2,2,2,2\], target = 5 **Output:** 12 **Explanation:** arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times: We choose one 1 from \[1,1\] in 2 ways, and two 2s from \[2,2,2,2\] in 6 ways. **Example 3:** **Input:** arr = \[2,1,3\], target = 6 **Output:** 1 **Explanation:** (1, 2, 3) occured one time in the array so we return 1. **Constraints:** * `3 <= arr.length <= 3000` * `0 <= arr[i] <= 100` * `0 <= target <= 300`
null
Math,Binary Search,Dynamic Programming
Hard
2031
71
okay question 71 leak code simplifying path so given a string path which is an absolute path starting with a forward slash to a file or directory in a unix style file system convert it to the simplified canonical path a unix style file system period refers to the current directory a double period refers to the directory upper level and any multiple consecutive slashes are treated as a single slash for this problem any other format of periods such as three periods are treated as file directory names so the canonical path should have the following format the path starts with a single slash any two directories are separated by single slash the path does not end with a trailing slash the path only contains the directories on the path from the root directory to the target file or directory no period will double period return the simplified canonical path so it's a pretty tricky question there's a lot to take in from the initial question and i believe facebook has used this question a number of times so the main thing with this question is that there are a number of different edge cases to take into consideration so we have a period which we need to remove we have two periods which signals the directory upper level we have two forward slashes which equates to one forward slash so we need to remove that and three periods equals a file directory name so there is a lot that we need to add into the solution so with example one we have a forward slash home and a training for slash now we need to remove that trailing forward slash and that gives us the output the second example here we have two forward slashes encapsulating two periods and in the question it said two periods equates to the directory up but here this is the route so this is the highest level so we can't go anywhere higher than that so we need to return that in the last example here we have home two for slashes foo and a trailing forward slash so we need to get rid of the training forward slash and we also need to remove one of these forward slashes so let's try and work out the solution to this so we have three examples here and we're going to run through each one so we have a question like this we're going to be using some kind of data structure which manipulates an array's processing order to last in first out and that is the stack data structure which is just an array but we process it as last in first out so what is common amongst all these three examples so within a unix file system each directory is separated by a forward slash so what we could do is we could split this string based on the forward slash so we could split based on the forward slash now in this example here this first example if we split this it's going to give us an empty string which is the forward slash that we split on it's going to give us the string of home and it's also going to give us an empty string if we split with this one we are going to get an empty string going to get home we're going to get two empty strings the two forward slashes gonna have foo and we're going to have a trailing empty string which is the last forward slash in this example okay great so we've managed to split these out now before we start pushing anything into the stack we need to create some kind of if conditional logic what we don't want to be pushing into the stack are empty strings right these empty strings provide us no value so we can just remove that so we don't have to add that into the stack also in the question if we had a single period we had to remove that from the stack so say for example we had a period at the end here we aren't going to include this in the unix style file system structure right because periods are excluded from that so we can remove that as well so if we have an empty string or period continue now in this last example we have two periods and that meant going to the directory one level above so that meant going to this value now with the stack data structure if we have these in order all we need to do is pop off the stack to remove this value and then we just have home so if we reach a double period we need to pop off a stack so now with this example what are we going to be pushing into the stack so we're going to have the stack and we aren't including empty spaces we're just including home with this example here we aren't including empty spaces or periods so we are just going to be including home and foo and with this last example we push in home we push in foo but then we come to the double period in which case we pop off the stack go back to home and that is what we're going to have at the end of this example okay so we're almost there we have the stack now we need to convert this back into the unix style file system so it's a string we need a forward slash at the start and we need to separate these via forward slashes so how can we do that well we could just add a forward slash to the stack and with this example we could join it by a forward slash so with the first example we are going to get home in the second example we are going to have home foo and with the last example we are also going to have home so what this question is really looking for is to see whether you can test a number of different edge cases and the best way to do that is just to have a number of different examples to run through in the interview so time complexity for this one is o n because we're looping through the string once and space complexity is also of n because we're using a stacked data structure to store the strings so there isn't really much to the solution to this question we initialize the stack we update the path by splitting it via the forward slash then we loop through the string we check if path i is equal to a period or is equal to an empty string that's the case then we continue else if path i is equal to a double period we need to pop off the stack else we are just going to push the value onto the stack like we said in the question we are going to add a forward slash to the start of the string and we are going to join what's in the stack by a forward slash and then we can return this value let's give this go okay it's been accepted let's submit it and there you have it
Simplify Path
simplify-path
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**. In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names. The **canonical path** should have the following format: * The path starts with a single slash `'/'`. * Any two directories are separated by a single slash `'/'`. * The path does not end with a trailing `'/'`. * The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`) Return _the simplified **canonical path**_. **Example 1:** **Input:** path = "/home/ " **Output:** "/home " **Explanation:** Note that there is no trailing slash after the last directory name. **Example 2:** **Input:** path = "/../ " **Output:** "/ " **Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go. **Example 3:** **Input:** path = "/home//foo/ " **Output:** "/home/foo " **Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one. **Constraints:** * `1 <= path.length <= 3000` * `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`. * `path` is a valid absolute Unix path.
null
String,Stack
Medium
null
1,647
uh let's talk about a minimum direction to make character frequency unique so a good string s if there are no two different characters in s they have the same frequency so basically you don't want a character that have the same frequency in the string so uh in this idea we can actually use a container array to just making sure every single character occurs how many times in the string so let me just stop holding this i'm going to say i'm here brand new ins and i can say 26 because the character is 26 uh character right and i will just traverse see it's not through charlie and then just adding the c and then i need to subtract the character a this is because it's the last key table and i only have 26 space in this continuity and later on i need to just keep double checking if they are actually have the same frequency before when i'm traversing at least in this uh or ls index right i can use the hash asset and i'm going to show integer i'm going to close set and i can accept and i need to traverse the diverse accounting array to to check if this current character index uh has been used or has been dated you know i need to check so if the content i go to zero uh basically i don't want to get uh i don't think about it right now uh the problem is this uh how do i know how many dilution i need to make right so i need the uh a new variable to uh delete also the labels initially equal to zero so i will do what okay i would say if c i is greater than zero balance is set up at uh container rate r right so the reason why using this is because when you delete right uh at some point like uh maybe this one right c a c e a b a c-a-b-b right a c-a-b-b right a c-a-b-b right you are not going to return well you are not going to return c probably right because you have to remove c somehow i mean wonderful solution be honest because ceo or c of course one time and a of a also occurred one time right you need to keep one right so this will be pretty much like see you have to get rid of it right but when you get rid of this the frequency is actually equal to zero right and then uh this is not low right i need to making sure when i did it right so how do you actually did it i need a while loop the reason why i need a value is because you probably have to delete every uh every times when you want to check like maybe you have five times of character b right and you have a five times of character e beforehand and then you probably have to remove one time or probably you have to remove two times right because probably there's a four times character of b right uh four times square root of a or sorry so you have to remember two times right so basically this is a solution so you have a condensation i so if you find there is a frequency inside a headset you need to remove so i'm going to say i minus now uh every single time you remove you need to increment your delete right and at the end you'll return it so this is pretty much the solution all right i made a mistake all right okay here we go so let's talk about time so time this is all the frame right uh unrepresented stop names and this is of 26 and i would say like uh probably all the fun most likely uh would be uh the worst case be honest i mean if the stream is shorter right definitely like 26 right but 26 is actually a constant beyonce so if you really want to be most be more specific probably you have to say 26 or all of them i mean all of 26 or all of them like which one is greater you pick right and the space is going to be what uh this is going to be a space right here set and it comes in array so this is going to be all the 26 right and this is going to be all of what probably like uh all of them and probably if they are actually have every single time you have different uh different frequency so uh time and space are the same be honest so just making sure you want to say all of them or all of 26 so this is pretty much a solution and i'll see you next time bye
Minimum Deletions to Make Character Frequencies Unique
can-convert-string-in-k-moves
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**. Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._ The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`. **Example 1:** **Input:** s = "aab " **Output:** 0 **Explanation:** `s` is already good. **Example 2:** **Input:** s = "aaabbbcc " **Output:** 2 **Explanation:** You can delete two 'b's resulting in the good string "aaabcc ". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ". **Example 3:** **Input:** s = "ceabaacb " **Output:** 2 **Explanation:** You can delete both 'c's resulting in the good string "eabaab ". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). **Constraints:** * `1 <= s.length <= 105` * `s` contains only lowercase English letters.
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
Hash Table,String
Medium
null
1,066
all right i am so excited to bring you guys this video today we're going to try something new i just bought an ipad so i'm going to use it as a virtual whiteboard and hopefully this will improve my production quality you know you guys can be able to see things on a bigger screen be able to um get some better visuals so all right yeah let's try this out so let me know what you guys think about it all right so um okay don't worry but don't look at this code yet but um okay i'll go through the code later let's first talk about the problem so we're going to look at the code 1066 campus bikes 2. if you've already done campus bikes 1 you know that the first part we only had to do a greedy solution so basically um in the first part they wanted you to you have some workers you have some bikes you want to pair each worker with a bike and you want to pair the workers so basically you go through and find the distances between each worker each bike and then you greedily just pair them based on who's closest to what um right so in this case it would be worker one goes to bike zero and worker zero goes to bike one because worker one is closest to this and then you pair worker zero with bike one so that was all completely greedy in this problem it's asking us to return the minimum possible sum of the total assigned distances right so basically that means uh let's see how let's see what the total distance would be if we followed the same approach from part one so part one you would just assign where we want to like zero so what's that distance that's a distance of two blocks and then workers zero with bike one that's one two three four five six so that's two plus six that's a total of eight units of distance um but it says that the best possible distance is six so how do they get six well they paired worker zero with bike zero and worker one with bike one right so workers zero to bike zero is one two three units worker one is one two three units to bike one so that's a total distance of six so ideally you wanna minimize your total distance your total combined distance for all the different assignments so the only way to do that is actually to try all the different combinations so that's why this problem they have way less workers i think in the problem in the first problem they had like a hundred or something for n m in this problem it's only ten so you can see how this problem um the time complexity is insane if you do it brute force um i mean regardless of brute force it's still gonna be a pretty costly problem so let me show you the different uh let me show you what let me show you why the time complexity is so high so let's go to the whiteboard and let's show you how i kind of visualize this in my head so let's say we have like a set of workers so we have workers zero one two three and then we have a bunch of bikes we have a set of bikes like zero one two three four bikes so we'll kind of just go through all the different workers from worker zero all the way to three we'll kind of just sweep through like this and for each worker can choose either this one or this one any of these bikes that aren't taken yet so right so worker zero could take one two three four bikes so this one you know you have four different paths here and then this worker um can take you know let's say worker zero took bike two so then this we go to the next iteration so for the next worker one can choose from any of these three remaining bikes right so it has one two three choices and then worker two we go to the next bike okay let's just say worker one chose this bike then we go to the next worker two can choose from any of the two remaining bikes so he chooses another two and then we let's say he chooses one then we go to the next worker the last worker and this last worker just gets assigned the final bike right so we can see that this one had four three two one so this is basically n times n minus one times n minus two blah all the way down to m s1 this is n factorial time complexity so this is going to take a long time to uh um you know do so let's see where dynamic programming comes in and where are the sub problems what are the sub problems that we can get out of this shoot um okay so let's see the different sub problems that we have sorry for that okay so the different sub problems that we have let's just say we same examples we have workers one two three zero one two three we have bikes zero one two three so let's say we assign this worker bike one bike zero by two and then uh we come to this okay so let's show you all the different states right so we have one two so let's say in an alternate path you know we could have assigned this guy to this guy is zero this guy one right so we've processed these first three and they've come to the same state right like this last guy has the same exact remaining bikes to choose from and um you know basically these two sub problems are both gonna have the same answer coming from this three right so remember if you remember in like a dfs um you know the bottom stuff it kind of bubbles up in the dfs the bottom the leafs kind of solve their sub problem first and then it bubbles it up to the you know previous one and then this stuff gets calculated and then it bubbles the answer back up to the you know previous one so that's why this three would get calculated first this sub problem for three would get calculated first it would pass it back to here but these two are in the same state right we've used up the same exact you know one zero one and two bikes so that's why these two would be repeating this sub problem for three so we can you know even another case where we'll be repeating sub problem is if we assign this one zero sign this one assign this one two right so you can see that there's a bunch of different overlapping sub problems and that's why we use dp so what is what's the dp that we're going to take advantage of so we're going to basically keep track of which um so basically we're going to go through the workers again like this one by one and so basically after worker zero chooses some bike then we'll keep track of which bikes he took and which bikes are still remaining so you know some naive way to keep track of which bikes have been used and which bikes haven't been used is you can just use a set of length n or like some list of length n and you know for bike 0 let's say it was used bike 1 was not used bike 2 is not used right we can just have a boolean list and pass through a list every time but caching a list you can't really you can't hash a list in python i'm not sure about other languages but you'd have to turn this into a tuple first and this is just so costly and passing along some list every time is also costly and annoying um so actually there's something called bit masking and you might have heard this before and it might sound pretty overwhelming at first but let me kind of go into the details and show you how bit masking is so much more efficient than that first approach with the list um so with the bit mask what we're trying to achieve is obviously the same thing as the list we want to keep track of which bikes were used and which bikes were not used how can we do that with a bimask a bit mask is going to be a binary string representation so let's say we have four bikes right so we have four um bits here right so this bit here will represent the zeroth bike this will remember the first bike second bike third bike so zero means that there is no bike present there or sorry it has not been used yet if this was a one that would mean that the zeroth bike was used you know same thing if um if this was sorry if this was a one then it means that the first bike was used so how can we keep track of you know the different um okay let me back up so first let's say that we have some existing um bitmask that we're passing into the current state so let's say we're on worker one or whatever and the first guy picked bike once right so that's what this state is representing you know we've already picked the first bike and we have these other three bikes remaining to choose from right so we're at worker one how do we know which bikes were chosen and how do we like yeah so how do we determine which bikes um are valid to choose from you know it would be kind of cost effective if we went through and iterated through every digit of this binary um you know first of all this binary is represented as an int whatever don't worry about that so basically just think of this as a binary we'd have to iterate through each digit in the binary so that would be an o of n operations so that'd be cost inefficient as well a way to do it with bitwise operations which is really quick is to kind of we'll use the and ampersand and we'll use a pipe so ampersand is the bitwise and this was this is this pipe is the bitwise or so let me show what let me show you guys what i mean by this let me grab a sip of water okay so we've taken the first bike so let's say we're going to be iterating through you know for each of these um workers each of these is basically a recursive call right we're going through each one as a recursive call and inside each recursive call right like this right so we have the worker index so we're starting from worker 0 and then each dfs call is going to you know increment the worker index so we're kind of just going through and um you know incrementing the worker index every time until we hit the end but inside each recursive call we're also doing a for loop we're going to loop through all the bikes right so let's see this so for b in bikes so for each worker we're going to be doing this for loop and then so basically we're going to be checking if that bike if this bike b is already if it has already been used how do we check if it's already been used without having to iterate through all these digits right what you can do is use the ampersand so this ampersand is essentially so what's going to happen is let's say this bike um so we're iterating through bikes you know zero one two three um so let's say we start on the zeroth bike here and so what happens is that zeroth bike is going to be represented as a it's going to be represented with the string of zero one um right because this bike is in the zeroth position this string right here this binary masking represents that we want to take the bike at index 0. if we were iterating through and we iterated to the second index then this string would look like then the string would look like it would look like 0 1 0 right this is the 0th index version next second index this binary string represents we want to take the second bike um so let's say we want to say take the second bike right so how do we check from the current bit mask right this bit mask here is the one that's getting passed in every time in a recursive call all right we have this recursive call and we're passing in some bit mask which represents the bikes that we've already taken and which bikes we haven't taken yet all right so let's say hypothetically this is our masking for this recursive call so how do we go in and compare this mask with this current mask that we want to um take from right this like i said this mask represents um that we want to take bike to so basically you know we can see that bike 2 was not taken in our parameter mask right it's there's a zero here so it wasn't taken so what we can do is um we can use a ampersand to compare these two binaries right 0 1 0 and 0 1 0. what the ampersand will do is it will you know take the end of these two values right the end of zero and zero is zero the end of zero and one is zero the end of one zero is zero the end of zero is zero right so this these two ended together gave us zero so that means that if there was nothing if there was no overlap if you know if this was one instead if this position two was taken let's say this was taken over here right then these two ones would have produced a one here so this is not equal to zero anymore right this is not equal to zero so when it's not equal to zero that means that this bike is a has already been used if it is zero that means this bike hasn't been used so basically what we're going to be checking is just you know we're just going to be checking if let me go back to the code we're going to be checking if this mask ended with if this mask ended together with this right here i or one left shifted by oh yeah so i forgot to explain the one left shift i so basically what this means is let's say we were looking at bike two right zero one zero to get this binary what we had to do was we had to take a one so a one is represented as zero one in binary and we left shifted this one two spots over here that's how we got this zero one zero right so this b the bike b has a value of two an integer value of two right so if we left shift it by two values then we're going to be representing this binary zero one zero so that's what we have here so if we and together this original parameter binary string with this current binary string which is the one that we want to check if it already if it has been taken or not then you know like i said if it comes out to zero that means that um it has not been taken yet if it comes out to something other than zero like zero one zero that means it has been taken and we can't process that bike and we have to go to the next bike so okay oh yeah so also how do we know so let's go back and have this example again so how do we so that's how we check to see if a bike has already been used so let's say the bike wasn't used and we want to update our mask to reflect that we're going to use that bike so let's say you know we wanted to use this second bike so first of all we checked that these two ended together gave us zero so that means we're good to go and we're good to use this bike so now after we've used it we want to update our mask right for the next iteration of the recursive call we want to tell the next recursive call that this state has been changed that the this bike 2 has in fact been used so how do we update this one and put it into the binary string you know right because our resulting string we want it to look like this right to represent that we have taken the bike here and we've taken a bike here so how do we do that how do we update this string well we can use the or we can use the bitwise or so what this will do is you can order these two strings together right so zero order with zero gives us zero ordered one gives us one ordered zero gives us one zero ordered zero gives us zero right so that gave us you know now this new binary string representation tells us that we have taken a bike at um index 1 and index 2. right this is our new state and we're going to pass this new state to our next recursive call so let's kind of just walk through the code so i've kind of gave my spiel about everything now and let me kind of just walk through the code at this point so if you haven't watched my previous videos please do that's basically what this cache i've explained the cache twice already so please watch that this is essentially the same thing as using a dictionary to store the results of the different combinations of worker index and mask but in python it'll just do it for you so all the different combinations of worker index slash mask will have their own entry in this dictionary and then the value will be the minimum distance at that state so um basically this is the starting point of the application of the function we call dfs with worker index zero and a bit mask of zero an empty bitmask so we come into the dfs and basically our base case is if the worker index is equal to the length of workers then we should return zero and stop doing anything um also so yeah so basically the main core of the logic which i've explained is we're going to iterate through all the different bikes and we're going to check to see if the bike was used already this condition means that it has been used so we're going to just continue to the next iteration to the next bike and try to use the next bike if this case was not hit that means that the current bike we're looking at has not been used yet so we're going to find the distance from the current worker to that bike and then assign this current worker to that bike and then we're going to update the workers we're going to up we're going to move forward to the next worker and try to assign the next worker to something and this is like i said earlier this is the or and we're going to just insert this one into that location in the bit mask to represent that we are taking that bike now and then at the end we're going to continuously just update this temp variable which is basically just going to right this dfs call is going to return to us some sort of distance right each dfs call is returning a sub problem um right because at the end of this you can see i'm returning temp so each dfs call returns some sort of sub problem you know once you're here like i said in the earlier example with the three this three will return some sub problem back to two and then this whole thing will return some prob sub problem back to one this will return right so each one is returning some sub problem and you want to minimize that right so you're going to take the minimum between um the current temp right so like i said we're trying um so this is basically going through all the different bikes and we're going to try assigning each worker to each of these four different bikes right so whichever one gives us the smallest value we're always going to keep updating that's what this temp variable is going to hold and so at the end we're going to just return this temp and it's going to be cached in our cache here all right oh i'm out of breath i've lost my voice please i think that's a pretty comprehensive explanation i tried my best i tried to use the new technology please if you enjoyed the video you know let me know if you have some complaints about my explanation please give me some feedback you know i'm always receptive open to hearing some feedback if you like this style just let me know give me some good comment good feedback bad feedback whatever just leave some feedback and tell me what other problems you want me to do also after this video i'm going to record another video which does bit mask so you can you know you can solidify your understanding of bimask in the next uh upload so all right see you guys in the next upload thanks for watching
Campus Bikes II
fixed-point
On a campus represented as a 2D grid, there are `n` workers and `m` bikes, with `n <= m`. Each worker and bike is a 2D coordinate on this grid. We assign one unique bike to each worker so that the sum of the **Manhattan distances** between each worker and their assigned bike is minimized. Return `the minimum possible sum of Manhattan distances between each worker and their assigned bike`. The **Manhattan distance** between two points `p1` and `p2` is `Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|`. **Example 1:** **Input:** workers = \[\[0,0\],\[2,1\]\], bikes = \[\[1,2\],\[3,3\]\] **Output:** 6 **Explanation:** We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6. **Example 2:** **Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\] **Output:** 4 **Explanation:** We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4. **Example 3:** **Input:** workers = \[\[0,0\],\[1,0\],\[2,0\],\[3,0\],\[4,0\]\], bikes = \[\[0,999\],\[1,999\],\[2,999\],\[3,999\],\[4,999\]\] **Output:** 4995 **Constraints:** * `n == workers.length` * `m == bikes.length` * `1 <= n <= m <= 10` * `workers[i].length == 2` * `bikes[i].length == 2` * `0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000` * All the workers and the bikes locations are **unique**.
Loop over the array and check the first index i such A[i] == i
Array,Binary Search
Easy
null
1,576
let's solve lead code problem 1576 replace all question marks to avoid consecutive repeating characters the question goes like this so you'll be given any string right and some of the characters on that string will be question marks right so all you have to do is replace this question mark with some character some alphabetical character some letter making sure that the character that you choose is not on the left or the right of the question mark So if you choose D here it would be wrong if you use K here it would be wrong you need to choose something which is not D or k similarly here if you choose K here it would be wrong if you choose J here it would be wrong it should be something which is not K or J right and then return the string so all you'll be given is the string how am I going to solve it simple suppose this is the string I'll put question marks in some place this is right so what I'll do is First Step uh would be what I'll go through the string one by one and check the left and the right and accordingly update it if I find a question mark I'll check the left I'll check the right and accordingly update the question mark right but uh if the question mark is at the beginning there's no left if the question mark is at the end there's no right so I'll handle that separately okay even before the loop and I'll run the loop between the first index till second last index so let's code it on right so first of all I'll convert the string into a an array so that I can easily work with it right string are immutable and every time I want to make a change I'll have to uh update the entire string again and again so I'm converting it to an array I'll update the array I can change the elements in an array and finally I'll join and return it will be something like this so I'll join and return s again in between first of all I'll let me write the loop for I in or for yeah I in range one to length of s minus 2 oh sorry minus one right and so what will I do I'll check if the current character or current character if that is equal to question mark okay what I'll do is I'll run a for Loop for C in characters a b c what will this do us it will pick character first character second character third character and what I'll do inside this is I'll pick the first character first and check F SI minus one which is the previous character is e equal to C or s i + 1 is = to C or s i + 1 is = to C or s i + 1 is = to C in both the cases what I'll do is I'll move ahead right or I could do the other way around set if s of If the previous element is not C and in the if the next element is also not C then I'll update it to be C then I'll change the current element to C because the previous element is not C and the next element is not c is the character right or I could say to be more here I'll update it to the character so it will pick the character if this character is not in the left or right side of the current character it will update it otherwise it will go and pick next character right at least one of the three will be successful if left is a or right is a it will move ahead if left is b or right is B it will move highe move ahead and if uh and c will definitely be not there on the left hand side or right hand side the first two conditions have passed right and otherwise what happens if otherwise right or uh after I have updated I could simply break out of here right because I have resolved this question mark I can break out of here of this for Loop okay that's taken care of now the next problem is that the first character in the last paper if s of Z is equal to or I could use this Spore Loop here for C and ABC again and in fact I could just check AB this time because there's only one character I need to check so it's either going to be a or b if it's a I'll update to be B otherwise it will updated to be a right so s of I If s of I is equal to car sorry f s of I + 1 that's equal to car sorry f s of I + 1 that's equal to car sorry f s of I + 1 that's equal to before that I need to check if uh s of0 not s of i s of one in fact right if s of0 is equal to question mark only then I'll be running this okay and what will it do is if F1 is equal to car is not equal to car right that's not equal to C then I'll update s of one to be S of0 to be the character right same thing I can copy and put it here if s of last element is question mark then I'll follow character in AB if s of - AB if s of - AB if s of - 2 not equal to car then s of 0 is z not z s of minus1 is equal to K right if s of -2 is not is equal to K right if s of -2 is not is equal to K right if s of -2 is not equal to 0 then s of -1 = to K and equal to 0 then s of -1 = to K and equal to 0 then s of -1 = to K and finally I return this let's run and see I could get into an error we'll fix that yeah so we have encountered the sorry this is not length this is list to convert it into list now we have done we have converted into list it's working let's submit it and see for all the use cases and it throws an error for the use case where the length of the string is just one right so what am I doing uh so if it is it's an edge case because clearly I cannot compare the next one or the previous one so if length of s is equal to one and S of Z is equal to question Mark then I'll return how about I simply return a right let's run and see so this is an edge case and that worked 27 milliseconds better than oh it's very poor and performance that could be because there's heavy load on the server side or is it really my program which is bad Lo it is improving so it's a high peak time servers are how to we know let's look at the best solution is doing something similar to what we are doing right they have just moved this out this was unnecessary putting entire string ABC would have done the trick this was clearly unnecessary but yeah this works let's look at some more solutions again for Loop goes through the range X question mark If yeah here it's doing something similar to what we doing if character in ABC then it's updating it and here it's just checking if it's the first element or the last element and so on so that's how it's Sol and that's how we solve problem 1576 repa all question marks to avoid consecutive deping characters see you in the next video
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,640
Hello hello one sir let's see the question January changes is its first question and check the reformation proximity of contention solved Here first an area is given which is all its element district and a piece of the same area is given it has been given some strength and grinded it. And it should be 150 real distant. If it is made like this, then it is your Google which will make this face whatever is from behind, do all the contacts in any order. You should get this for that you are not allowed in your order the speed of Element like this, you scan it, you can turn it on with this element, these Shyam 9896 can come on continuing content, so like this, 1628, so we will not be able to do it from one to the other, so all this cannot be achieved from both, so here But we get tips, there is an apk file that is behind this, if it is 8585 quantity minutes, then it has got CO. Now let's watch the porn movie, this is the feature and so one piece of mine, if you can arrange it in some tummy, then just do five and eight. Now we can add elements inside this, we can do this combination which is next to Ajay, next is the example, so here 9114 six and seven eight and from the back, this is the first 9, keep this first. We give it first but after that if we need more then we put it in the center and we need 378 tomatoes, we can make this like this, now look at this face in this, if there is any judgment in this, then this will make this, then now how to think, then one can do this We are also elements, keep it like that 98100 a flying dec06 four's seven is eight and 78th here sorry this is two and this is free so with the help of these pieces we have to make this so every element is district in this and also in this So there is no question of repetition, so first of all we will see that from 7878 clients, my husband is 728, in this we will check if he had already started it, we will emphasize on this 323, we will appoint here, subscribe, 6 continuously increase the speed. Today, this is continuous, let's look at the element 2019 and this is possible, so let's go now, what happened is that first let's take the excise here and here Nitish will do the maximum fine day e the index and its Khasam of the length of that, so we take this, let's take one ego in which we can store the feet, then one Maithili, we can store this request in this, let's go to size 168 and we started this element. There is Its first elements are present then let's check this mp dot front part in different places come back if you like it then it is not equal to inches then print if it is not president then return it first check that elements are present president I am subscribed and I liked it on the index. I got to know from ma'am whatever festival was there and will check all the elements of the species in this index shares. So let's go to all the elements of the species. Let's turn on the Bluetooth settings. Pay is its element, if you like and share this, then we will check your intake that if it is not equal to 30 which is Bhairu, we will return it so that if it is not a Delhi school then it did not match like Here, first you go into this and so will be equal to if six has happened to melt the ice or if not till now then we will do for the next parties then the index will move forward and this is next to its next element so that's done. There can be a person who consumes me, I have this cigarette here, after that, who subscribes to this channel, the effect on the index will be equal to the addictions, file a return here, if this happened to whom, then everyone else. I am also subscribed to the channel, I am taking good stress, custom tips are clear, there is a compiler, it is not known, it was not added in the size, it is here that the size is matching with yours, it seems to be submitting. What has happened is that there has been a police accident. If you would understand then you would have liked. Thank you.
Check Array Formation Through Concatenation
design-a-file-sharing-system
You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`. Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`. **Example 1:** **Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\] **Output:** true **Explanation:** Concatenate \[15\] then \[88\] **Example 2:** **Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\] **Output:** false **Explanation:** Even though the numbers match, we cannot reorder pieces\[0\]. **Example 3:** **Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\] **Output:** true **Explanation:** Concatenate \[91\] then \[4,64\] then \[78\] **Constraints:** * `1 <= pieces.length <= arr.length <= 100` * `sum(pieces[i].length) == arr.length` * `1 <= pieces[i].length <= arr.length` * `1 <= arr[i], pieces[i][j] <= 100` * The integers in `arr` are **distinct**. * The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
Try to solve it by keeping for each file chunk, the users who have this chunk. Try to solve it by keeping all the users in the system with their owned chunks, and when you request a chunk, check all users for it.
Hash Table,Design,Heap (Priority Queue),Data Stream
Medium
355
1,480
hi guys this is khushboo and welcome to algorithms made easy in this video we will see the question running sum of 1d array given an error nums we define the running sum of an array as running sum of i is equal to sum of num 0 to the num till ayath position and we need to return the running sum of the nums array there are a few examples given with us in the example 1 you are given array 1 2 3 4 and your output for this would be the first digit will be one the second would be addition of these two which gives you three the third would be addition of these three which would give you six and fourth would be addition of all the numbers which would give you 10. similarly with example 2 and example 3 also the constraints given with the question are that the length of the nums array would be between 1 2 000 and the numbers in it would range from minus 10 raised to 6 to 10 raised to 6. this is a fairly simple problem as you can see from the explanation of the first example over here all you need to do is take the for loop and you will start from i equal to 1 because the 0th position number would always remain the same and would not need any updation then you go up to nums dot length and you can simply change the nums array and say that numbers of i would become nums of i plus nums of i minus 1 that is the previous number finally you can just return the num's array that would contain your running sum let's run this code and it gives a perfect result let's submit it and it got submitted so the time complexity for this particular problem would stay of n and the space complexity over here would become o of one because you are just updating the same input that is given to you and not using any other extra space so that's it for this question guys i hope you like the video and i'll see you in another one so till then keep learning keep coding
Running Sum of 1d Array
movie-rating
Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`. Return the running sum of `nums`. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[1,3,6,10\] **Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\]. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** \[1,2,3,4,5\] **Explanation:** Running sum is obtained as follows: \[1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1\]. **Example 3:** **Input:** nums = \[3,1,2,10,1\] **Output:** \[3,4,6,16,17\] **Constraints:** * `1 <= nums.length <= 1000` * `-10^6 <= nums[i] <= 10^6`
null
Database
Medium
null
973
hey everyone welcome back and let's write some more neat code today so today let's solve the problem k closest points to the origin so let's take a look at this example and you can't really see it well but they have a couple points so there's one point over here and there's one point over here so we have a list of points right we could have a bunch more points right anywhere on this two-dimensional grid we have an x-axis two-dimensional grid we have an x-axis two-dimensional grid we have an x-axis and a y-axis so each point is and a y-axis so each point is and a y-axis so each point is represented by a pair of values this point is 1 3 this point is negative 2 right and so we can have a bunch more points and we want to return from the entire list of points we want to return the k closest points to the origin now the origin is the center which is zero right so which of these points is the closest to the origin and in this case we have k equals one so from these two points we just want to return the single point that is the closest to the origin and we're guaranteed that the solution is going to be unique so there's never going to be a tie or anything like that but it could be you know in this case we have k is 1 it could be k is 2 k is 3 or something if we had a bunch more points so we just want to figure out efficiently what are the k closest points to the origin now the first thing is how do we know how far any given point actually is from the origin you know you might remember from your you know high school math class or in this case they actually tell us the actual formula which does make things a little bit easy so it's basically taking the x difference right so in this case for this point the x difference is going to be 1 minus 0 plus the y difference in this case the y difference is going to be three minus zero and each of these is going to be squared because you know that's kind of how it works a squared plus b squared equals c squared this is the formula we're using so if we want to find c which is going to be the actual distance we'll take a squared plus b squared and then take the square root of the entire thing to actually find c so you know finding the distance we can do that a squared plus b squared taking the square root but in this case we actually aren't required to find the square root because we're not actually trying to return the distance we're just trying to determine which point is the closest so you know for example let's say we had something like this that totaled up to five right and we had another one that totaled up to 4. if we take the square root of 2 or 4 that's going to give us 2 if we take the square root of 5 is going to give us 2 point you know something so we're not required to take the square root because we just want to be able to compare which one is greater right obviously if 5 is greater than 4 we know that the square root of 5 is also going to be greater than 4 so we're not technically required to actually take that square root and i don't know why i'm making this such a big point it's just that it's kind of easier to code it up then if we don't actually have to take the square root we just take the absolute difference between the x square it the difference between the y square it and then add them together that will be enough for us to compare two points and to figure out which one of them is actually closer to the origin so once you have that down how can we actually find the k closest points we're not just finding the single closest point that would be easy but we're trying to find k of the closest points well the easiest and simplest idea that you might think of is just sorting right so if we have a list of size n and for each one of these points we you know compute this take the x difference y difference square it right and use that value to sort the entire list of points the time complexity of that is going to be n log n because we're sorting the entire list and then once we have that right like let's say we had what you know three values or something we just wanted the first two which is k and then we can just iterate through the list and find k so the k is not really going to change the time complexity is going to depend on the n log n sorting but since we're only looking for k points right we don't actually need to sort the entire thing we just need the k closest points so actually this problem can be reduced or slightly simplified if you use a min heap and that's going to be the solution i'm showing you if you know if you already know how to use a min heap you can probably skip to the coding portion or you know solve this problem yourself a min heap is a good way to solve this problem but i'm going to analyze it for you right now so let's still take the simplified example so like i said the first thing we're going to do for every point so we have the point 1 3 and we want to know the distance between it so we can say okay 1 squared plus 3 squared which is going to give us 10 so this is you know the distance actually isn't 10 but that's going to be the value we use to compare we're not going to take the square root because we actually don't need to the other one negative 2 positive 2 is going to be 2 squared plus 2 plus negative 2 squared which is you know just going to be 2 squared as well so taking both of these together is going to be a distance of 8 so the next thing we're going to do is take these right notice how we put the distance as the first value because when we put this in a min heap we want this to be the value that we order it by so we're going to take this and we're going to run the function heapify which is not n log n heapify is actually a linear time algorithm so it'll basically take all of these put them into a heap in o of end time so now you know let's say that all of these are in our min heap what are we going to do we want to pop from this heap k times because we want every time we pop we want to pop the closest one which is in this case going to be this point right and of course k in our example is only one but obviously this solution could be generalized to if k was two three or bigger right so in this case how many times are we gonna pop from the min heap obviously k times we only need to find the k closest points and what's the operation for popping from a heap it's going to be log the size of the heap which is worst case going to be n so this time complexity is actually going to be a little bit better it's going to be k log n that's why a min heap solution is slightly more efficient because if k is relatively small it's going to be a lot better than something like n log n right this is much smaller this is much faster so that's kind of the idea at this point you probably know how to code it up but you know just to finish the example k is one we pop from this one time are we gonna pop this one or this one obviously this one has a smaller distance so we pop this one and then we take it append it to our result and we only append the coordinates were negative two positive two right we don't actually have to append the distance or anything so this will be added to our result and then we're going to return that result right we only need to pop once and we can return that you can see up in the result over here at the top that's exactly what they did they just returned a list of one point so that is the main solution now we can go ahead and code it up so now let's actually code it up and like i said we're going to be using a min heap so initially a min heap is just an array or a list in python so what we want to do is we actually want to go through every pair of points every x y in the input list points and we want to go ahead and actually compute the distance so how can we compute the distance for every point well it's pretty much just going to be x squared plus y squared right so we can take x in python you can take x to the power of 2 like this plus y to the power of 2 like this and add those together we just won't take the square root because we're lazy and we know that we don't actually need to take the square root so then to our points or rather to our min heap we can append to it this uh point that we just calculated right so we'll append the three values we talked about the distance is gonna go first because that's the key value for our min heap python will use that the first value by default and we're going to also append the coordinates of this point as well and now that we have all those points in a list obviously that this operation was a linear time operation now we're also going to do a linear time operation in python we can turn that list into a heap like this heapq.heapify that list so it'll reorder heapq.heapify that list so it'll reorder heapq.heapify that list so it'll reorder the list to make sure that it is in the structure of a heap and we also want to have a list for the result right we're going to pop k times so while k is greater than zero we're going to keep popping from our min heap we're gonna say heap q dot heap pop from the min heap and whatever value is popped we're gonna append it to the result just like this but actually i just realized we're actually popping three values from it so before we append it let's get the three values we're popping the distance the x-coordinate and the y-coordinate from x-coordinate and the y-coordinate from x-coordinate and the y-coordinate from the min heap and once we pop those three values to our result itself we're only appending two values the coordinates the x and y coordinates and we're gonna do that k time so let's make sure to decrement our k value and so once we've popped from it k times we can go ahead and return the result that we just created and as you can see the solution works and it is pretty efficient i think a sorting approach would be about as efficient but this is slightly better in some cases so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
K Closest Points to Origin
stamping-the-sequence
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in). **Example 1:** **Input:** points = \[\[1,3\],\[-2,2\]\], k = 1 **Output:** \[\[-2,2\]\] **Explanation:** The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\]. **Example 2:** **Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2 **Output:** \[\[3,3\],\[-2,4\]\] **Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted. **Constraints:** * `1 <= k <= points.length <= 104` * `-104 < xi, yi < 104`
null
String,Stack,Greedy,Queue
Hard
null
1,608
hello so this question is special array with X element greater than or equal to X so this question is pretty challenge uh the wording is kind of tricky so if the nums is considered special if there exists a number X so this is going to be the dynamic value that you want to find out what is the number X such that there are exactly X number in nums are greater than or equal to X so three and five are consider what um a special element because two there are two value three and five they are greater than or equal to two so um so the maximum so if you look at this so the maximum output is going to be the L of num array right and you had negative one if there are zero so you'll have three this is because if you get R of zero right then you'll say okay these are the special element when you Traverse three then you know this is the minimum you can get it's between the element inside the CH the chosen one right all right so what you can do is you want to create a counting array uh so let's look at this so you want to create a counting array and then you store element inside a cting array and if the element is greater or equal to the L of the nums you just consider is this like this value is equal to two so the L is two right and then we create a counting array space s two sorry three this is because you want to include the index zero and then we know the value for the first one is three so three is greater equal to two this is going to be length so we want to consider this guy is the counting array at two Plus+ so we two Plus+ so we two Plus+ so we increment this element as a increment we increment this element as a two so five is going to be the same because we don't want to create extra space all right so once we do every uh the conent array then we can check the number X so we want to return number X so you will definitely starting from the last it's going to be the length minus one all the way to one you don't want to say zero this is because you will just return negative one at the end and then you want to just keep adding so S Plus equal Contin AR R element if x is equal than the current index then we know like this is the condition we satisfy you want to say Square equal right but once you say equal this will be fine U all right so let's start doing this so I'm ARR a new in nstop l plus one and then for in nums I want to say if n is s equal to n lens and then I will say Ting array and lens Plus+ lens Plus+ lens Plus+ else find array and n Plus+ so we don't worry about Index Plus+ so we don't worry about Index Plus+ so we don't worry about Index right and then at the end you one just in case I forgot and then I can derse from the last element inside a compy array all the way to zero but not including zero and iusus all right so what we can do is like we can using the X = to Z like we can using the X = to Z like we can using the X = to Z right and then we say X plus equal to the C array I if x = to I you want to return X I if x = to I you want to return X I if x = to I you want to return X right so yeah let me run it and let see what happened so this is a like this condition like is greater or equal to X like I already convert the element into the I mean into the content arrays and then you just want to make sure the S equal to I and you will get the answer all right so the timing space for this one is all of n for the space all of n for time all the lens uh the L for the time and then you can get a little bit Improvement based on list syntax still doable time and space of the same so this question is a little bit challenge like you want to understand the question before you do uh start coding but other than that it's pretty straightforward all right I'll see you next time bye
Special Array With X Elements Greater Than or Equal X
calculate-salaries
You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. Notice that `x` **does not** have to be an element in `nums`. Return `x` _if the array is **special**, otherwise, return_ `-1`. It can be proven that if `nums` is special, the value for `x` is **unique**. **Example 1:** **Input:** nums = \[3,5\] **Output:** 2 **Explanation:** There are 2 values (3 and 5) that are greater than or equal to 2. **Example 2:** **Input:** nums = \[0,0\] **Output:** -1 **Explanation:** No numbers fit the criteria for x. If x = 0, there should be 0 numbers >= x, but there are 2. If x = 1, there should be 1 number >= x, but there are 0. If x = 2, there should be 2 numbers >= x, but there are 0. x cannot be greater since there are only 2 numbers in nums. **Example 3:** **Input:** nums = \[0,4,3,0,4\] **Output:** 3 **Explanation:** There are 3 values that are greater than or equal to 3. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
null
Database
Medium
null
1,385
hi my name is david today we're going to do number one three eight five find a distance value between two arrays this is an easy level problem and we're going to solve it in javascript so basically the prompts a little bit confusing given the amount of dislikes it got but what we have here is an array of them the first input argument is in every one the second argument is another array and this third argument is an integer and it wants us to return an integer and this integer is how many times it fits the category where the difference of each of this one each uh each index of the array one iterated throughout each one it gets their absolute value as the difference and as long as all of them is greater than the d it gets incremented to the output and same for it happened to for five the difference absolute value of the difference is all greater than d or two and then the last one eight minus ten eight minus nine is less than or equal to d which is two so it doesn't get incremented to the output so first thing we would want to do is that we have to create a variable to hold the output so create variable to hold the count account and then next what we will need to do is that we're going to loop through each index of array one and inside this we'll have to do another loop inside of it to loop through area two and inside this we uh create a state to keep track if after we loop through what here we'll have to create the state inside here create variable passes we're just going to pass this for now to true and then we loop through array two and this side we compare each element of array 2 to the current element of ray 1. so what we need to do is find the absolute value find absolute value of the difference between element over a2 to array one if the difference does not match the d which is less than or equal to there we go get rid of this there it is format this will have to increment change passes to and after you finish this loop if none of it if passed this is still true we'll have to increment count and then lastly we return count and there we go so what we need to do is create the variable let count equal zero starts off at zero next we loop through a one equals zero i is less than array one dot length i plus if now we create the variable that passes equals true and now we do this the nested loop for that j equals zero j is less than array two dot length j plus and now we create the condition inside this if math.apps this if math.apps this if math.apps value of the current index of array 1 minus the current index value over a2 is less than or equal to d we change it and then after this after you do this we still check if passage is true or not if passes is true we increment count and then at the end of this your return count there's parentheses which must place great so the complexities the time complexity since we have two loops here and but they're different um what we're looping through so be of n times m where each of these is the arrays and then the space complexity it will be since you're in creating a variable of a constant variable so constant space so o over 1. so that is how you solve this problem thank you
Find the Distance Value Between Two Arrays
number-of-ways-to-build-house-of-cards
Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_. The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`. **Example 1:** **Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2 **Output:** 2 **Explanation:** For arr1\[0\]=4 we have: |4-10|=6 > d=2 |4-9|=5 > d=2 |4-1|=3 > d=2 |4-8|=4 > d=2 For arr1\[1\]=5 we have: |5-10|=5 > d=2 |5-9|=4 > d=2 |5-1|=4 > d=2 |5-8|=3 > d=2 For arr1\[2\]=8 we have: **|8-10|=2 <= d=2** **|8-9|=1 <= d=2** |8-1|=7 > d=2 **|8-8|=0 <= d=2** **Example 2:** **Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3 **Output:** 2 **Example 3:** **Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6 **Output:** 1 **Constraints:** * `1 <= arr1.length, arr2.length <= 500` * `-1000 <= arr1[i], arr2[j] <= 1000` * `0 <= d <= 100`
If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles.
Math,Dynamic Programming
Medium
815
435
hello hi everyone welcome back to the channel so this is your randip Singh I'm back with yet another lead code problem so in the previous days I was a little ill that's why I couldn't upload video but from now I will be uploading videos continuously so in this video lecture we'll be solving this problem nonoverlapping intervals which is a medium tag problem so this is one of the problems from the blind 75 list and it is really important problems to practice so we given an interval array which is called intervals for any integer in this intervals array any element in this integer array is a pair start I and end I we have to return the minimum number of intervals that we have to remove to make the rest of the intervals non-overlapping so what does that mean non-overlapping so what does that mean non-overlapping so what does that mean what is the meaning of nonoverlapping intervals so let's understand that so we have intervals like one 2 1 2 then we have intervals like 2 3 then the third interval is 3 4 it's 34 the next interval is 13 so these are the intervals that we are given so what is the meaning of overlapping and non-overlapping intervals so non-overlapping intervals so non-overlapping intervals so basically let's plot these intervals on a number line so we have a interval one then we have two then we have three then we have four so these These are the numbers this is the number line the first interval is this 1 to 2 the second interval is this 2 to 3 the third interval is this 3 to 4 and the final interval is this 1 to 3 so these are the intervals that we have right so what do we have to do here what we have to do think about it we have to remove the intervals which are not overlapping right which are not overlapping we have to return the we can see that we need to remove the minimum number of intervals that we need to remove to make the rest of the intervals non overlapping right so the rest of the intervals must be nonoverlapping so what do we have to do here how can we do that the intervals must be over non overlapping so here we can see that we have 1 2 then we have 2 three then we have 3 4 and finally we have 1 three so we can see that these three intervals 1 2 3 4 they are non overlapping right but there is a one interval which is 13 which is overlapping which we have to remove and that's all the answer is one we have to remove one interval so what do we have to do count the over non-overlapping non-overlapping non-overlapping intervals so let's say that count is CNT this CNT stores the intervals which are non overlapping 1 2 3 4 n are the number of total number of intervals the N minus CNT is going to give me the rest of the intervals right n minus CNT is going to give me the rest of the intervals so we have n as four CNT is what is CNT the CNT is three CNT represents the non- overlapping represents the non- overlapping represents the non- overlapping intervals we have 1 2 3 then we're going to return n minus CNT that is one the answer would be one right so that's all we have to do fine so what we can do now to solve this problem what we have to do is we have to count first we have to count the over nonoverlapping intervals then we will be able to find the nonoverlapping intervals right because we can see that if we count these three intervals we can simply subtract this three from n right and that is going to give me my answer right so how we can do that let's see so to do so what we have to do is we have to here this is basically our screen so here for the second interval to be nonoverlapping with the first interval the starting of the second interval must be greater than or equal to the ending of the previous interval that is the condition which we have to understand same goes for the third interval the starting of the third interval should be greater than or equal to the ending of the previous interval fine same goes with the final interval the starting of the final interval must be greater than or equal to the ending of the previous interval which is not the case here so we means this 22 this 3 three these are 2 3 what are these These are non-overlapping so 2 two 3 and then we non-overlapping so 2 two 3 and then we non-overlapping so 2 two 3 and then we have 14 right so what do we have to do here we have to count these intervals so we'll start from here this is I so let's take I to be the first second interval and this is let's call it previous but before that notice that to count these type of intervals we have to sort them by the ending point why so if we sort the intervals by the ending point only in that case we will be having the intervals in increasing order right so imagine the scenario when we have this second interval before this interval so we have 2 three here now we cannot compare the second interval which is this now with this one why because this interval lies ahead of it there's no meaning in compar comparing it right so that's why to make the comparison easier we have to sort them in the increasing of the increasing order of the ending interval so we'll sort them according to the increasing order of the second integer so we'll have 1 2 we'll have 2 3 4 1 3 like this right fine so that's all we have to do 1 2 3 4 1 3 fine so let's start the I from this one and previous let's keep here before that we're going to sort them so first sort these intervals then keep an eye on the second interval let's call it I and after that let's start comparing compare the first integer of this interval with the second integer of the previous interval if it is greater than equals to that one that means we're good then move to this one I is here three is greater than equals to this three that's good move I to the next interval this I this first one is not greater than equal to this one that means we have a problem here the count is three that means n is four so 4 minus 3 is going to give me one so the answer is one that means I have to remove exactly one interval for to make my intervals non- overlapping to make my intervals non- overlapping to make my intervals non- overlapping right so the answer is one so that's all we have to do so the solution is simple sort the intervals by the second integer right then keep a count and keep a another variable start comparing the intervals with the previous interval right the previous interval is the one where the ending point is less than or equal to the starting point of the current interval right and let's better understand it with one more example so let's take the second example which we have for this problem the second example is 1 2 1 212 right the second example is one two 1 2 one 2 that means what we have here we have 1 2 one two so here this is the first interval let's call it let's say we have C and we have previous here p r e v and then we have I here right so here we can see that one two is this one two the starting they are already sorted by the second integer so the starting point of this integer is greater than equal to the ending point of the previous interval here the starting point of this interval is okay we can see that the starting point of this interval is less than equal to the ending point of this interval that means we have a problem that means we do not have to count here we simply move I to the next interval that mean this is invalid I simply mark it as invalid fine move I here we can see that this starting point of this interval is again not greater than equal to this one mark this again and in invalid so I is here that's all previous is here right so what is Count what does the count stores at this point what is the count stores at this point the count was one initially right so we can see that this count represents the number of valid intervals right the number of nonoverlapping intervals but we can see that we do not have any non-overlapping we do not have any non-overlapping we do not have any non-overlapping interval right so that means this count is one because one interval is always non-overlapping we neither incremented non-overlapping we neither incremented non-overlapping we neither incremented count here nor we incremented count here so the count is still one so that means n is three the total intervals minus the number of nonoverlapping intervals which is one that means two are the number of intervals which are overlapping which is indeed the case if we plot the things on the number line we have one we have two so the first interval is this second interval is this the third interval is this like this fine so the answer is two so let's jump to the code implementation part so here we can see that let's stick n is equals to intervals do size then let's sort them first let's com create a static boo Vector of B return a of one greater than b of one why because we're sorting them by the second integer so that's why we're comparing the second integer right so we're going to sort intervals do size intervals it's not intervals. size intervals. begin intervals Dot and right then after that what we have here is let's take a count which is one let's take I which is let's take a previous variable which is zero let's start from it I equal to 1 I less than n i ++ we can see that if intervals i1 is greater than equal to intervals i0 that means increment the count by one and reinitialize previous to I at the end return n minus count so what does that mean we have the size of the intervals we have to sort them and we also have to pass the comparison operator C MP right and here we have count and then we have to just do these things right intervals i1 greater than equals to intervals i0 count Plus+ previous of I intervals i0 count Plus+ previous of I intervals i0 count Plus+ previous of I and minus count right so in this fashion what we getting is we're simply getting the number of non-overlapping non-overlapping non-overlapping intervals we're simply getting the number of minimum number of intervals that we have to remove to make the rest of the intervals non- overlapping so of the intervals non- overlapping so of the intervals non- overlapping so these many intervals I have to remove for the to make the rest of the intervals to be non-overlapping so let's intervals to be non-overlapping so let's intervals to be non-overlapping so let's run this one okay it's giving me wrong answer I'm doing something wrong here okay this is not i1 this is I have to compare the first one the first integer of the current interval with the second integer of the previous inter right like this so let's run it okay so again giving me a wrong answer let's try to submit it okay that got accepted so that's all I have to do and this was a not so hard problem it was a medium tank problem so stay tuned with me make sure to subscribe to the channel and I will keep coming up with such videos in the future so I will see you soon in my next video till then take care bye-bye
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
1,394
hi welcome to data structure and algorithm series by coding ally i'm your host sue in this video i would like to go through this problem find lucky integer in an array this is the agenda first i will go through the problem statement and thought process behind and for this problem in this video i will use hashmap to solve this problem so let's have a look at the problem statement so i will read it given an array of integers arr a lucky number is an integer that has a frequency in the array equal to its value return the largest lucky integer in the array if there is no lucky in detail return minus one so let's have a look at the example one in here we've got array two we've got two the value is two so this is one of the potential candidate for the lucky number the largest one in here the next elements we check three there is only three is one so three we can cross it out four the frequency is only one so we can cross it out so for this array the only lucky number is two let's have a look at the next one the frequency is one okay so this is the largest current like largest lucky number here okay go to the next array next element 2. so now what of course they are frequencies 2 the number is 2 and it is larger than 1 so currently this is the largest number next we go through the array and we check so three the frequency is three so out of all of these are lucky number but three is the largest so we return three this is the output so let's have a look at example three in this example two but the frequency is three so this is not the lucky number so in here three the frequency is only two so this is no lucky number so in this array there is no lucky number so the output is minus one the constraint is one uh the constraint is the array length is between one and 500 and the value itself is between 1 and 500 inclusive so how can we solve this problem uh in the agenda i have mentioned that i'm going to use the hashmap so i'm going to i will go through that with the example so let's have a look so from here we can see that we need to iterate through this array so as a first step we can do that so we are going to use the hash map so on now we will we you we will need to declare the hashmap so we first we will declare the hashmap so in the hashmap we will iterate through this individual element in this array given array so hashmap is basically like in dictionary like key value pair so key i'm going to write key and value so what i will do is i will iterate through this array and then if there is this value it's not in the hashmap then i will add it so uh so first we have to check if the value is in the hash map if not so if it is not then we need to edit so we need to add the key as the element itself so a r if we iterate through we will be using i or one of the variable so it will be k so in this case it's going to be 2 and the value is going to be frequency is going to be 1. so we are here beginning of this array so next is we will check so in the next iteration we will be here i will be here so i is index is 1 in index 1 we have already added 2 into this array so in this case that we are going to the this element is this key is already present in this hash map so all we have to do is increase the frequency so we will increase the frequencies to two and we can continue in this section so three is going to be 1 4 is going to be 1. so this is the faster in the second step what we have to do we will iterate through this hash map and so what we can do in the step two is iterate through hashmap and what we can so in here we need what we need to check is the key and value the frequency have to be the same so in this case 2 and 2 is the same so this is the largest this and we can see this is the result so let's have a look at the example one two three this example so in this array the hashmap is going to be key value so i'm going to write key value one is one two is two and three is three so if one we iterate through the la so currently this is going to be the result and then when we come here we so what we can see is we need to compare two is greater than one so instead of one we need to update it to two so the next one we will check again three and three they are exactly the same but three is higher than larger than two so we need to update it so the value the correct value that we have to return is three so this is the uh this is the thought process so now we can translate this thought process into the code so let's do it so first what we have to do is we need to return the largest here as the question said largest lucky integer and if there is no large largest lucky integer we need to return minus one so i'm going to initialize this value inch and i'm going to say largest lucky integer maybe i just initialized the largest lucky integer um so maybe largest it's going to be initially -1 largest it's going to be initially -1 largest it's going to be initially -1 and this is the value that i will need to return so i will minimize this okay so now we will do the step one is i need to initialize the hash map in this hash map we are going to store the key value pair so for that one i will english i will use map and both key and value they are the type of integer so here two is integer this frequency is also integer so integer in detail and i will call it map and new hash map so in java we have to i need to find the data type but in javascript and python i don't think that you will need to define the data type so that is map so this is the preliminary step that we have done so next is what we have to do we have to go through iterate through this array so for example if i use this example 1 and then 2 and then 3. so we are at the beginning here so i is here this is i is at index zero so we need to iterate through this array and then we are going to add it into this created newly created map so now i'm going to do that so now for we are going to start from zero and then until the end of this given arr array and what we have to do is we have to check first if we have already added this key into the hashmap so which well what i would do is i'll check here map door contains key so the key is we can um we can get the key uh the key we can get it like this for example and uh let's say k it's stand for key and uh er i so map dot contains key so if that we have already added the map that we are seeing it again so we need to increase the frequency so for that we will need to update it so map.put so in will need to update it so map.put so in will need to update it so map.put so in this is the java syntax put me we are putting that key and value so the first one is the key so for that we will just add k and the value is going to be when the value is going to be the frequency so in this case then we have to do map.get in this case then we have to do map.get in this case then we have to do map.get and what i'm getting key and i need to add one so this syntax in java is saying uh we are map.cat.key so we get the corresponding map.cat.key so we get the corresponding map.cat.key so we get the corresponding frequency so which is going to be if the if we have already added the key then the frequency is going to be one so we are simply incrementing it plus one so this is the case if we have already added this key so otherwise then we can just simply put map don't put and then it will be key value so key is going to be key which we've got in here this line 7 and that value is going to be 1 because this is the newly added value so by the end of this iteration then we have added all the corresponding key and value into the hashmap so by the end of this line 13 we have already added everything so now we can go through the next step is we need to iterate through this hashmap so we will go through this so in here i'm going to write this i'm going to use this so key we are iterating through the key and um so map door i'm going to use uh key set so i'm going to use this method called key set and um so this is basically iterating through all the key so from here what we can what we've got is key and then and i need to compare the value so i need to get both key and value and check for a check whether they're identical so for to get the value i'm going to say value it's going to be door get and then key so now i've got the value so in here i have to check if key and value if they're identical then it could be one of the potential for the largest so we are at the beginning in here this could be the larger so i can say largest which i have declared in here so largest it's going to be i need to in here i need to get the maximum value so one is frequency is one two frequency is two three frequencies three so therefore i need to keep updating this larger so they that's the reason why i'm selecting the uh i'm using the maximum out of these two values so the current a max and the key and largest so this way the largest will be always updated so by the end of this loop then we will get the answer correct answer which is largest in this case is 3. so it could they could be the case that it could be minus one so if the largest if it is greater than minus one then we get we can just simply return the largest otherwise we just we can return minus one so in this so this is the end of this algorithm in terms of time and space complexity time complexity it's going to be o of n is in this line we are going through the every single element in the array and the constraint here given here is 500 so this is the la this could be the largest size so o of n and the space is off and because we use this hash map so let's submit the code yeah this got accepted so uh thank you for watching and um join our fortnightly dsa night where we organize peer-to-peer coding interview organize peer-to-peer coding interview organize peer-to-peer coding interview thank you
Find Lucky Integer in an Array
find-lucky-integer-in-an-array
Given an array of integers `arr`, a **lucky integer** is an integer that has a frequency in the array equal to its value. Return _the largest **lucky integer** in the array_. If there is no **lucky integer** return `-1`. **Example 1:** **Input:** arr = \[2,2,3,4\] **Output:** 2 **Explanation:** The only lucky number in the array is 2 because frequency\[2\] == 2. **Example 2:** **Input:** arr = \[1,2,2,3,3,3\] **Output:** 3 **Explanation:** 1, 2 and 3 are all lucky numbers, return the largest of them. **Example 3:** **Input:** arr = \[2,2,2,3,3\] **Output:** -1 **Explanation:** There are no lucky numbers in the array. **Constraints:** * `1 <= arr.length <= 500` * `1 <= arr[i] <= 500`
null
null
Easy
null
1,189
hello everybody and welcome back to the DCCC channel where in this series we saw for technical interview questions let's pick a question and I was looking at it I think maximum number of balloons sounds interesting kind of like goofy let's see 1189 maximum number of balloons given a string which would be text you want to use the characters of text to form as many instances of the word balloon as possible that's interesting let's see you can use each character at most ones return the maximum number of instances that can be formed that is interesting so I'm thinking about cases where reg X could be something useful and thinking about I guess we'll see I'm not sure how to handle this but I guess we'll see so first example this would be our text and we can see that there are enough characters to form a single word balloon how do you recognize there are enough characters well that's an interesting thing right we could have something that's Wreckers that's kind of like iterative because we know if we don't find any B in the text we know there is no possible chance to get the word balloon if we don't find any so basically we could have a mapping that would be required frequencies and hard we do this I mean theoretically we would have something like the word character B would be at least once that would be a requirement right and what would be for the character a I wonder alright here's me forgetting to turn on my Mac game so let's quickly recap what I did here well how we actually implemented this algorithm in the end was having a couple of interesting things first of all oh wow what was that anyway first of all you have the required frequencies what do they say what they mean like that for each character in the word balloon there is a frequency to that character right so we know that the letter A comes one time in the world balloon the letter L you can find two times and so forth and those are necessary for what happens later the gathered frequencies are all at zero at the beginning and they basically tell us how many times we saw this letter in our text so we get max balloons which say variable will actually look at that variable real quick afterwards I actually put it a bit later on this is always good to kind of like cluster things that are semantically or logically close actually together because like if you have this way on top why do you have it there right like somebody starting to read this would be confused like why are maximum Bulow's infinity and later on they might even not have a good time trying to find it again when they when it's actually used so keep it here where it's actually used let's go over the first part of this algorithm though we have we get basically we loop over each letter in the text if we know if we find that a letter is in one of those letters that we're actually looking for we go into gathered frequencies we find that later we basically update that counter one more right for each of those of letters so in the end you might have something like one two four five one for example and these are all the frequencies of those characters that we found now we get our max balloons they are stuff initialized with infinity and now we go over each of those letters in the gathered frequencies and their frequency and we look at when we get the frequency and we divide it by the required frequency for that letter and we get the floor value just because if we have like five divided by two we get two and a half but we cannot really use two and a half letters in a word right we can only use two that's why we lower it and if this is less than max balloons we can actually update max balloons and this so that happens so for example let's go over we have max balloons at infinity we see B is 1 right 1 divided by 1 we get a maximum of one possible word with this amount of bees that we found right so we updated here because it's less than infinity we have one here now the second time let's even put it I wouldn't but yeah at the second time like for the second letter that we see this is a we take it's gathered frequency we divided by the required frequency so two divided by one it's actually two right so theoretically we could have had use the letter A in balloon words but just because we have two possible cases doesn't mean we can actually use it twice because we only have one occurrence of the letter B so that's why this condition here restricts us in updating the max balloons because 2 is greater than 1 and basically this doesn't ever actually happen so we are left with one in max balloons and we continue on we do the same thing for / - - but - it's a bit we same thing for / - - but - it's a bit we same thing for / - - but - it's a bit we actually have a maximum amount of balloons that's lower than that so we keep it 5/2 two and a half floor it's keep it 5/2 two and a half floor it's keep it 5/2 two and a half floor it's actually two greater than the maximum amount we cannot use it and again one divided by one is one exactly like the maximum amount it's basically whatever and in the end we are actually left with our maximum balloons if we never actually found such a case here for example I don't know of them were 0 I don't even remember I know I just programmed it this way because I was actually had to talk and program at the same time it's a bit hard so in this case if we for any reason for example we yeah let's just say for any reason we are still left with maximum balloons at infinity we can just return 0 because we never actually found any meaningful occurrence and if we yeah if that's not the case we can just return max balloons which would be the last frequency that we actually could back here right and that is all and as you can see the answer got accepted and I was just not recorded with audio but anyway that was it for me I hope you learned something I think this question is not as easy as it seems for my level I think it's a bit more like a medium sized question I did I couldn't really like I had something similar in my mind but it was like I was not really sure why I would do this and not something simpler and it kind of took me some time to actually get myself to do it but anyway let's yeah just try and find a solution by yourself let's see how you do something like this and like I said if you like this content and you're new to the channel because you're subscribing I hope you learned something and if you have a good day see you next time bye
Maximum Number of Balloons
encode-number
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible. You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed. **Example 1:** **Input:** text = "nlaebolko " **Output:** 1 **Example 2:** **Input:** text = "loonbalxballpoon " **Output:** 2 **Example 3:** **Input:** text = "leetcode " **Output:** 0 **Constraints:** * `1 <= text.length <= 104` * `text` consists of lower case English letters only.
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
Math,String,Bit Manipulation
Medium
1070
59
uh hello friends uh welcome to my channel so let's have a look at problem 59 together the sphero matrix two so we saw that there are four such problems in this code so we are going to share the solutions for all these four problems using the rotation matrix method um here let's look at the this problem sphero matrix two first we'll quickly read through the statement of the problem and then we're going to share the idea and analyze the method and then we're going to share the code and do the tests so first let's look at the statement so given a positive integer m so we are required to generate an m by n matrix filled with elements from 1 to n square so in total these are n square numbers so in spiral order so here is the specification for example we can first align the top walk to the right then downwards then to the left then to up and then to the right so finally we get this none so this is example one so example two is sort of trivial so here the constraint is about the size of the matrix or the total numbers the n is less or equal than 20. so it's actually a small number so actually for this problem so if we follow the method in the video for lead code 23 26 so this sort of script forward so here we'll do it in a much quicker fashion so the method we're going to use is the rotation matrix method so here the key is how to detect a direction change and the hot to optic direction of this direction so similarly for the first question so we meet the boundaries or meet something which already set for example when we look at eight we if we continue up so we're going to meet one is already set so we're going to change direction so how to up this direction is exactly what the rotation matrix does so in general the rotation matrix is given by here so it's science theta that's called cosine a just for coming in question a to saying negative cell in a and saying a cosine a so here a is the argue the angle in a cone in angle in contra clockwise fashion so if we want to um rotate the direction in a clockwise fashion so that the degree is negative so here the degree is actually for a is 90 degree but it's negative so if you compute the rotation matrix is nothing but so cosine 90 is zero and um negative sine negative 90 is um is one so and sine negative 90 is negative none and here is zero so that's the rotation matrix so if we have a direction see called dr dc so originally it's you can set it as 0 1 because it works to the right then basically uh let's call this the let's call this vector let's call it vector is uh and dr and dc then we're going to use matrix on multiplication so r times v so we're going to get the optic rule so if you compute what we get is that uh so um this will be this row times this column so this will be dc so the second one will be negative dr so that's the direction optic rule so for details and how we get this rotation matrix and how to compute this matrix and you can refer to this the 23 36 for further details so with that aside we grabbed the idea for the two key questions now we are in a position to write the short code so in this problem we're going to return the matrix so we're going to first set the result as the following so 0 times m for a thumb index in a range m so here we notice that an n is the number range is from 1 to n square so we set it a 0 for the convenience of check in the leader so if the position is not 0 it means it's already set so with that side let's specify rc because zero so this is the start position so dr dc it's um to be 0 1 so this is a starter direction so we are going to use a number called current to mimic the process then this also provides the stop condition so well current is less or equal than n square because we want to set n square numbers then that's this condition holds so we're going to set the result for the current index rc equals current once we reset we're going to increment the current by one and next we're trying to update this r to r plus dr and c to c plus dc however we need to check if we need to change the direction using the rotation matrix so for that let's do the check if r plus dr is less than zero or r plus dr is greater or equal than m so this uh auto bound condition for the row index similarly for column c plus dc is less than zero or c plus dc is greater or equal than n so all in other case so in our case is that the number is already set so in other words the result r plus dr c plus dc is not zero so if this is the case we're going to update the direction so from the previous direction dr dc so we can update to dc negative dr so it's a dr dc is updated to dc negative dr um so with that done what we want to do is that we update the position for traverse so r plus dr c plus and dc so that's about it for this solution so now let's return the results so first i'll do a special case check for example one let's see yeah it passes this example let's do another one let's see r5 it passes this one so now let's do a generic case check it passes all the generic keys so this is a total solution for this problem again we are following the previous two videos using the rotation matrix it's very straightforward in some sense so now here we want to ask a question so the question is can we do the traverse here to the traverse traversal here in a contour uh clock of that fashion right so that's actually um sort of straight forward let's copy this code and then we're going to reset this one as method v1 so here i'm going to write one using a counterclockwise fashion counter clockwise fashion so for this basically the rotation matrix is changed so here we have a is negative 90 so but for counterclockwise a is positive 90. so let me write here for contour clockwise the rotation matrix so r equals so cosine 90 is zero and the positive negative is negative one negative sine a negative saying 90 degrees negative one and sine a is 1 and cosine a is 0 still then we do the matrix multiplication so r times v it equals so this zero when negative one times this column so we get negative dc uh negative dc and also this um this row uh times this column will the r right corresponding to take the first element in this v vector so this is the optic rule for the um for the direction so here basically we do not need to change anything we change this doc direction to be negative one so we move to the left and then the direction object rule is uh is the negative dc dr so it's negative dc and dr then if we do the check so this is the clock counterclockwise traversal so you can test for the case three to make a comparison with the example one here right so um also another thing is that um is this direction actually you can change the direction to be so here i'm changing to the left wall you can change to the downwards so in other words dr is one and the dc is zero it actually does the same thing so here is one two three eight nine four remember this and try it again so we get the same thing right so this is a counter clockwise assertion so the solution to this problem here is clockwise traversal so with that side actually we solved this problem and also we uh we extended to uh do a traversal in a counter-clockwise uh do a traversal in a counter-clockwise uh do a traversal in a counter-clockwise sphero fashion i guess that's all about it thank you very much
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
393
hey everybody this is larry this is me doing a bonus question so let's find one that we haven't done yet and also hopefully isn't premium because i'm too cheap but yeah hit the like button and subscribe and join me on discord let me know uh yeah uh and definitely especially let me know for this part because i would appreciate it because this is a bonus thing um some days i've been a little weak about doing it so if you want to do it with me and you want to keep this up uh then let's do it um yeah okay you have two eight validation so this is going to probably sounds already annoying but what are we doing all right so i guess this is just a real implementation thing let me actually read the problem 393. common individual ways data represent the data representative okay so utf-8 can be one representative okay so utf-8 can be one representative okay so utf-8 can be one to four bytes long subject to final rule for one byte count the first bit is zero okay um and it's uh first bit is zero okay maybe oh yeah okay so here we have 193 so we have this thing is a router for two byte okay so then here okay so this is just a parsing thing so we just have to be really careful but it seems like a lot of downloads which i don't care about seeing but uh yeah also one word of warning is that my neighbor's vacuuming so maybe i should have done this a little later but i drank a little bit too much and maybe i made some poor decisions so hopefully the background noise is not too annoying if so my bad anyway um so yeah so we have an eight bit number right uh and each is each number a bit because int is technically more than one byte which is why it's a little bit awkward um so okay so it's a number representing a by okay fine um then here we have to check uh let's just do it one at a time right so for x in data um we go um well let's actually start with n as you go the length of data and because we have multiple running stuff we should probably check that um so yeah so then we have i is equal to zero so while i is less than n we do okay if that is supply it's current that just said that kern is equal to this and then we go okay if current and uh was it one two um and this is basically this the first bit is going to be one so if this is the case then this is a multi-bit thing then this is a multi-bit thing then this is a multi-bit thing multi-bite thing matter and then else multi-bite thing matter and then else multi-bite thing matter and then else it's only one byte so then we can continue uh maybe we increment and then continue because you know the rest of it will be uh a character right so what is not a radical byte um so now the valve values maybe if we ran out or something but yeah so n by numbers then the first n bits are all ones and n plus one bit is zero okay so it could be as many bytes as necessary the most significant two bits being ten the first n bits are all ones oh it could be one to four bytes long okay so that's i actually i did read it but i guess i forgot it um okay so that means that here we could get the number of bytes get number of bytes in that case right so we maybe we can do something like so yeah maybe we can do something like yeah def count prefix or something like this off the number x and here this is going to be and we will take it out but yeah so we do uh for i in range of four maybe zero one two three four and then else we return four is the number of bytes like it only can go one two three four but if current and one to the eight minus i also wait is this eight or seven because this is a bit so i think this goes to the left seven times so maybe i missed a thing here so this is equal to zero that means that we're done here then we return i right um and that's pretty much it i think so yeah and then we have count prefix of current and then we i count at we increment this by that right um yeah i guess we don't need to continue here but the question is then maybe this goes out of bounds oh no yeah maybe this goes out bound right so if i is greater than or equal i guess if it's equal to n is fine if it's greater than n will return force otherwise we return true is that the only validation that we have i don't know if there's another scenario where this is you know not the case let me just wonderful quick oops i don't know that i understood this property but um okay why is this one wrong so we have this oh i forgot that there's something about n minus one byte so the n five by n minus one bytes with the most okay so it has to be this and then each one of the prefix has to be one zero right so that's um that's this and so yeah okay so maybe i do a check here um first right so maybe offset is equal to this we do i do but before that we want to check that you know for uh j in range of from i to i plus offset is that inclusive um well it should be i plus one anyway because the first one contains all this number of bit stuff and then and then the next um so if offset is 4 then this would be i plus 4 is that right maybe that's right we want to make sure that this number if um if that is of i or sub j so if this is n um if one to the seven and uh or one to the six right so basically here we're doing we're basically adding this with one the dot uh something like that maybe it's off by one no it's okay uh this i think yeah so basically this is the number bit that we're representing and this should give us one zero um as a result so if this is yiko two um yeah it should be good to one's it should just equal to this actually right if this is equal to that's good if it's not then it's returned false i think that's maybe the thing okay let's give it a run this is a very annoying problem this is also the type of problem that i anticipate getting like 20 wrong to be honest but let's see if i misunderstood any parts of it now let's give it a summat i could see myself getting like 20 wrong on this one um oh i did know too uh that's just silly that one i did think about but uh yeah um if j is greater than or equal to n or this stuff will return false that one i should know i was actually thinking about it but then i don't know i just got distracted and forgot or something i don't know sometimes because i was like okay oops two whips i don't know no excuses sometimes it just happens um whoops but i was thinking about it going out but then i forgot it by the time i implemented because i was explaining why i'm doing it and i have just but yeah but i still expect other wrong answers to be honest so let's see yeah okay what's 145 why is that wrong because this is just that type of problem but uh maybe i could print out print bin x for x and data or something like that yeah so we could look at the binary representation of um okay fine convert it to a list of 145 is it um what oh it's i'm just being sloppy it should be this but then this okay um okay so it's one zero is that not right why is that wrong the first bit is a zero oh okay so one zero means that this one byte so is that not right i don't know that this cannot be one that's why um the n plus one the first one bit is zero to n plus one bit is yeah and then followed by n minus one bytes so about by zero of them right this is just so confusing i don't know why this is wrong because i don't know that i maybe i do not understand this particular piece but i return true when the answer should be forced maybe that's why there's so many downwards i don't know that i understand this particular piece but like is the n greater than i think that's the question right is n specifically uh like do we if n is if offset is equal to one do we just return force is that the idea i just don't know because i don't think that i it's not clear if i'm reading this for me but i could be wrong so i'm gonna maybe it is queer and i just misunderstood it let's give it another submit give it get another wrong answer uh yeah okay and then here this is that type of problem not really surprised but putting back into debugging so the first one has four bytes so it's one no is it what n plus one bit problem okay so the third so this looks good and then you have this thing which is also not right uh so what did i return so i return true why that return true because offset should be one right or oh this should be offset minus one because if the offset is one you increment it by one i guess that's true if it's ingrained at two uh it should be only mine maybe i am this should be right or is the idea but why is this wrong oh i think what how did this get did i make that mistake here why is return true inside the loop it should be outside a little bit before obviously okay was that always like that huh that's a very bad mistake actually but okay so it looks good now let's i don't know how that happened huh okay so let's give it a submit ah okay i expect this for this kind of problem just because i think it's just way underspecified so let's see how i misunderstood it this time one of them was a legit mistake to be honest but okay so this one they want it to be false and i put it true why is that so it has five bits maybe that's why uh hmm okay fine i guess i should i don't want to make i just a silly mistake if that's the case but oh no i have four here so it should be just strictly speaking um yeah that's why i didn't do it this way okay but why is this why they put true because it's one zero right oh but i think this is five that's why oh okay um because this is five but the next number isn't zero so okay so this is only four if okay i see wow this is so annoying uh and then we can do something like if it four is not zero so then we would you know do something like two five and then something like that maybe it should be good because we basically make sure that the next number is should be zero which we did not do um this is usually i'm pretty bad at this but this is all sloppy even for me so i feel a little bit uh bad about it but let's see again how i'm gonna get along this time so i guess actually that wasn't that bad per se i didn't make this mistake as a big one and a couple of ones that i probably could have avoided just a lot of typos this wasn't as complicated as i thought um but yeah this is gonna be linear time uh constant space because we don't really do anything so yeah let me know what you think yikes yuck maybe next time i'll do it better but yeah stay good stay healthy take your mental health i'll see y'all later then take care bye
UTF-8 Validation
utf-8-validation
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules: 1. For a **1-byte** character, the first bit is a `0`, followed by its Unicode code. 2. For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`. This is how the UTF-8 encoding would work: Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx `x` denotes a bit in the binary form of a byte that may be either `0` or `1`. **Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data. **Example 1:** **Input:** data = \[197,130,1\] **Output:** true **Explanation:** data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. **Example 2:** **Input:** data = \[235,140,4\] **Output:** false **Explanation:** data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that's correct. But the second continuation byte does not start with 10, so it is invalid. **Constraints:** * `1 <= data.length <= 2 * 104` * `0 <= data[i] <= 255`
All you have to do is follow the rules. For a given integer, obtain its binary representation in the string form and work with the rules given in the problem. An integer can either represent the start of a UTF-8 character, or a part of an existing UTF-8 character. There are two separate rules for these two scenarios in the problem. If an integer is a part of an existing UTF-8 character, simply check the 2 most significant bits of in the binary representation string. They should be 10. If the integer represents the start of a UTF-8 character, then the first few bits would be 1 followed by a 0. The number of initial bits (most significant) bits determines the length of the UTF-8 character. Note: The array can contain multiple valid UTF-8 characters. String manipulation will work fine here. But, it is too slow. Can we instead use bit manipulation to do the validations instead of string manipulations? We can use bit masking to check how many initial bits are set for a given number. We only need to work with the 8 least significant bits as mentioned in the problem. mask = 1 << 7 while mask & num: n_bytes += 1 mask = mask >> 1 Can you use bit-masking to perform the second validation as well i.e. checking if the most significant bit is 1 and the second most significant bit a 0? To check if the most significant bit is a 1 and the second most significant bit is a 0, we can make use of the following two masks. mask1 = 1 << 7 mask2 = 1 << 6 if not (num & mask1 and not (num & mask2)): return False
Array,Bit Manipulation
Medium
null
5
everyone in this video we are going to discuss a very famous problem known as longest palindromic subsequence so they're given a string and we have to identify a subsequence of the string so we have to pick the characters out of the string and the order of characters should remain same and this is known as a subsequence and we have to find a subsequence which is a palindrome so a palindrome is a string which is same each if we read it from in the forward direction or if we read it in the backward direction it remains same so if we have to find of all such sequence is a sequence sub sequences which are palindrome we have to find the longest one so in this example and we have to return its length so in this example the longest palindrome is this and its length is four and hence our answer is four so this is a very famous question and it uses dynamic programming and the state is length of the substring for which we are finding longest increasing subsequence so let's say that indices of these characters are from zero to four so we'll create a DP matrix and so let's create a 2d DP matrix and the entry DP XY where X is from 0 to 4 and y is from 0 to 4 is longest palindromic subsequence for string for substring s x2 let's say sy where SX is a except character of the string and Y is the white actor of the string so it's longest palindromic subsequence so let's see on this example first we'll consider all the sub strings of length 1 so length is 1 so we have 5 sub strings of length 1 and for all the sub strings of length 1 so DP 0 this entry here will consider the substring the Stars have 0 and ends at 0 and we know that if there is only one character the longest palindrome we can make is of length 1 so this one represents the substring which starts at 1 and ends at 1 which is this B this one represents the substring which starts at 3 so this is basically start and this isn't an density which is the same so for all the sub strings of length 1 the answer is 1 but now let's see if substring of length 2 so it starts at 0 and ends at 1 let's say this entry since the SX is s is equal to s y for substring of length two we know that here y is equal to X plus one because we just have length two if this is the case then our answer is two because we have a palindrome of size two else our answer is one so this is else so here for 0 to 1 minus a is 2 for 1 to 2 which is this substring Manson is again 2 for 2 to 3 which is this my answer is 1 because s X is not equal to X Y for 3 to 4 again my answer is 1 now we'll move to length 3 so from 0 to 2 this entry so now so for lengths equal to 1 answer is 1 so length is equal to 2 we decide on this basis on base of this for length greater than 2 so what we see is that if s X is equal to s Y so where X is the first character and Y is the last character so here x is 0 Y is 2 so if these two characters are equal as in this case then our longest palindrome would be of length as calculated by DP X plus 1 comma biomedicine which means which mean let's say this is s X this is s y and this is X plus 1 this is s of Y minus 1 and we have a substring like this and since we are calculating the DP values based on the length and this is a smaller length substring present here so we already know the answer for this and it's stored in DP x plus 1 comma Y minus on and whatever the longest palindromic subsequence we can find for this substring from X plus 1 to y -1 will add to the 2 from X plus 1 to y -1 will add to the 2 from X plus 1 to y -1 will add to the 2 to this if I sexy is equal to sy otherwise if they are not equal then we have two cases so now since these SS x is articles to sy to find the longest increasing subsequence it would be same as either the longest increasing subsequence from so max of DP from x comma y -1 because whatever be the comma y -1 because whatever be the comma y -1 because whatever be the longest subsequence of this case 1 and then this case 2 where DP x plus 1 comma Y so whichever of these two sub strings would have a longer palindromic subsequence would give us our answer because SX and sy both can't be into our answer because if they can only be into our answer false answer for substring SX to s X Y because the only way they can be in to answer for substring SX to SSI is that they are the first and last characters of the palindromic subsequence and then there are few characters out of this and for them to be the first and last character of the palindromic subsequence they have to be same if they are not same then we have to exclude one of the toes and we have two cases so here we exclude sy here we exclude SX and whichever of these two cases give us better answer we take that so in so let's continue filling our table for index 0 to 2 so since SX 0 and I said to these both occurs to be our answer would be 2 plus from 1 to 1 so 1 to 1 is 1 so it would be 3 so in X 1 2 3 so since B is not equal to a for this substring so we'll either exclude a or we execute the first B and whatever the maximum of these that would be our answer for that case so maximum would be so answer would be 2 now sorry so now let's see for K the K is 2 4 so this is our index to the for now since SX is equal to sy answer would be 2 plus the result of this is 1 so answer would be 3 so now let's see for length is good for so from 0 to 3 this is the substring and since B is not equal to a we'll have two cases either we consider this or because it is this and we know that a better answer is this 3 so here we'll get 3 now let's see for case 1 2 4 so this is the subsequent four says b and b is same we'll see what's answer for this and the answer for this is 1 and hence answer would be 2 plus the answer for the substring in between which would be 2 plus 1 2 3 and finally we calculate the answer for the entire substring for the entire strings is from 0 to 4 and since sex is equal to sy our answer would be 2 + equal to sy our answer would be 2 + equal to sy our answer would be 2 + answer for this substring and answer for this is DP 1 comma 3 so DP 1 comma 3 is 2 here so answer would be 2 plus 2 which is 4 and finally we returned DP 0 comma n minus 1 where n is the length of string so there are many questions which of dynamic programming which are filled in the same way as we filled this DP table in a diagonal way so and the state is basically dependent on the length of the subproblem for which we are finding our solution and hence it's good to know this problem of longest palindromic subsequence because we can then solve a larger set of problems which follow the same pattern so now let's see this in code I so now let's see the code for longest palindromic subsequence strong store the size of the string in my variable thing and then I'll initialize the DPLA so I'll start with length 1 so L is equal to 0 or will refer to length 1 so L is basically the gap between x and y and if gap is zero then Lent is basically 1 if L is zero then basically we have the substring of size 1 and answer is 1 for that if two gap between x and y is 1 that means we have a substring of length 2 and in that case if SX is equals to s Y then the answers to all sounds have one else now if again if SX is equals to sy then the answer is 2 plus T P of X plus 1 comma y -1 else the answer is my X of 1 comma y -1 else the answer is my X of 1 comma y -1 else the answer is my X of T P of X plus 1 comma Y or DP of X comma Y minus 1 so I hope this is clear and finally we simply return DP of 0 2 so now let me try and submit this mission has been successful if you like this video please share it with your friends give a thumbs up subscribe stay tuned has more and more good videos are coming soon goodbye see you
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
20
What have we put in the current character? We have put its icon in the current character. Okay, so is the current character equal to this and then I said, is my current character equal to the square bracket? Opening square bracket. Okay, if any of these. If it happens, what did I say? In this type, push me. Current character is fine. Gas. What did I say? If any of these conditions match, then push. If there is no opening among the three, then closing will happen. It is obvious that you If it is opened then it will be closed, if it is closed then what will I say, brother, first of all, what should I do, let's get the top element, now how will we get the guest off element with this tax?
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
93
Hello hello friends welcome to jaipur flight today once again went look absolutely medium glutes core problem 193 restore ip address for the problems is given stringer scanning only it has written all possible valid ip address that can be obtained from this app you can determine your order 24 Comprehensive event with string which contains numbers and need to come up with all the possible IP addresses Solid IP address consists of sacrifice in teachers teach in teachers 2002 563 pasand sangh ltd dot 2009 ghr dr dot 2009 ghr dr dot 2009 ghr dr example within the first example also 1 -8-2016 within the first example also 1 -8-2016 within the first example also 1 -8-2016 Chauhan Diesel Valid IP Address The Chair Samudra Fu Invalid President 0 255 2245 Shyam Vacancy in the Second Statement V0 Leading 08 2011 More Without Correct IP Address You Also Pointed at 6000 The Amazing Shyam and Vehicle Strangeness 12116 Rate of Vway Its Characters Witch System Numeric Value Securities Invalid IP Address 1620 V0 Enter Problem Just To Make This Simple And Understanding Plus It's Good To Know But With Deep Dive Into The Solution Ayush Diary Recommend That You Tried To Solve A Specific And Order Video And Destroy To Think About The solution and they can resume the video in order to see my solution so let's enter the solution more board of the example of IPL pressure generally 32-bit or 64-bit ipv4 is suppressed generally 32-bit or 64-bit ipv4 is suppressed generally 32-bit or 64-bit ipv4 is suppressed New Delhi 86 switch off video oo hua hai so Annie in the Fourth Separated During The Thoughts When Will Have Eat Between So Lets You Have It Own Share Subscribe Av0 Maximum Person All Way Raw Ko Blind Little Bit 2000 25-01-2014 Ko Blind Little Bit 2000 25-01-2014 Ko Blind Little Bit 2000 25-01-2014 Stuart Clark 323 504 225 Tumpa Century Pass l210 1234 of Clans 248 606 And 12838 Them All The Validated To Five 9th December Value Under Max A Anything Very Everything Is All The Best 700 2000 221 Similarly To Three Four 750 Shyamdas Of Macrame Pressure If They Can Get This I Laugh Ruk Bajjo All The Best All Set To Shyam not considering any of the website also not the best 54f i have a single bed anshul bittu life i have something like this one saree is this express lucknow remove 10th one message how too now value is 200 meters hanuman 14 main as a great thing is a row and maxists 250 5 this pickup 4 inch 2025 android phone mera favorite song yaad siddha context of all problems were given with the sum of examples to consider upar se haraya 255 135 so let's take the example nc shift wave 135 ki swarna And possible and scooty 255 dot 215 adhavwali panch and 22552 500 in 18135 please habit to and saturn can stop this input the civil rights law said will put a and 5000 1000 effective they can not make love and not fixed in superintendent balbir singh sudesh should be Forces Must See All Subscribe and Share 1234 Similarly Kerala Coast 1234 Example 000 Lot Option Will Take The Example Builder Solution Shyam And The Top 10 So Allah Remove This Very Nice Have Explained How The IP Address And Arrange Shyam Hotel To This Year's Base Side We Can Decorate To Letter 100 Gram Persistent 100 So Let's Check The Example Of Switch 1010 03 Sudhir And Confirm 20 Lot Of Problems Which Is Generally Ghee Building Mind Is I Will Have To Use For The Loot Subscribe More During 800th Urs 102 What I Can Build Doc 4023 And Like You Think Of 101 And See What The Can Build Way 023 Take That But I Can't Take One 019 Economic Development Indigenous This Is Not Acceptable To Sense Is Values ​​And Attentive 500 War Also Your Sense Is Values ​​And Attentive 500 War Also Your Sense Is Values ​​And Attentive 500 War Also Your Include exit criteria for identification 100 to ki to tuesday to * * * * explorer picture have and see what we can do take the example will * * * * explorer picture have and see what we can do take the example will simplicity this function first child abuse and consume one and the same old is gold with them to see what i Can Do 2010 232 Ki And Wealth Builder Free From Fear Files Will Do It Eventually 512 See Water I Options And One Possibility Of Instead Of 2010 And All My Same Function With 1023 Low And There Is A Third Option Anything Use 101 Should Readily Use 101 But the rest is a false use 101 and process meaning improved man 234 that not coming on to country and this part of the country so double three request Francis of the frequently that we can see your water from her all what we can do you speak and Take 1008 and process that 1023 is a and we can take the 021 and process 2030 to three low so I first condition otherwise they can see her spiritual healing zero phone right shoulder speakers my first criteria of digits of the result leading zero that you have Scene in the example of civil service branch is basically omitted from Anywhere 98100 developed all leading to subscribe to and listen coming breaking don dysfunction in father son who has taken the 0 noida sector one and all the same function with 023 low and ayush 104 length consumer To arrest ladies to three and good in another branch hair remove der webitec 102 so and process re sa a right now i can not take printout from 1023 in cities by letting that condition share what i can do it 108 this process is 23 and high court 102 And Process Reel That If Not Si This Is Validating Visitors Are Ling Jio Phone Chauhan Breaking Dawn Dysfunction Liquid 1 2 And Process Re Sa Hai And High Court Use To Three Layer And All Song With Null 98100 This Is My 1104 Is This Is my level one of recognition Dushmani slide to aisi level-3 is level 430 level Dushmani slide to aisi level-3 is level 430 level Dushmani slide to aisi level-3 is level 430 level 5 main aapke show whatsapp ine zoom the three layer and call with anal vipra mileage 6 10 vikram to exact criteria show vansh is vinod at one is the calling phone a Secondary school is greater than because 25th is that show another prayer for aishwarya is pastries back from this time ip address will welcome something for 3220 chauhan something right now have seen that another condition welcome something for 3220 chauhan something right now have seen that another condition farz udayveer top level is not equal to four cloves Kal swimming is not empty for morning downers that was during the days when nothing more to consumer in every smile Naval force in processing data input but I get after level fort in valid and comes from the exact criteria Bigg Boss Our Format Sister Did Something Like This along with the important thing but they must first level means question wear in noida which will force string twenty-20 is this is not what is string twenty-20 is this is not what is string twenty-20 is this is not what is this is not satisfied but means the part of the trees invalid and not a result of this will also due Problem And See The Solution Will Go To Question A Which Laxmi Ruth Minar Delhi Mode That We Can See That Clearly Show Delhi Start IP Address Will Return List Of Ring On That Mushroom Returning And Friend Which Is Well College Result And Oil Cancer History Output Two That And Which Will Bear MTP List And They Will Slowly Half My Valid Results Into 10 M&amp;M Going To Return The Output 10 M&amp;M Going To Return The Output 10 M&amp;M Going To Return The Output Head And Affair Processing OK What They Are Doing For Restoring The We Will Try To Solve This Will Take You Will Stay In This Will Not Go Into Operation The Way Are Not Going To Subscribe My Channel Thank You How And What Is Doing So Will Result And Subscribe School Loot Output In Minutes Least For This Is My Result And The Fourth Is Policy Level The Thing That Ever Did Not Go Beyond Level For Soil Creative White Method Senior Member Will The Come From Which Is Totally Different Give The Same Name And The Position Of The Spring Well Time Operating The Index Of Spring And Have List Springs Pair Calling But In Mur Daitya Hua Tha Lut Which Will B calling gas output and will need a level of education ministry do subscribe screen will start getting strong with various forms at the booth-level button adhir win gold acid written booth-level button adhir win gold acid written booth-level button adhir win gold acid written in the possibility of getting rid of this is not possible and 251 more results possible Solutions and 110 Dars Will Enter Chinese Style 10530 Slowly E Will Move Will Consume Characters and Increment Performance Paswan Soft Any Given Point of Time in Their Position Is Equal to the Thing Length Soft Opposition Is No Point in the Spring Balance Minute History Consumer and Spring The Interesting husband consume so this is vivek roy responsibility data i can have a result shoaib dab opposition for inter result to length springs handloom it term effect flash light it front then segments in this case is no rate of founder result time looking for rights over two years Will Give You Have Done A Great You My Heart Was Show What Will Do Is Will Add Result Tweet A Torch Light Show Dasha Modification Near Welcome To The Letter And Will Dua The Written Word Pradesh Vidhan Sabha Exit Prayer For The Liberation Not Come Into Processing Part Tubelight Witch Needs to Titillating Mother and How Far Can Lead Characters and Subscribe End Witch Will Start Eating After the Subscribe Indian Idol S 12th Part Plus 2 Flash Light That Bader Can Bear Scenario Where Post Plus Remind to Beyond the Boundaries of the Only For String For Example Let's Loop Remainder Thursday 135 Plus Three You Tell Me How To Find Length is torch light shoulder civil servant man from the length of the spelling of isn't he fearless very-very neatu start the isn't he fearless very-very neatu start the isn't he fearless very-very neatu start the number show I will give name ki hand work to you going to do this brave world you below left blank argus with what They are going to years where going to say name equals to name plus water works for the time getting a goodbye indic I'm that's just look at this point to the code okay so what happens is let's go back to the white board name From this initially blank a my pane our input tax pair operating ns1 03 snacks time bread doing name equals to black name palash one sheet victims one self considering only one next time white sesame free and expect name moot vs oneplus 0 subscribe 000 time name tweet0 0 A little too 101 rate 1400 taken initial exam with land and each time weir wear pending one character from every inch of wear building real is oil wild vishwanath meghwal goodnall subscribe to that dj prince over time you to is f22 airport st of name and Drishti Gift This Is Greater Than 25 That Means I Ca n't For Android Immediately Be Quiet Right To Editor For Watching This Number Say At Every Time Disposal System Right Wear Converting This Using Antidote St Ki And Where Sitting At Its Best To Shift Is Better Than 255 Weird Breaking This Loop Words Dec 06 First Time Name Mood With Three Idiots 3000 Valid Notes Will 303 34 Inside Pores Tree Is A Superstition Which Gave Me 30 This Is Invalid Show Dekh Chakhtar Smackdown Ver He Also Of This Great Dane 255 In That Of This Great Dane 255 In That Of This Great Dane 255 In That Is the time doing I am just breaking the loop is but if it is less what will happen s we are going to call and restore function again choose to function will call with s1s and justice is getting in treatment android software going to part plus one So What Ever Index Is Aimed To Send The Next Rally Tweet Select Complete The Missions We Are Already Subscribe Now To Receive New Updates On That Hand Chord Bhai Award Out How To Taste Nothing But Collector List Which Will Have The Results To Attend For Processing And We Have Already Received A Level Sorry I Am Well Received Levels In Treatment Are Available On So Let Me Explain This Point To You Should I Suggest You All The Flying Jatt Opposed NYV Roadies Line Related Entries Details Office Let So Hai but the question starts the platters paid show initially award function was called restore function was killed with what is the function was killed with a switch s03 ko blind position just passed 1000 want to start from the beginning hui hai there output witch mp list and never Passed Zero Phone Show When They Came Inside The Is Function What They Want To Achieve What Is Equal To Post So Come Is Equal To Pass Is Just After Eating Kill McDermott Menopause Plus Free And Length Shop Austria Follow Sutherland Shyamvir Wing To Go From Eyes 0262 List Entry Now To-Do List Eyes 0262 List Entry Now To-Do List Eyes 0262 List Entry Now To-Do List Entry Selection Process What Will Happen When More Days What Is Not In That One Number De Villiers Name Initial Vs Garrett 0 Which Give Me One And From This Point On The Spot Off Condition In Snore Valley I'm Going To Call Restore Function Again And Every Time I Am Going To Call With 03 That Now I Am Going To Pass That Next And Activists Have Already Used Dard Se Zinc Shampoo * Paswan And Share The Biggest And Zinc Shampoo * Paswan And Share The Biggest And Zinc Shampoo * Paswan And Share The Biggest And Most Incremental Level That Chop's Anti Allergy I Am S --1 That Chop's Anti Allergy I Am S --1 That Chop's Anti Allergy I Am S --1 parameter evening * pass vanasthali bal so before this letter parameter evening * pass vanasthali bal so before this letter parameter evening * pass vanasthali bal so before this letter in acts 10th 200 I am going to send result plus name sur result initially best results plank rights of chief minister to pun robbers and shabbir ali results and intermediate result in collecting and define Am going to subscribe to 200 this decision this to position zero I am going to pass the results playing and my to pos mute hata do to kya is show water par world war ko * to kya is show water par world war ko * to kya is show water par world war ko * paswan mo ki and what they are doing with wind name question name plus Why one that vijaypal singh and veer passing over share result plus name suraj ultis bank software results plan plus .in vijaypal results plan plus .in vijaypal results plan plus .in vijaypal singh and veer 1a how did I come increment wwah increment wwe going to get name vikas name plus add kar 1810 adv1 Show Name Vikram Ward-10 Phone Software Go Into Vikram Ward-10 Phone Software Go Into Vikram Ward-10 Phone Software Go Into Again Call Restore Function With 2030 But This Time They Are Going To Parts December Decisiveness To Boy Doing Some Figures Which Have Consumed Two Characters Year 0n One Has Been Ghanshyam Singh 2 And Over Share Hi We Passing test 102 dot less 101 108 valid options like newsseptember 100MB comes to when it comes to what will get 300 plus abhimaan ji re ji already getting name plus five weir getting from these candidates and bells 101 shape weir going to call restore function in one 03 in This Time Is After 200 Oil Pass Industrial And Have 101 Entry Level Still One Should Live Vijay Free Option Service And Consider All The Validity Of Wave Or 101 Shamseer Welder Trade Preferred Member Same Thing But You Have Done Awal 0101 Same Thing Is Not With Dhaka Dhai A Write And The Information Will After Break Down Into More Options Write Knowledge To Personality In Advance Or Show At Any Point Of Time IF O See The Name Soon Equals 1060 Whatever All Shop Remains Stop This Loop Not Late May Explain This Point To You 108 Any Point Of Time This Name Is Vikram 08 Mirch Wish Ud 9 Bread This The Right Bigg Boss Name Is Itna Mr That Meenu Saeed Ko Intercept And Anything After Repeated Vikram Something With All Leading Sure For Example If I Have Seema Input 0123 So They Started This Rule Name Vikram 0characters Entered And After 10 000 Subscribe 598 Don't Break And Festival Builder Mode Number 90 Subscribe Minutes Later Now It's Towards Chances Of Giving Wrong Input To The Restore Function Subscription Preventive Sector Has Been Done Years Okay so here's basically select me pure solve one thing that will change your attachment and subscribe and daughter and son meghnad a subscribe 1002 result dot nick dot length a minus one special fruitful for morning $15 a minus one special fruitful for morning $15 a minus one special fruitful for morning $15 codeo if input is 2018 new know that you have In passing of inputs 10.to new water and will be possible and two daughters TV remote 6 dancing with the length - 1m 6 dancing with the length - 1m 6 dancing with the length - 1m ki chudati sa check element penniless dream date of birth to k a tuesday sir products level hai apk feed them with rumor Thinker should have previous juice so let's see how this question is yours but if you wish to swell up output was given to me typing what is waste oil in that pit I am Mukesh Vacancy Dutt Howrah Solution has been accepted select all this maintain c universe ok So I Can See The Quick Way Can Improve But Basic Intention To Give It To Solve This Problem Of Truth Behind Will Leave The Pimple Talk To You Really Know What You Feel About It's Due Share And Subscribe This Video Create More Videos Only Problem With Very Simple Solution Thank You For Watching My Video Have A Great Day By Day
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"192.168@1.1 "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
539
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 539 minimum time difference given a list of 24 hour clock time points in our hour minute format return the minimum minutes difference between two any two time points in the list so if we were given the time you know midnight one minute before midnight and midnight we should be returning zero because the minimum difference between these two is zero now this problem isn't particularly difficult the approach that we want to take here is simply to not work with strings but we want to work with you know minutes and we'll use it as the total number of minutes from midnight so we can standardize all of our um you know inputs here so what we want to do is we want to take the hours of a current you know string we want to multiply that by 60 and then add whatever the minutes is right and that way we'll normalize it and we'll do that for every element in our list here then what we want to do is once we've done that so for this value let's just say it's going to be you know um zero and then oh boy what is uh 23 times 60 that's um and then plus 59 okay so it's going to be 1 four three nine and we're looking at zero here now what we wanna do is simply sort this list because we want elements to be next to each other in a sorted order that way two elements that are next to each other will be like uh the distance will be as small as possible between them and what we want to do is check all possible distances between two elements and check whether or not um you know we have a solution there and remember that we need to watch out for one edge case which is that this zero should also be compared to the previous value here so we need to check that and make sure we don't accidentally you know do undo that combination because that is a valid um combination that we need to check so that's the solution here that we want to go with and we're going to keep track of the minimum distance we've seen and simply return that so remember the first thing that we're going to do is convert these strings into the i guess minutes past midnight we're going to sort the array and then we're simply going to take the difference between two consecutive pairs and try to find whatever the minimum difference is so hopefully that makes sense if it doesn't once we go into the code editor and you actually see what we're gonna do it should start making a lot more sense so let's go to the code editor back in the code editor let's write the code remember that we need to change time points from being strings into integers representing the minutes past midnight so we're going to say 4i time in enumerate time points uh time points we're going to say the hours and the minutes is going to be time dot split and we're going to split on the colon and now we're going to say minutes past midnight is going to equal to the integer representation of the hours times 60 plus int of minutes and now what we're going to do is we're going to say time points of i so we're going to overwrite the original array and we're going to say minutes past midnight so this assumes that you can overwrite the original array if not you can just create an empty array and then just append to it i'm just going to overwrite it here it shouldn't really matter you can ask your interviewer if you can do this if not just create a new array it's not a big deal now what we want to do that we've transformed our array to be the integer values we want to sort our time points so we're going to say time points dot sort and what we need to do now is we need to set up our result so we're going to say res and here we need to account for the fact that once we sort uh remember how i said we had to handle the wrap around right we had that case where we had something like zero and then we had fourteen three nine and we need to handle the wrap around of fourteen three nine and one and if we simply did the subtraction we would get you know the wrong value because we would get a minus value and actually we need the difference is actually only one minute between midnight because midnight is technically fourteen four zero but since we're representing it minutes since midnight then we need to consider it as zero since everything is normalized that way so we need to you know return reality at fourteen four zero minus thirteen 14 3 9 to return one when we have you know zero and you know one minute before midnight instead of you know zero minus this in which case we would get the wrong answer so we have to normalize for that as our initial value so we're going to do that in the beginning to make sure that we account for that wrap around that we need to do for the last element in the first element so the way that we're going to do that is we're going to say the total number of minutes in a day plus time points of 0 minus time point so the last element here and this is going to handle us actually taking care of that first and last element and making sure that our value doesn't actually come back negative so that's why we're adding in the 1440 to account for the fact that the time points of minus one is obviously going to be greater than the time points of zero uh so we need to add that 1440 to basically flip it back into the positive um instead of having a negative number which obviously isn't possible so now what we need to do is just look over all the pairwise um times and basically calculate our minimum here so we're going to say 4i in range starting from one because we're going to start at index 1 and then look back we're going to say and then len time points and we're going to say res is going to be the minimum of the current res or time points of i minus time points of oops i minus 1. so we're just looking back to the previous element and calculating the difference and trying to update our result if we can and then at the end all we have to do is return our result and we should have our solution here so let's submit this and we see that it works so what is our time complexity well going through our time points and calculating the minutes past midnight is going to be a big o of n operation right because we have to go through the entirety of time points and make those computations then what's going to happen is we do a sort so this is going to be a you know n log n operation and then what we do next is we go over time points again and then for each element we try to do some computation so we can see that the most dominant operation here is going to be the sort so asymptotically our algorithm is just going to be n log n and for the space complexity well since we didn't actually create uh any new space here to store our result we simply overrid the original array we can think of it as you know constant space because we're just overwriting the original array but you may not be allowed to do this in your interview your interviewer might say okay don't overwrite the original array so we're going to say big o of 1 if not if overriding input otherwise you're going to have to create an array of length time points to basically store these minutes past midnight so we can consider it as big o of n if we're not allowed to override that original input so that's how you solve this problem not really a complicated one i think the only tricky bit here is just handling that edge case where you have to deal with the wrap around between the first element and the last element and making sure that your difference is not negative obviously we're doing time points of i minus one so you know if we tried to do that subtraction then obviously the last element would be bigger than the first one and we get a negative value so that's why we need to add in the 1440 to basically account for that and then flip it back to the positive and give us the actual correct minutes that we need as the proper difference so once you handle this the rest of it's really straightforward you're just looking at all the pairwise times and trying to find the smallest difference possible so that's going to be how you solve this problem if you enjoyed this video please leave a like comment subscribe if there's any videos or topics you'd like me to make please leave them in the comment section below i'll do my best to get back to you and make the videos and in the meantime happy coding and bye
Minimum Time Difference
minimum-time-difference
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Array,Math,String,Sorting
Medium
2266
823
Hello everyone welcome to my channel quote sir with me so today we are going to consume the video number of the playlist of our hash map hashset ok so the lead code number is 823 medium is marked but it will be a very easy question it will be very intuitive it will be built very easily The question is okay but from this question I want to explain some more things to you, I will tell you further. The name of the question is Binary Tree with Factors. Okay. Look, pay attention, it has only unique integers. Where is each integer? Hey. I is strictly greater than one Ok all elements are greater than one Ok We make a binary tree using these integers and each number can be used for any number of times No any number can be used multiple times Each non Leaf nut's value should be equal to the product of the values ​​of its children. values ​​of its children. values ​​of its children. Apart from non-leaf, meaning all the notes that are non-leaf, I don't Apart from non-leaf, meaning all the notes that are non-leaf, I don't Apart from non-leaf, meaning all the notes that are non-leaf, I don't know what should be its value. Let's say this is x and it has two children. Let's say If there is a and b then you know what is happening it is saying x must be equal to a * b ok equal to a * b ok equal to a * b ok that is for example if it is six then it should be 2 3 or 3 2 ok and so on In this way, return the number of binary trees we can make. Now how many binary trees can we make using this, we have to tell you that, the answer can be large, that is why we have been asked to send the module 10 power 9 + 7. asked to send the module 10 power 9 + 7. asked to send the module 10 power 9 + 7. Okay, so let's see first. Let's look at the example and understand how the output is coming. Okay, so look let's understand how the output is like this. One, I am getting to know that this is a tree. This is a tree all by itself. This is the first binary tree. This is also a binary tree. So this alone is making a binary tree. Total how many binary trees have been made. Four binary trees have been made and how many more binary trees can be made according to the Let us see the rules which are mentioned here, firstly I am seeing four, it is fine and after that look, there is a two, right, it has become two and it has become two can be used twice, it is said in the question. You can use a number multiple times. Okay, so I used this number twice. Now pay attention to this tree 2 * 2 Now pay attention to this tree 2 * 2 Now pay attention to this tree 2 * 2 4. Exactly the same thing I said in the question also that the root is the product of its children. Okay, one tree, I see this and I see one, I see this is 10 is n't it, two is used here, five is used here, let's see, 10 is also there is F is also what we have or So one more way is 10 here f here two this is another way ok and you will not be able to get any more way than this, look at the total number of ways, four were found from here, so 6 sa total seven binary trees are possible. Right, you won't be able to make more than this, try more, you will not be able to get any new binary. Okay, so now let's come to the int part of it, let's look at the int, let's try to understand it. Okay, now look carefully and assume that if you accept it then Have you considered this as the root, okay, there can be many batteries, maybe the root of one battery is 4, one, √2, and so on, so first root of one battery is 4, one, √2, and so on, so first root of one battery is 4, one, √2, and so on, so first I have come to four, okay, my index is here now, okay, so you will see that What are the elements which can become the left and right side of four? Okay, so let's see four and what are the elements left besides four? That two can be formed on the left side of four, when will it be able to be formed, when 4 mod 2 e 0 can be formed, only then it can be multiplied and get four, like it is two can definitely be multiplied with something and can get four, okay Look carefully, 4 Moodle Two, if it is zero means definitely 4 must be equal to two, sum 2 multiplied by sum And which number should be there, I just told you, if we assume that I do not know the number here, take it as one, then 2 in What am I saying 4 Batu T E Okay if let's say there was four in I pointer and now I am looking at all the elements one by one to see who can become children of four so let's say I started from Okay so see my root which is are of aa is okay and which is my left child is of There was four, this is I considered two and this is 4 batu. Okay, so a banet is found here. Okay, let's get a b here. Now let's see if there is anything else that can become the left side of four. A. So I got this, okay, J, okay, so can f, which is the left side of the root of four, be formed, four is here, down below, f can never be formed because four module of 5 is equal to 0, okay, first thing. This second thing is that brother, f is a big number, so f should be the root because if you multiply anything by f, then it will be bigger than four. Okay, so anyway, I cannot take this big number because He is bigger than four. Here too, when I came, I saw that he himself is bigger than four, so how can he become children. Okay, so from four, I got this one binary tree and myself, a four, which was a binary tree, this one is fine. One, I got this bin tree and one is this one which I made, okay, now let's see with two, okay, now I am here, my index is here, now I am trying to make two the root, okay. So let me erase it now that I had just found two bin trees, one was itself four ok and what else I had found was the fur root, its left side was two and the right side was also two bin trees were found ok. Now we have come to two, okay, so two itself is a binary tree, right, n is itself a binary tree, so plus and I have got another binary tree, okay, now let's look at the remaining elements which together with two form a binary tree. If we can make a tree, then this is four. I started looking at all the elements. The J pointer is here. This is four. Okay, so yes, it is bigger than two, so from where can it be made on the left side. It cannot come at all. Okay, so we ca n't take the bigger element at all. This is I on its own. Let's remove it. This is J. Okay, this is F itself which is bigger than 2. Isn't this also bigger than 2? So there is no element which is to the left of 2. If side and right side can be formed, then only one can be formed. From two to right, if two is the root, then only one can be formed. Now let's come here, let's check again who can make a bin with F itself. There is one bine, so one more bine is found. Okay, let's see what can come on the left side of F. First, I came to this four. Ok, four can come on the bass left side of F. Let's see. Mad f what is zero otherwise it will not come ok now let's see what is f mad 2 zero with it no it is come what is 5 mad 10 zero is 10 itself greater than f so from where will the left side be formed ok So this is also gone, so only one byte can be made from F, which is itself F, okay, so we have seen this also, now let's come here, okay, I am seeing whether we can make a byte by taking 10, okay? J started from here, what is 10 model zero? No, 10 itself is a bine, that is what I am writing here. Okay, now look at this, which is two, is the left side, which is not, the binet of 10 can become the left side. Why because 10 mdu which is not i.e. 0 is okay but 10 mdu which is not i.e. 0 is okay but 10 mdu which is not i.e. 0 is okay but we also have to see that here the right side x which comes here should be 2 not x 10 okay so that means x = 10/2 5 Do we have If you okay so that means x = 10/2 5 Do we have If you okay so that means x = 10/2 5 Do we have If you look closely, yes we have F, then F, you had to find it. No, if F, then you have to find F, then we will do one thing, we will store it in the map. Let's see 10 Batu, what is F? 25 Okay, now when J comes here, okay, so this time what I am saying is that the left child fi can become what 5 let's see 10 Moodle 5 e 0 so that means it can become there are chances but let's see 5 and Which will be on the right side x 5 * x must be and Which will be on the right side x 5 * x must be and Which will be on the right side x 5 * x must be 10 means Found another Bine tree, see what it is, 10 52, okay, now I have moved ahead, this is here, so I am finished, okay, now mine will move ahead, out of bounds, see the story is over, we have total sense. Binary Tree Okay, it might be looking quite simple, now understand one more important thing from the dry run, here we noticed two things here, first let's assume this is mine, look back, J checked this, you Noticed that the elements which were bigger than I, that is, the elements which were bigger than five, we cannot make them children of this five because they are big elements. Okay, so why don't we sort it. Look, see the advantage of sorting. Okay, what will be the benefit of sorting? It's 2 45 10. It's 2 4 5 10. Okay, look at the benefit of this. Now look, it's here, let's assume it's here, okay, so I don't want to see elements bigger than this. This is because if F is formed as a root then there cannot be an element bigger than this on its left or right side, so I will not see as many elements as on the right of F. Okay, I will only check this and this. What does F mean in the left element? I am saying that if aa is any value of mine, let's assume the value of aa is 3, okay, then whatever is there, it is 0 to aa -1, that is, we will check only till 2, to aa -1, that is, we will check only till 2, to aa -1, that is, we will check only till 2, okay, that means this is f, so I will check it. And checked this, 0 1 2 3 is right and aa will go to every element from the beginning, that means I am saying that i e two is ok, 0 aa le n aa pps is ok but now look at the one which is j I will start from 0, j lesson will go till a, it is always ok, j plus is clear till here, why can we do this because we have sorted it, ok because all the elements after a will be bigger than that, ok, similarly look here also. When I come here, then these 5 and 10 cannot be its left side or its right side, F and 10 cannot be its left side or its right side, why how will it be possible because these people are bigger than him, so I am only I will see to it that I can get the answer only from 2 and I will not get the answer from anyone else, I am clear here, so one thing is understood that we will have to do sorting, okay, the second thing is that we came to know that we have to store it in the map. It will have to be stored in the map, okay for quick access. It is clear till here for quick access, okay, so we have found out two things, we will do sorting and will have to keep the map. Okay, now understand one more very important thing. Now look at this example. Consider this a very important thing, how many ways would there be to make it, I am showing you, first of all, this 2 4 8 is a binary tree in itself, after that look 4 2 This is also a binary tree, after that look 8 24 8 42 This is also a bine. This must be looking simple to you but have you ever thought that this four can also be broken into two twos. Multiplying these two twos will yield 4. Look, we have missed both of those cases. We have not seen the first one. It is in the example, so we also have to see whether the fur that we have chosen on the left side is okay, are there some ways to make it too? Yes, look at the way to make this four, no, it can break in two, so we have this. We will also have to see that the one whom I am considering as the root here is right. Whoever I am considering as the left child, we will also have to see how much number of steps was required to form this left child. The number of steps to form this left child is right and the number of steps. To form this right child, this will also have to be seen. Now see what will happen in this case. Let's assume this is my root, okay, let's assume it had a left child, okay and there were more below, okay, let me write here the left child and Here, let us assume that there were more right child below, okay, now look carefully, let us assume that there were four ways to make this left child, there were four ways and there were three ways to make this right child, okay, that means this right child. The way to create a file could be that there are some nodes here, okay, either it nodes here, there are some nodes here, okay, either it could be, Va is done here, X is done here, it is okay, either it is this, which is the right child, Va is done here. Here it would be x3, here xv ext and so on means due to the value, there are many ways to make it, there are total three ways to make it, the right child is okay, there are total four ways to make this left child, okay, so I write it here like this. Which is the left child, there are four ways, way number one, way number two, way number three, way number four, total there are four ways to create this empty node and similarly, which is the right child, there are three ways to create it, way number one, way number two. That number is three, okay, now pay attention to one thing, how many ways will there be in total, I want to find out, now I have selected the root, okay, now there are four ways to create the left child and right child of the root and three ways. Respectively, it is okay, then how many ways will there be in total, look at this route, pay attention, it is possible that I choose this route, it is okay and here, to make the left side, I will catch it in the number one, as many as the number one. Bane tree will be formed, okay, and to make the right side, I may choose number two, this and this, either, it may be, to make the left side, I may choose number two, but to make the right side, I may choose number two, either. If I choose the number three on the right, then you see, I have so many choices for this one, there are three choices for this one, similarly, there are three choices for this one, and similarly, three for this one. If there are choices then how many choices are there in total, here we have four and here we have three, remember how many lines I drew, 12 4 * 3, total is 12 wedges, it is * 3, total is 12 wedges, it is * 3, total is 12 wedges, it is okay to make that means there are total 12 ways to make this route, how? I can connect this wave with wave weight two and way 3, that means I can form it in so many ways, either I can take wave na and weight here and here wave weight and way can be formed in th way and so on in so many ways. To make the left side and right side of this root, what does it mean that if we know the sum of the elements on the left side, let us assume that it is four or whatever, let's take the value of 16 and make it. How many ways are there and let's say there is four on the right side, how many ways are there to make it, so we can easily figure it out, it's obvious that 16 * 4 will be 64, obvious that 16 * 4 will be 64, obvious that 16 * 4 will be 64, okay, so let's go by the value, we had something like this. 64 16 4 2 8 Okay, it was something like this, so it is an obvious thing, look, there are many ways to make this 16, one will become four and four, okay what is another way, t and 8 will become one, 8 2 It will be done and so on, there can be many ways of making it, so for each of those ways, we will map it in different ways, that is, we are multiplying, so I know what was the main issue, I had to explain to you why multiplication. Many people understand the question, they also understand the code, but they do not understand why multiplication has to be done. Okay, so what does it mean that I will know the count of the left child, whomever I consider to be, how many? There are ways to make it and if I know the count of right side, how many ways there are to make it, then I will multiply both, ok then I will know how many ways there are to make it. It is clear till now, so now let's make it with this understanding. This question is 2 48 Okay, look let's pay attention This is this 4 This is 8 Okay, now I do one thing, I store in the map that which is this which is the binary root then which is and There is a way to create these people because two is a binary tree in itself, four is a binary tree in itself, eight is a binary tree in itself, so there must be one, ok, one by one. Diya, now let me start, first of all we have to do the sorting. Okay, so it is already sorted. Let's start from here. Remember, we were going to go from ro to i, so j = 0. Lesson. Come from here. If you j = 0. Lesson. Come from here. If you j = 0. Lesson. Come from here. If you start J, then J is already there, otherwise it is better to always start A from one, because then J will start from here. Okay, index number zero, index number one, index number two. Let's see if I make four the root. My are of aa is okay till now it is clear so first of all I will see that I will run the loop from j = 0 to j le aa I will see that I will run the loop from j = 0 to j le aa I will see that I will run the loop from j = 0 to j le aa and see if this guy divides 4 md e 0 if yes then the left side can be formed. Okay, but I also have to check whether the element coming on the other side is with me or not. Okay, so 4/2 that is two, we already have it. 4/2 that is two, we already have it. 4/2 that is two, we already have it. Look here in the map. Okay, so I will check that. How many ways are there to make this two? There is only one way. How many ways are there to make this two? Find out from the map. If there is one way, then 1*1 is one way. Okay, so there is only one way to 1*1 is one way. Okay, so there is only one way to 1*1 is one way. Okay, so there is only one way to make 4. Or earlier there was one way, okay and now. Found one more method, 1 new method, T is V, there was one way to make four already and now one more method has been found, T is 1 Psv, it is clear till now, okay great, this thing has been understood, now let's move ahead. Increasing j lesson, if a is not there, now a will move ahead, then again started j from zero, okay now look, pay attention, this is 8, I am trying to consider 8 as the root, I am a Hey off aa, let's look at j first. Yes, it's okay, yes, so can this left side be formed? Let's see, 8 md 2 = 0. see, 8 md 2 = 0. see, 8 md 2 = 0. Yes, okay, great, but 8 ba 2, that's 4. Do we have one that can fit on the right side? Yes, we have four. Look closer and you will get four from the map. Okay, so what did I do, I put four here, so now let's see how many ways were there to make this two. One way will be taken out from the map. Every time there was one way, how many times was there to make this four. How many ways were there to extract it from the map? Remember, there were two ways to make this four. One is that the four itself is a binary tree. Okay, and what was the other way to make it? Four is made here and two below. And if two is ok, then two wedges will be found here. Two is ok with me, so look, 1 * 2, that is two, it ok with me, so look, 1 * 2, that is two, it ok with me, so look, 1 * 2, that is two, it is ok, so look at how many ways to make eight, 1 * 2, that look at how many ways to make eight, 1 * 2, that look at how many ways to make eight, 1 * 2, that is 2, ok. So look here, I have added three, earlier there was one, now I have added two, so it has become three, okay and after this it will end, then after this, j will come here, okay, now look, we will do the same thing again, this time a. The element which is on jet is four, so at was going to be my root but let's see whether four can become its left side or not. 8 module 4 = 0 yes divides not. 8 module 4 = 0 yes divides not. 8 module 4 = 0 yes divides that then four will become the left side but here the element which is Will it come? We have 88/4 two. Yes, no, here we will 88/4 two. Yes, no, here we will 88/4 two. Yes, no, here we will bring two. Okay, now look how many ways are there to make four. There are two ways to make four. I got it from the map. Okay, and here two which How many ways are there to make it, one way is 2 * 1 that is total, I found two ways, it way is 2 * 1 that is total, I found two ways, it way is 2 * 1 that is total, I found two ways, it is ok for this case, if I found two more ways to make 8, then here I will add + 2, okay now J is mine. will add + 2, okay now J is mine. will add + 2, okay now J is mine. J will move ahead, J has also ended, now I will move ahead, i is out of bounds, this is also over, okay, now look, I will get everything from the map, there were so many ways to make this two, one way to make this four. There were so many ways to make two. Do you remember how many binary trees could be made from four? One, four itself was a binary tree and four and here two, so you see two, that is the way to make a binary tree. Okay, so two more wedges are found here, let's see how to make eight, we are getting five binary trees, eight is the root from eight, here is 2, 4 or 8 is the root, here is four, here is one, and this is done by myself alone. Isn't there one, there is only one myself, then look at this one 8 2 The four here, look at this here, this four too could have been broken into two parts, okay and look at this one here, this one also has the four. If we could have broken it into two parts, then how many did we get? Look, we got five. Add it to the total. 5 3 8 That is, the answer to this will be my answer to this example. A total of eight possible binary trees is fine. I hope you have understood well from the dry run and you have noticed that I took every step based on the requirement. The first step I took was sorting and why was it required because look, I could have written this for loop. Now there is no need to see all the elements, now it is okay, then my requirement has been fulfilled, I have to find some element, I have to find one or any of the 8 elements, I have to find the right side or the left side, then how will I be able to find it immediately, ok from the map. After that, I took one or two steps of sorting and mapping on the basis of requirement, it is not that I told you directly to do it, you should feel the need, that is called intuition, okay, after that we understood the most important part. Is it from this example, here we never noticed these two? Okay, so then we understood the reason for this and also understood why multiplying is necessary. Okay, to cover all the cases, so I hope you understand the code. Okay, if you notice this, then how simple will its code be? Think about it, first of all we have to sort, okay, I am writing these story points, then we have to make a map, okay, we have sorted and made the map, after that it is simple. There will be a for loop from i = 0 to i &lt; n and j = 0 to i = 0 to i &lt; n and j = 0 to i = 0 to i &lt; n and j = 0 to j &lt; i ok and why could we do j from 0 to j i j &lt; i ok and why could we do j from 0 to j i j &lt; i ok and why could we do j from 0 to j i because we had sorted it ok but you remember this is from i = 1 only but you remember this is from i = 1 only but you remember this is from i = 1 only Start right because j is starting from 0 okay and after that there is a need to multiply you will know right there is a need to multiply see what is happening in this for loop that I have made hey i the root okay And which is my zth element, I am going to make it on the left side, I am going to make it Hey of J, but when will it become the root, right? Modelo, the left child must be equal to zero, then the left child can be made, but we will have to see. That the right child i.e. root by left child right child i.e. root by left child should be present in my map, only then I will be able to create it, otherwise it will not be able to be created, if you can create it then it is great, then how did I calculate the count, do you remember how many ways there are to create the left child? I will take that from the map and how many ways are there to make the right side, I will take that from the map. Both had to be multiplied. You will remember it well. Okay, so this is how we will make the route. How many ways are there to make the map of the route. Once this much is done, we will keep adding, okay, it is clear till now, so let's code quickly and pay attention to you off A. You must have seen the time complex here, okay and we have taken a map, so off A. We have taken the space as well, it is ok and we have done the sorting, so here also we have put off a different, my starting is ok but this is a big component, so it will be a square time complexity, let us code quickly and tell the same story while coding also. So that you can understand well there also, line by line, you should understand each and every line, then let's code quickly and finish it. So let's code quickly and when you code, you will know one more thing or not. Knowingly or unknowingly, you have actually written the code of DP. Now look carefully and you will know that earlier we used to sort it, after that I had said that we will take one map, so let us take the unordered map. Ok int comma. Let's take long because it is a very big sum, isn't it, the total wage of bytes which we calculate, okay, now look for int aa = calculate, okay, now look for int aa = calculate, okay, now look for int aa = start from one, not from zero because aa will go up to my number, isn't it, lesson aa ps Okay, now look, pay attention, you know that Hey Off Aa, which is i.e. int root, what am I considering now? There is i.e. int root, what am I considering now? There is a way to make it as Hey Off Aa, that itself is clear, isn't it? Now remember, I am starting from the index aa = 1, clear, isn't it? Now remember, I am starting from the index aa = 1, clear, isn't it? Now remember, I am starting from the index aa = 1, so do something about the index aa = 0. There must be so do something about the index aa = 0. There must be a way to make it too. Obviously, now I want to make it also at i = 1. If there now I want to make it also at i = 1. If there now I want to make it also at i = 1. If there is one way then I have done this one, okay now let's see how many more ways to make it Int j = 0 j le aa j Int j = 0 j le aa j Int j = 0 j le aa j pps If you guys have seen the video of my longest increasing sub sequence then exactly bottom up approach. If we look at it, the bottom up approach of the longest E subsequence was like this, it used to come from J = 0 to J till A, then come from J = 0 to J till A, then come from J = 0 to J till A, then if we knew the answer of J, then from it we could find the answer of A also. Okay, let's go left. What is the child of mine? Hey of I am assuming but when will this happen when if look Hey of I which is that is which is my root right? Module left child, if it becomes zero then it can become the left child but at the same time Also, you will remember that I had said how to get the right child, Are of A by left child. Okay, so let's look at the right child, it should also be there in the MP. My right child is in the map, that is, Are of a by left child is equal. Two is not equal to mp.in, which means equal. Two is not equal to mp.in, which means right child is present in our map. If it is so then it is obvious that we have got our answer i.e. we have got our answer i.e. we have got our answer i.e. I will add more in MP off root. Remember which one is MP off left side. What was the way to make MP and what was the way to make MP off right side? What was the right side? Are off a by ac is clear till now as simple as that in the last what we have to do is sum the value of all the maps int. Result e 0 is ok take it long for auto and it in map I am treating it ok remember result e is equal to result plus now see there were two elements in the map what was the first element which is my value and remember the second element What was the method of making number of binary trees in the map? Okay, I have to add only that, it means I have to add the second value, okay, it will be the value in the first, which value is which root and what is it in the second. My number is of one and that's what I have to add, so in the ID second and question it is said that to take the mode, multiply the power of 10 by 9 by 7 and return the result in the last and yes, let's define the mode out here. In int mode e power of 1e is 9 + 7. Let's run it mode e power of 1e is 9 + 7. Let's run it mode e power of 1e is 9 + 7. Let's run it and you must have noticed that we are able to get the answer of each aa from which we are able to get the answer from any previous calculated. You see, actually this is DP, it is hidden. DP is there, if you look at its topics then look, there is sorting here, hash is there, but there is also DP, because see, you have unknowingly used DP of this Aa, if you had to find out the answer which is the root, then you go back and look. You are extracting the answer from J = Jal Aa Actually this is extracting the answer from J = Jal Aa Actually this is extracting the answer from J = Jal Aa Actually this is bottom up and it is similar to LCS Sorry Longest Increasing Sequence is also very similar to that so I will submit and see let's see if we are able to pass all the test cases Indeed yes we have solved this question see if you have any doubt please come in the comment section to help out in the next video thank you
Binary Trees With Factors
split-array-with-same-average
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary trees we can make_. The answer may be too large so return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[2,4\] **Output:** 3 **Explanation:** We can make these trees: `[2], [4], [4, 2, 2]` **Example 2:** **Input:** arr = \[2,4,5,10\] **Output:** 7 **Explanation:** We can make these trees: `[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]`. **Constraints:** * `1 <= arr.length <= 1000` * `2 <= arr[i] <= 109` * All the values of `arr` are **unique**.
null
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2162
1,396
hi guys good morning welcome back to the next video so basically firstly many people have made video on this but for sure if you're watching this my Prime purpose is how to make you think that how to start solving these problems everyone will tell you that okay it's a hash map use this map make this map but how to actually you how you will know that you will make this map how you will think of making this map you will see in just in this problem for sure my purpose is not to make you solve this problem but to actually start to make you think how to actually start with these kind of problems cool um let me quickly jump onto the question it's very easy um so basically I'm just saying that I have underground Railway system and it's keeping the Trap of all the customer travel so basically the customers are traveling from some stations to other stations cool and ovaries we have to calculate the average time uh that takes to travel from one station on another session cool no worries and how we have to do that we have to implement a function called as underground we have to implement a class called as underground systems basically in this we have three functions first is check-in where the customer with the check-in where the customer with the check-in where the customer with the customer ID will check in at the station name at a time T where we have another function called as checkout where the customer with a customer ID called as ID will check out from the station called a social name with the time T cool uh we have phase two functions kind of same a customer ID station in which he checked in at that time he went in and customer ID the station he went out and the time he went out cool average time we have to return something called as double which is actually the average time itself uh in this it just gives you the start station which means the station he went in and the end station the station he went out it is given to you and you have to calculate the average time for all the customers combined for this station pair which means if I say let's say start station is essay star station is as end station is SD now average time for all the customers let's say customer one two three four all sessions between this essay and SD what is the time and then getting the average of that which means the sum of all the times upon the total number of people which is actually Four let's say in this case then that will be the average time cool that is the question is asking us to find cool no worries and it's just a few conditions which is stated that okay all the previous like travel times it's completely like how it is being completed it is just showing at this point then and just a condition that okay at least one customer will be there at least one parallel time will be there on so on and so forth now let's come to the quick example that how actually with the problem is like although we know that what the problem is saying but still just a quick example firstly it will just have this chicken I'll check in check out it is the input which we will have uh when as the check-in it will just say a customer ID check-in it will just say a customer ID check-in it will just say a customer ID a station name and a Time cool um a customer ID a station name and a time uh apologies for this but cool right uh and when I say check out it just says a customer ID this checkout station name and the checkout time right um now my Prime purpose was to find the average time let's see they see now comes the interesting part your main task was to implement this three functions but your ultimate task was to find the average time so start from the average time don't go and think what you will put in this check-in time what you will put in this check-in time what you will put in this check-in time what you will put in this checkout time don't think like that start from the requirement itself it is how you approach an interview also start with the requirement what you want from that requirement come song okay if we need map okay if you need map then what kind of map structure we have to make so start thinking from that end point okay I need to get the average time from what a star session and the end station cool iron I need an average time let's have an example I need an average time from the essay to SD so considering the fact that I have all customers so customer one is having some start buying and some end station start station so I will have the time for this customer for with id1 that time is 30 minus 10 which is 20. between the station SC and SD but I want the average time which means I want that for all the customers I took for the customer one what are the other customers okay I didn't take iot other customers customer two start time end time sorry End Time start time 40 miles 20. now I got the time for all the customers between station a and station which means the star session then session but my purpose was to find the average time not the total time and how we find the average of something we have the total which means 20 plus 20 and we have the count also which is actually two that's how find the average so it is a simple 40 upon 2 that is 20. now you got the requirement what you want so for this string which means why I'm saying string you can take anything you can also take a pair so basically for this Prime thing my Prime English was for this star station and station pair string anything you want this total time upon this count which means you want the numerator as the total time between this station SA and SG between the start session and session what is the total time you have and what is the count of such number of times it is the two things I require right cool now I will just say okay for this start station and station means appear a string anything which means I'll consider this as a journey because it's kind of okay from start to end it's just a journey I need the travel time I said no a total time of travel which means for all the customers what is it and the count of such all the customers so count of all the customers travel time which is the ultimate travel time and also the count of all the customers I need for this particular journey and then ultimately I will just do this travel time upon the time and I'll get my answer do you remember how we approached we went on to find this example then we went on to see okay what are the requirements what are the things we need okay I need a travel time I need the account time but for what for a journey which means a station pair or a station string which means start switching hyphen and session start session comma and session kind of a station like from start to end I need something like that with this I know okay I need to maintain I need to update something like that to get the answer now let's go back to how and what we can do okay if we are at the checkout I know that I need to get the travel times for all the customers because here I have the customer ID which means I can update for One customer at a time so I need to get a travel time for that customer so that I can update this travel time which means add the time for that customer in this travel time right because for travel time it means travel time between the start and the end of that station you need the stock session also but checkout will only give you the end station which is SD which means I also need the information of star station at a point when I am in this checkout function I need the information with me for the start session that's the reason Aryan when I will go in this check-in Aryan when I will go in this check-in Aryan when I will go in this check-in function I will use a hash map which anything such that I can keep a track of that customer start station and the start time that is how from this because I know for at this ID I need to know what is the travel time for this customer but for travel time I also remember okay travel time is nothing but end time minus start time end time and starting profession also in the start time I also need the start station also oh which means for the customer when he started I needed the start session in the start time also that's the reason I have to store for this customer I need it's a start station and also the start time that is the reason how we've built another requirement of finding or fetching or for storing this customer IDs start station and start time cool now what will happen is I will easily get the travel time because ultimately travel time is nothing but a travel time is nothing but our checkout time minus our start time which is which we stored in map which is the check-in map which we have for this the check-in map which we have for this the check-in map which we have for this customer and the T which means although it is thought first and something but I've like make it very clear visualization that okay it is the start time for that particular customer and also Aryan you remembered that we need to update that for a particular Journey which means okay I need to have a end station and also the star station start station so end station is for short I have right now start session I also needed so we also know that we stored it because of that start session I also took the start station I will just get and ultimately My ultimate aim was to get this journey so this journey is nothing but the checkout station you can add anything hyphen comma anything but I added hyphen checkout station hyphen the check-in that is the three things we need to update this particular map because we needed this map to calculate the average time now we went on to this checkout time to find the travel time itself or to find the journey itself when we went on to find the travel time we found okay I also need the time of check-in and also the station of check-in and also the station of check-in and also the station of check-in okay cool then we went on to check-in okay cool then we went on to check-in okay cool then we went on to this check-in station to who stored this check-in station to who stored this check-in station to who stored that information in my map and then I'm using this to find my journey which is the end station Maya star station and station hyphen start session or you can also have a pair incision pair uh and station uh comma start session as a pair or you can also have a string anything you can have then the travel time is simply the checkout time minus the Simple Start time which means the end time is starting and count is simply will be increased by one because simply another customer is in your pocket that's the reason how you will get these three put that in your map and find the answer ultimately it is the prime thing which I want to show you that how to go in the reverse manner simply you will see the code firstly as we computed the check-in for firstly as we computed the check-in for firstly as we computed the check-in for every customer I every customer for every customer I updated my map the start station and the start time for that customer at the checkout I just got okay what is the check-in info for this particular check-in info for this particular check-in info for this particular customer which I am in so that I can use that check-in information for that check-in information for that check-in information for that customer and when I say I need to use the information I need to use that to find the journey which means the start which we see I find my journey as essay iifa hyphen SD so simply starting station hyphen and ending session that's simple to get the journey as a trick now travel time is nothing but how much time it took for that customer to travel between SC and SD so simply we know okay we have completed the start time we also know that we are having this end time so simply n time minus this start time and you will get the answer for travel time and for sure you remember also one thing that you need to add the account which means increase the count by simply one you will simply increase the account by one now as you are get the average time simply get this both which means the travel time and the count and just divide that travel time the count you just get that divided convert that into because it can be in points it can be in like uh value can be float or double so simply get it into double and return the answer simply getting the journey and getting the travel info which means the travel of that person so like it's nothing but this particular pair which means travel time and the count and I using that travel info which means travel time and the travel count to find the ultimate my average time that is how you actually purchase other questions I hope that you guys got it and if yes then do smash the like button although it's easy problem the main purpose of me to actually show you that how to actually approach these kinds of problems cool so you can never go right see you goodbye it was not my end lines I forgot my line itself but yeah cool uh see you love you goodbye take care bye foreign
Design Underground System
count-servers-that-communicate
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the `UndergroundSystem` class: * `void checkIn(int id, string stationName, int t)` * A customer with a card ID equal to `id`, checks in at the station `stationName` at time `t`. * A customer can only be checked into one place at a time. * `void checkOut(int id, string stationName, int t)` * A customer with a card ID equal to `id`, checks out from the station `stationName` at time `t`. * `double getAverageTime(string startStation, string endStation)` * Returns the average time it takes to travel from `startStation` to `endStation`. * The average time is computed from all the previous traveling times from `startStation` to `endStation` that happened **directly**, meaning a check in at `startStation` followed by a check out from `endStation`. * The time it takes to travel from `startStation` to `endStation` **may be different** from the time it takes to travel from `endStation` to `startStation`. * There will be at least one customer that has traveled from `startStation` to `endStation` before `getAverageTime` is called. You may assume all calls to the `checkIn` and `checkOut` methods are consistent. If a customer checks in at time `t1` then checks out at time `t2`, then `t1 < t2`. All events happen in chronological order. **Example 1:** **Input** \[ "UndergroundSystem ", "checkIn ", "checkIn ", "checkIn ", "checkOut ", "checkOut ", "checkOut ", "getAverageTime ", "getAverageTime ", "checkIn ", "getAverageTime ", "checkOut ", "getAverageTime "\] \[\[\],\[45, "Leyton ",3\],\[32, "Paradise ",8\],\[27, "Leyton ",10\],\[45, "Waterloo ",15\],\[27, "Waterloo ",20\],\[32, "Cambridge ",22\],\[ "Paradise ", "Cambridge "\],\[ "Leyton ", "Waterloo "\],\[10, "Leyton ",24\],\[ "Leyton ", "Waterloo "\],\[10, "Waterloo ",38\],\[ "Leyton ", "Waterloo "\]\] **Output** \[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000\] **Explanation** UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45, "Leyton ", 3); undergroundSystem.checkIn(32, "Paradise ", 8); undergroundSystem.checkIn(27, "Leyton ", 10); undergroundSystem.checkOut(45, "Waterloo ", 15); // Customer 45 "Leyton " -> "Waterloo " in 15-3 = 12 undergroundSystem.checkOut(27, "Waterloo ", 20); // Customer 27 "Leyton " -> "Waterloo " in 20-10 = 10 undergroundSystem.checkOut(32, "Cambridge ", 22); // Customer 32 "Paradise " -> "Cambridge " in 22-8 = 14 undergroundSystem.getAverageTime( "Paradise ", "Cambridge "); // return 14.00000. One trip "Paradise " -> "Cambridge ", (14) / 1 = 14 undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 11.00000. Two trips "Leyton " -> "Waterloo ", (10 + 12) / 2 = 11 undergroundSystem.checkIn(10, "Leyton ", 24); undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 11.00000 undergroundSystem.checkOut(10, "Waterloo ", 38); // Customer 10 "Leyton " -> "Waterloo " in 38-24 = 14 undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 12.00000. Three trips "Leyton " -> "Waterloo ", (10 + 12 + 14) / 3 = 12 **Example 2:** **Input** \[ "UndergroundSystem ", "checkIn ", "checkOut ", "getAverageTime ", "checkIn ", "checkOut ", "getAverageTime ", "checkIn ", "checkOut ", "getAverageTime "\] \[\[\],\[10, "Leyton ",3\],\[10, "Paradise ",8\],\[ "Leyton ", "Paradise "\],\[5, "Leyton ",10\],\[5, "Paradise ",16\],\[ "Leyton ", "Paradise "\],\[2, "Leyton ",21\],\[2, "Paradise ",30\],\[ "Leyton ", "Paradise "\]\] **Output** \[null,null,null,5.00000,null,null,5.50000,null,null,6.66667\] **Explanation** UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10, "Leyton ", 3); undergroundSystem.checkOut(10, "Paradise ", 8); // Customer 10 "Leyton " -> "Paradise " in 8-3 = 5 undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 5.00000, (5) / 1 = 5 undergroundSystem.checkIn(5, "Leyton ", 10); undergroundSystem.checkOut(5, "Paradise ", 16); // Customer 5 "Leyton " -> "Paradise " in 16-10 = 6 undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 5.50000, (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2, "Leyton ", 21); undergroundSystem.checkOut(2, "Paradise ", 30); // Customer 2 "Leyton " -> "Paradise " in 30-21 = 9 undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667 **Constraints:** * `1 <= id, t <= 106` * `1 <= stationName.length, startStation.length, endStation.length <= 10` * All strings consist of uppercase and lowercase English letters and digits. * There will be at most `2 * 104` calls **in total** to `checkIn`, `checkOut`, and `getAverageTime`. * Answers within `10-5` of the actual value will be accepted.
Store number of computer in each row and column. Count all servers that are not isolated.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix,Counting
Medium
null
1,191
Hain Saunf Bandh Today Baikunthpur Discuss Important To Medium Problem Number One Question Maximum Set Only Delicious Question Has Been Previously Today Note Of Companies And Make Sure Important Diagnostic Is Gold Medal Tomorrow Morning Starting With Problem Ayush Bhawan Recommend You To That Way Forward Porn Dance of Tamils ​​and vore this system of Tamils ​​and vore this system of Tamils ​​and vore this system mein vitamin A time for different issues for the video and locate vardhak hai statements of being hidden truth but I will be discussing about what we have to the question the approach tweet0 Kauthig ki subah uthakar tubeless question laddu is Casino Tak Question Research Question Is The Giver Solitaire Are Supposed To Two And Three Idiots 123 Checking Officer Android Phone Main Suresh Poddar Dharmendra Want Two Three And K Is Equal To Free Software 12312 Shyam Subscribe To Subscribe Our A Factory Where Is Example Which Som Different Wali Hoon Sir I wake up in the morning Small Example Apeejay Institute - 2nd T20 - - 200 Abs Hai How To Do Subscribe Definitely Lab Technician Travel Tips Ko No Question of Translations For Yes We Can Do Subscribe To Yeh Sach Hai MP3 Chuke Hain Yeh Hoon Points Pacific Vitamin C The Question Talk Apps Do You Do Subscribe To Connect With Bhi Lance 0 And Gremio Zero Size Basic Maths Number 90 And Greater Noida Divided Into Two Subscribe And Sunao All Case Will Be Of This Defect In Sabke Switch Off Video Me Zee TV this offers the technical twisted universe in thing in VLC for this question was reduced to t&amp;c main t&amp;c main t&amp;c main suraj siddh force ke iss video me jham kuch der sham hu is president equal to zero torch light sudesh lipstick diya are one minus two entry li ki pra notice Given Shambhu Circular Two So Let's Celebs' Times Ko Celebs' Times Ko Celebs' Times Ko Tight Sholay's Mark This Show Is Not Related To Any One 8 - Two Three Live 123 Live Victory And Some Total K 8 - Two Three Live 123 Live Victory And Some Total K 8 - Two Three Live 123 Live Victory And Some Total K - Two Times - Two Times - Two Times Are Another This Vansh Stuart Broad Shoulders Return One Minus Two Three torch light note cancer about this point one incident at this time Assam at this time max is bay reported cases this two sleeping 0 1 0 That Edison Always True Improve Means Till This Enter Value Now Also This Point That Always Positive A To Switch Off Means Taking Place Value K Note Reduce O My Total Song Is And Nazar Watch It Can Only Increase That I Total sir A for equal to zero this will be true and all the cases will be too that not considering this water will affect your life but spot that answers part plus X n that today one seats 128 and these are most difficult 2013 combined Calculating that scene is only for you and two repetitions a price I safe button to in the 6th that boat electric also ginger juice and mirus we call this bell a super any number 10 multiple regression 0x * will always be glad you * will always be glad you * will always be glad you too Not improved second test match suit with me attachment previous person others this - times the violence during this chapter in a improve positive this time it doesn't want to be caught in a negative effect each other included in assam in the field my answer is not Correct I Safe But Example To Understand This One And Happiness - Three - Axiom Ten Snake Is And Happiness - Three - Axiom Ten Snake Is And Happiness - Three - Axiom Ten Snake Is Minus One So Let's Back To Vibrations Of Its Most Attractive One Two Minus One Want To See Torch Light Sweater All Gift One Presentation 800 60 Format Last Mist In financier S2 Vegeta from another account Taking all the other address Not used oil lage The only for oo ka Andaz state But I didn't go into Intruded into ganges mein Safal dugad Any problem understanding That lasts for amaze Please pay attention 1600 While doing are and Defeated 210 Not Leaving Certificate Us After Twelve Thirteen Maximum Evening In The Morning Rolly Ca A Possible Alarm Set Suresh Kushwaha Friend And Skimming Battery From Witch Sentences Are 2200 Celebs Caught Last Three Seconds This Will Be Difficult Other Side Until After 20th Tere Sam Sabre Overhead Diya Hai And possibly in short notice I will be early in the morning inter medical test like these norms and skimming these cases me sacrifice global you and see how to subscribe sudhir water element subscribe scripted other in this part of this element 400 to turn on this combined thing in this Original And This Has Posted 100 And Also In To-Do Subscribe Positive-Positive In To-Do Subscribe Positive-Positive In To-Do Subscribe Positive-Positive Subscribe Indian Politics S Well Tell Me The Information About The Phone Main Suresh Pichlaggu States Repeated K - Suresh Pichlaggu States Repeated K - Suresh Pichlaggu States Repeated K - Two Times And Isko Success Suno Labs K Juice One By One And Points Perusahaan tak ho sake what will lead you to tiles pe like this a suite nutritious like this cream - suite nutritious like this cream - suite nutritious like this cream - two way reduce and do service tax to maximum reduced from this acid this point and will be the chief guest of the Suryavanshis is to is tented against Candidate Answers from back few seconds vote vilayadu is dad a like this plus bataye start from her in the middle of the grocer and middle thank you bol diya judge a guy pani ke is special shooting bhi address in last person do I will definitely take This Post on Violence and Masse Director C 99 This Reduce Like This Content From Middle Of Twelve Subscribe To Hai Aadhi Most Widely Improve Confuse All Three Cases And Thanks For Answers For 100 Greater Noida And You Will Get 300 Grams Repeat You Should We Do Subscribe to my channel fluid subscribe one two three two one two three subscribe to flash lights pregnancy care to picas hai 100 words with me show i plus hai 108 plus and use this and acts and restoring prohibition in this vansha plus and misses and Subscribe The Effigy 2002 Taste Simply Apna A Code As Per Tej Without Number 20 And Finally Bigg Boss Case 204 Ki And Who Voted For This Christmas Greetings Zero Rate Whose In Sex Earth And Calculate Indian Values ​​For Earth And Calculate Indian Values ​​For Earth And Calculate Indian Values ​​For Second To Repetitions Now Him Emphasis * K Second To Repetitions Now Him Emphasis * K Second To Repetitions Now Him Emphasis * K I Superintendent of Police Vipin subscribed to this first original that and now have taken its models and multispecialty with which came into any takers models in its to the given in the question which was tempted 2978 som distant to par ninth class 7 that Andhra and finally Amazing specific commands for this and you celebrate it and prosperity will be provided in this extinct Hindi approach for school students I ex-muslim 1008 need not included in the ex-muslim 1008 need not included in the ex-muslim 1008 need not included in the complaints of bill sexual code for knowledge for submitting list subscribe so let's get the soldiers who first pass And Suzanne Test Mission Point Se Left Side Reaction Worth Subscribe To Tubelight
K-Concatenation Maximum Sum
synonymous-sentences
Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times. For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`. As the answer can be very large, return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,2\], k = 3 **Output:** 9 **Example 2:** **Input:** arr = \[1,-2,1\], k = 5 **Output:** 2 **Example 3:** **Input:** arr = \[-1,-2\], k = 7 **Output:** 0 **Constraints:** * `1 <= arr.length <= 105` * `1 <= k <= 105` * `-104 <= arr[i] <= 104`
Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements.
Array,Hash Table,String,Backtracking,Union Find
Medium
null
6
hello and welcome to python programming practice in this episode we are going to be covering elite code number six called zigzag conversion this is classified as a medium problem so it might take some doing to get through it so i'll start by reading the problem description here the string pay pal is hiring is written in a zigzag pattern on a given number of rows like this you may want to display this pattern in a fixed font for better legibility and it's showing us the string but it's in this weird configuration where it goes pay pal is hiring up and down across several rows in kind of a zigzag configuration and then it says we're supposed to and then read line by line so instead of doing the zigzag we're reading it this way and that's what this output string is like so basically write the code that will take a string and make this conversion given a number of rows so we're given some string i guess that's in a zigzag configuration and we have to output the string that would be made by taking each row of that zigzag configuration and then concatenating them together let's look at some of the examples here so example one we're given that same string we just looked at with the number of rows three and then the output is each of the rows in order instead of in the zigzag configuration and now we're given another example with num rows 4 with the same string it looks like and that's just breaking it out over longer zigzags so now it goes up to four rows and that alters how many rows across there are so that's going to end up changing the final output string too and the third example is just an input of a only with one row and in that case we just output a they could have actually made this even longer and you just output the input because if it's only run one row there's no zigzags happening and in that case we could just output the input string um and the constraints here our input is going to be between length 1 and 1000 the string will only consist of english letters lowercase and uppercase along with potentially commas and periods and the number of rows in the zigzag pattern will also be between 1 and 1000 so i suppose it's possible we could be past something that's like a column where every single letter is in its own row so to start tackling this problem i've pulled up a white board with some letters on it here in a zigzag pattern a b c d e f g etc and we'll use this to think about how we can approach this problem so if we're passed in a string like this with three rows as the target we're going to have to figure out how we can basically make this kind of construction and loop through the string to come up with this result where we're going down to three rows then we go back up like this down to three rows go back up like this etc until the end of the string and then we have to somehow keep track of the fact that all of these positions are associated with what's going to be the beginning of the string or the first row and then all of these positions are going to be in the middle of the string or the second part of it and then all of these letters end up being the kind of third row position and those are going to be at the end and then the string that we have to output for this is everything in row one and then concatenate everything in two and then concatenate everything in three so basically what we're going to have to do here is we're gonna somehow have to keep track of everything in each of the rows that has to be created so we might want to make something like a dictionary that's going to have a different substring entry for each one of these things and then we're going to have to figure out how to loop through the string and keep track of what row we're currently in and then as we go along we can add to the substrings so let's look at an example of what this might look like for this problem we could say initialize an empty dictionary with an entry for row one row two and row three so here's our empty dictionary and then we can loop through our string and say okay we're looking at a what which row is a in and then we'd say okay a is in row one and then somehow we'd have to know the next letter b should be in row two and then we'll say okay b is added to row two then we'll go to c and we'd have to keep track of c is supposed to be in row three then we go up to d that should be in row two and then we'll just keep adding on to these as we go along and then we'll end up with all the substrings we need and we can just concatenate them together in order so the difficult part will probably be figuring out how to loop through the string and know which row each letter is in at the time that we see it and how we can do that is probably just having some counter that keeps track of what the current row is and then every letter we look at we'll increment the row by one and then when we get to the last row we'll just start decreasing it by one so we'll say we'll start at one two three oh three is the maximum length so we should start decreasing now two one is the beginning now we should start increasing two three etc so we'll have to have some counter for the row that's increasing and decreasing based on whether we're zigzagging in this direction or this direction so we'll probably have to have some indicator that's telling us are we currently moving in the down direction or up direction but that should be enough in terms of the intuition to start coding up a solution to this problem so i've pulled over to the code editor now so we can start writing up our solution you can see we're past a function called convert and we're given the input string and also an integer that specifies the number of rows now to start off with we should probably handle the case where we're past just a single row that we need to return if the number of rows is one then we don't have to do any zigzagging and we can just return what we were given so if num rows is actually equal to one we basically don't have to do anything and we'll just return the input string now if that's not the case we actually have to handle the problem so we'll start by initializing the map that will keep track of what's in each row that we will put together at the end so and we're going to need a row for each row in the row length so that was given to us by num rows so for row in range we'll say one two num rows plus one so i'm going from range one to num rows plus one just so that we have something that aligns with the example so instead of being zero index this is going to be indexed from one and now we can initialize the variables we need to keep track of the logic within our loop so we needed to keep track of what the current row is so we'll say we'll start at row one because the first letter we're going to look at regardless of what num rows is that's going to be row one and we'll figure out later how deep it goes in the loop but we're going to initialize that to one and we also have to keep track of whether we're currently moving up or down in the zigzag pattern because that will tell us whether we should be incrementing the row by one or decrementing the row by one so to start off with we'll say up equals true and now all we have to do is loop through the input string and then add to the appropriate row in our row map whatever the current letter is based on what row we're currently in so for letter in s we're going to add to our row map the current row so it starts with row one but that will be changing plus equals our letter so basically on the first iteration we're at row one so we're breaking off the first letter and we're storing that in row one in the row map and then for the next iteration the loop maybe we're storing something in row two row three row four eventually we'll go back and start storing things in reverse order so now we basically have to figure out how we are going to increment or decrement the row counter based on whether we're moving up or down so first we'll handle the moving up case or moving to larger numbers i should say so if we're starting at one or if we're currently at one we should be increasing the row number if we're ever in the first row the next value is always going to be a higher row because the case where we had only one row we already handled that by returning right away so if the row is equal to one and the other case where we're moving up is if we're already moving up and we haven't gotten to the end of the zigzag yet so the current row in that case is less than num rows so or the current row is less than num rows and up so basically we're saying we're moving up and we're still less than num rows that also means we are in the moving up state so in that case we want to increase the row by one and up is going to be equal to true and the reason we have to set up equal to true here is in the case where we just came back down to the first row the up is probably going to be set to false at that point so we need to set it back to up to say okay we're moving back up again now so now all we have to do is handle the case where we're not moving up we handled all the logic behind any time we need to move up so that means otherwise we're just moving down so else we're going to say row is decreasing minus equals one and up for now is false so basically that's going to say anytime we're not supposed to be moving up we're moving down and in that case up should be false and this should take care of the kind of zigzag logic so at the end of this for loop our dictionary will have stored in each row all of the letters that belong in that row so now all we have to do is basically construct the converted output string from all of those sub strings that are stored in the dictionary so we can do that by looping through the rows one by one for the number of rows there are and for each one of those just extract those saved substrings so we'll say converted equals empty string and this will be what we're going to return but we're just going to build it up from those substring results that we have stored so far so now we'll say for row in range one num rows plus one so we're looping through all of the rows that we had stored in row map now there's actually something in there we'll say converted plus equals row map of that row so basically all this is doing is going through each row that we know we have extracting the substring that we had saved as being for that row and then concatenating it or adding it onto this final converted string so this should be the final string we need to return for this so let's say return converted and i'm going to go ahead and click submit on this one and if we didn't make any coding errors it should hopefully be a working solution so let's go ahead and pull over to see our result here so you can see that the submission did pass we got a run time of 52 milliseconds which was faster than about 88 percent of other python 3 submissions so that seemed like a reasonably efficient solution to this problem if you found this video useful you can drop a like or hit subscribe thanks for watching and keep coding
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
40
hey everyone today we are going to talk with a little question in combination sum two so you are given a collection of candidate numbers candidates and a target number Target and find all unique combinations in candidates where the candidate numbers sum to Target so each number in candidates may only be used once in the combination note that solution set must not continue duplicate combinations so let's see the example so you are given 10 1 2 7 6 1 5 and the target is eight so we can create the um like a candidate number some to Target is like a one six one two five and one seven two six so that's why we can we should return these four array yeah very simple question so let me explain how to solve this question before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get a call from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example 10127615 and the target is eight I think there is a better way to solve this question um but the easiest way to solve this question is like a first of all um I sorted input array so we get like a 1 2 5 6 7 10. and then um we basically we iterate through all numbers one by one and trying to find a unique combination so first of all uh we start from index 0 so we fix I here and then try to find the unique combination in the list of numbers here so in that case uh we can choose like so we choose one and then in the rest of range we can choose like a we include this one or not include this one so and we can again include these two or not include these two so we can use the same thing for all numbers and then in the end we can find a random answer like a one two five and the total eight yeah so that is the one answer um and then uh at some point we finish all like a possible combination um when I equals zero and the next we move next so I is now index one and uh try to find the unique combination at the rest of like a number uh from the nest of number and then in that case we fix one here so but uh there is a possibility that we can we make a same combination like a one two five but we already have one to five so that's why we sold the numbers so actually I wrote down the important two con conditions in the loop so one is a if current number equal the previous number in that case we skip that Loop because uh there's a possibility that we make a same combinations so that's why we Skip and there actually we have another important condition so if connect number is greater than Target we stop iteration so let's say so this is 9 this is 10 this is 11. and uh if we are like a here index I is now zero one two C4 and then pointing nine in that case um so 9 is a greater than eight so in the case we have to stop because we sort it input DeLay So list of numbers are definitely greater than eight so we don't have to iterate through all numbers so that's why we stop um the looping yeah so that is a important to conditions so I think uh it's easy to understand the solution if you see the real program so that's why uh let me jump into the code okay so let's go first of all um I sorted the candidates dot salt and then um initialize the result variable with empty list and we try to create like a depth first search so text first search and then um passing the target number and the start point and the current combination empty and then the term results variable so let's create a text for such So Def that's for such and the Target and the start point and the combination so before I iterate through the numbers so let's check the current Target so if Target is less than zero in the case oops less than zero in the case just return and then if Target equals zero in the case we find the combination so appends the current combination to result variable and uh com B and then be done so that is a base case and then if not to the case we start the iteration for I in range and every time we start from like a start point and the length of candidate and then as I explained earlier there is a two important condition so if I is greater than start point and candidates so current number equal candidates so current number equal previous number in the case um we should skip this iteration so continue and one more thing if candidates so current number is greater than Target in the case we don't have to delete the rest of number so just break if not the case um we call the depth divs first search again so divs for such and uh passing like a Target minus candidates so Target minus current number and then um we have to pass the next number so start point should be current index plus one and then current combination is should be combination Plus and candidates so current number I yeah so that's easy actually that's it so let me submit it yeah looks good and very efficient so time complexity of this solution should be a little bit complicated um n plus K multiply due to the power of n so n log n is from a sorting this one and the K is the number of valid combinations and so we use the depth first search and in this case last case time complexity or is like 2 to the power of n because uh in for each number we have two Choice like uh include the current number or not include the current number and we have n um any ranks of a num combination candidates so in the worst case we have to choose like a include not to include for all numbers so that's why worst case is 2 to the power of n so that's why uh time complexity is like this and the space complexity is um order of K multiply n so space complexity of this first generalism is o n so N is a length of input array and this is because this was algorithm store the current combination and the remaining candidates on the call stack which can grow to the depths of n in the worst case and the K is a number of valid combination and the um second of N is a length of each combination so that's why we take a regular larger complexity space complexity so that's why uh overall complexity type space complexity should be order of K multiply n yeah and this is a little bit um complicated so yeah that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment
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
949
in this problem we are given uh four digits uh single digits from zero to nine so like this let's say three two one five so we will be always given four digits and we have to form time and time should be in this format h m so you see four digits are being used and you can use these four digits in any of these four positions either for h m and you don't have to duplicate that so you cannot use three multiple times and ignore one of that so you have to use each of these exactly once and then for a time and then there will be multiple possibilities here you can have any of the four digits here you can have any of the remaining three digits so four permutation possibilities are there so 4 cross 3 cross 2 cross 1 that is 24 so we have to return the largest time so by largest we have to see that time starts from zero point zero or colon zero this is the smallest time and the largest time is two three five nine so all time will be between this and this including this so we have to form the maximum possible time for example we can form here one two three five this is one time then we can form uh 2 3 using 2 3 and then 5 1. so you see that clearly this is the larger than this one and in fact for this problem this should be the largest one but there may be scenarios where you cannot form a valid time for example you need two digits to form the hour clock and that should be smaller than 24 let's say you have three now no time is possible it will be 33 hours 33 minutes which is invalid so in that case we will return empty string otherwise if it's valid we will return the largest time so let's see how we can do that so we will try for all the possibilities so we have four places to fill h m so uh in fact if you fill three places you automatically know what should be the fourth one whichever digit is left so we can have uh some loop i equal to 0 to 3 including this so this index is 0 1 2 3 j equal to 0 to 3 k equal to 0 to 3 and the fourth one we automatically know so their sum is three two five plus one six so we will see which index we have picked the first one which index we have picked the second one third one and subtract from six so here we will have let us call this a i the string representation of this and concatenate with this one aj so this is the hour hh and then mm will be a k and a 6 minus i minus j minus k so here this operation let's say denotes concatenation we are concatenating it into one string and we have to check that this should not be equal so when i is equal to j or j equal to k or k equal to i then we will not continue we will skip those values so and then what we will do we will have a global answer or result and whenever we find a better value we update it so first we will check if this h should lie it should be less than 24 if it's more than 24 then we will not update it so if h is less than 24 similarly minutes should be less than 60. and hh mm the string this one is less is more than result so we found a better solution better valid time then we update the result and finally we will return the result so what is the time complexity here this will run for 4 times so o 64 this is the time complexity so you can assume it to be constant time and space is same as the result variable we are having a few more string so its length can be at max two characters here also two characters so four characters and one for result so its also constant time so let's write the code for this would be pretty simple so what will be the time here h m so let's keep a separate variable and the answer matches so let's submit and the solution is accepted so let's do this same thing in java and python this and the java solution is also accepted finally we will do it in python 3. so and the python solution is also accepted
Largest Time for Given Digits
cat-and-mouse
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
1727
987
hey everybody this is Larry this is me doing cube four of day four of the legal day challenge hit the like button hit the Subscribe button join my Discord let me know what you think about this poem this day before hope you liked the intro uh it took me a long hike to kind of get there but uh but yeah it was fun uh and also I just want to should point out the uh the virtual uh contest thing uh what was my YouTube yeah I think that's okay um yeah just because you know uh one thing I would also always say is celebrate your victories and you know and this one I did pretty okay so I you know and Long Time watches of my and I've been struggling lately so uh we'll see if that comes back when I get back to New York I'll uh you know do them live okay so let's take a look to Ace Farm is vertical order traversal of binary tree so given a root of anything where to go Ultra what does that mean okay so you have to do multiple notes in the same one same column okay does that mean okay it's way awkward but uh okay um how do I want to do it I mean I think I'm just thinking about right now because there are multiple ways you can do it um the key thing is just denoting you know uh these weirdness um yeah that's good let's give it a try let's see how that goes right so basically we have a recursion we go okay um it's quick for the kernel Rubicon X Rubicon Y and then we can just do look up as you go to collections Dot default take of a list this way we have a list for each lookup maybe it's not necessary I don't know but uh actually in this case we'll just have to show the list because why not okay let's actually not do that let's not communicate things okay and then now we just have basically look up uh no type value or something like that and then well check if the node is not none return uh yeah uh wait if it's none return whoops it's a little early today um okay and then now I'm gonna Traverse know that left we was it so row plus one y column minus one and then we do the same for the note that right and then okay so then now look up should have everything and then what are we supposed to look at of the column could maybe have formatted this in a better way but I'm lazy so it's fine so yeah four key in lookup that keys this is probably not the cannot go away of doing it I would actually just write it slightly differently but yeah I'm actually trying to go hiking so I'm a little bit lazy today sorry friends for people uh mostly because this thing I think we could have um look up I had done like in a list of lists or something like this so that we don't so we could save on this sorting but for now let's take a look um and then we have sort by column so okay so columns is you go to also um another thingy so then now uh the key will have X Y anyway so then now we have Columns of why yeah we sorted by X so we're good or first anyway so then here we are pen um X no we append this um and actually we want to extend in that again because this is a list where so then now for Y in columns type keys and then we sorted this as well what do you think unefficient inefficient um and then we just have answer and then the pen y and this is already a list so it should be okay and okay let's see if that works this is my first you know uh go at it how come we have the same input twice oh six and five was swapped okay well I guess it would be nice to return stuff but hmm is this not right run away extend okay let's take a look at what I'm doing wrong after the lookup as well oh it's because we eat oops yeah okay it's still warm but at least it's uh slightly better why am I wrong okay let's click on the Tiff thing oh because I sorted by wait oh I don't sort it oh I forgot to sort it that's why um okay that's why I meant to sort it but then I forgot yeah okay let's give a submit hopefully it's not too slow I'm a little bit lazy today yes okay 887 day streak yay uh and also for those who've been following the drama in the last few days uh if you don't see this pop up please remind me I'll give you a map pops a shout out or something but uh but yeah let's see what I do last time hmm yeah I guess like last time I did it this smart way I guess I still do it whatever bit um yeah let me know what you think uh just a lot of sorting so it's probably end again in the worst case so I wasn't worried about it um because the summation of order sword is going to be linear anyway oh sorry it's going to be end again anyway so uh yeah um yes especially with n is a thousand um instead of me I don't know I think it's just a lot of so this problem is there's some recursion obviously but I would just call it a bookkeeping problem and what I mean by that is that you just have to keep track of everything and that's the core part of this problem so yeah uh I'm gonna one to a hike so that's what I have with this one let me know what you think stay good stay healthy to good mental health I'll see you later and take care have a two-hour you later and take care have a two-hour you later and take care have a two-hour drive to a hike all right bye
Vertical Order Traversal of a Binary Tree
reveal-cards-in-increasing-order
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Array,Queue,Sorting,Simulation
Medium
null
459
hey everybody this is Larry this is me doing day 21st 21 of the code daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's part and we got a easy one so yay uh good because I'm a little bit tired I uh played a lot of softball today and went as much as I can I say that because I if you might be cool I have a pulled hamstring and it's still today is very uh I just say I got the blood voting it hurts again so it's a little bit sore all right let's see give it a string as check if it can be constructed by taking a substring of it and appending multiple copies of the string together okay uh and then you have ten to the fourth so the key thing to notice is just um yeah you have to be careful about the time constraints I think that's the biggest thing uh yeah what is the naive complexity right I think that's maybe the biggest thing uh let's see so given a number so I think the uh and this is something that I Pro I when I was younger and a very hardcore about competitive I would know off my head but basically let's see what is the biggest um well what is the number of the most factors right uh up to 10 to the fourth let's see I'm just Googling this so yeah number with most factors under 10 000. uh and it claims to be 7560 which is 64 factors which is one and itself including one in itself sorry uh I don't uh that sounds probably right uh oh yeah 64 sounds about right so uh and it doesn't have to be prime but that also means that if you um you if you put first this should be fine right what I mean by that is if there's only 64 uh well first of all is that you have to nice to be a prime yeah it has to be another prime factor it just has to be a factor um of the smaller length because otherwise then just yeah you have um if they're co-primes or relative primes if they're co-primes or relative primes if they're co-primes or relative primes then you have remainder right so that's basically the key thing and once you do that and then and once you know that it's 64 in terms of the number of uh factors that means yoga one the loop at least or ammo 64 times or maybe not the loop but the expensive Loop and 64 times linear is going to be okay right so that's basically the idea and that's you know I mean it is an easy after all so I guess that's basically the uh the idea so let's get to it and of course yeah there are some nuances but not that many I mean I think the biggest one is just you have to make sure that the factor is not whatever right so yeah so for I in range from let's say one to uh I guess n over two right um plus one so we include n over two uh yeah the reason being that you don't want it to count n because one is always going to be true but also two that's not part of the answer right so yeah if n my I is equal to zero meaning this is now a candidate then we can just do some I mean you could do some for Loop wow statement stuff but in five hand you can also just do something like uh S Sub wait let me see if I understand this correctly taking a substring of it and impending mobile copies of the substring together it's a very awkward phrasing that's all because I don't know if you can like do a shift thing but we'll see if it's wrong as well but yeah but then now if this is true then you just take the first chunk which is up to uh I yeah or the eye length and then we multiply it by n or by I so now we have a string of length I and if this is equal to S then we can return true otherwise we just return Force if we tried all of them and as we said uh this will go at most 64 times it should be good let's give us some and this is just double checking like mt cases and stuff like this um what if you have one character so the zero this is one so okay so this is in Loop so I think we're good let's try yeah okay so that's good I just want to make sure because edge cases is where users are mess up uh what about two characters well two this is going to be one so this is two so just once up so okay that's also you know try it out the two cases with two string and that looks good so let's give it some mint yeah uh seems like in the past I made some mistakes I don't know what happened there in September dude is that doing a contest what is this part 459 so that wasn't doing a contest so I don't think so yeah you did it back then uh oh I did some sliding oh I did some craziness hmm I mean this is like uh what should we call it I think I tried to do some KMP type thing but then I don't know is this faster I mean it seems like uh I mean this I guess this is the linear solution uh the way that we do it is I mean this technically linear but it's like linear in the sense of like f times um ironically this is actually faster than this linear even though this is supposed to be linear but um we can be but this is faster because string operations in Python are very fast because it's um it's implemented in C way often um but yeah but this is I would say this is f times n where f is the number of factors in N which is bounded by you know like I said ten thousand is gonna be 64. what's a hundred thousand I don't even know hmm the bit I'm just curious these are good constants to notice that I don't have to look it up next time but let's see what number less than 10 okay it gives me a number that doesn't tell me how many factors they use there's a name for this but I've highly composite numbers is that it 100 000 um I don't know I feel like these like are the number of prime factors I don't know uh oh I see seems like 240 is for a hundred oh sorry that's for one million so or maybe the 38th anyway but so but about like let's say even 300 400 million I mean that's gonna be too slow if you do something like f times n algorithm again but there's something to think about for certain other things of hundred thousand is 128 in case you're wondering so that's also probably cutting it tight but yeah uh anyway that's all I have for this one let me know what you think and yeah stay have a great week everybody stay good stay healthy to uh be good mental health I'll see y'all later and take care bye
Repeated Substring Pattern
repeated-substring-pattern
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. **Example 1:** **Input:** s = "abab " **Output:** true **Explanation:** It is the substring "ab " twice. **Example 2:** **Input:** s = "aba " **Output:** false **Example 3:** **Input:** s = "abcabcabcabc " **Output:** true **Explanation:** It is the substring "abc " four times or the substring "abcabc " twice. **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters.
null
String,String Matching
Easy
28,686
872
hey yo what's up my little coders let me show you in this tutorial how to solve the lead called question 872. leave some more trees basically we are given two binary trees and the only thing about which we hear is the binary trees leaves so we need to return true if the leaf values of these two binary trees are the same and they're in the same order here we have like 6 7 4 9 8 and again in the second binary tree we also have six seven four nine eight in this case we return true if the leaf values are not the same or they're the same but they're not in the same order we return false this is basically what we need to do let's do it so first of all let's declare two arrow lists we will use the first release to store the leaves uh of the first binary tree and the second one to store the leaves of the second binary tree so in the end we will be able to compare this to our list and we will check if they're equal in case if they are we will return true if k in case if they are not of course will return false okay once the error lists have been declared we can basically start traversing through the trees we can use the algorithm to traverse to the tree which is called the different search algorithms so for those of you who don't know this is the algorithm which we should definitely want to learn because it's like one of the most popular algorithms it basically starts at the root note and explores as far as possible along each branch before backtracking let me just declare the method first of all so guys we will traverse to the binary trees for the first binary tree and for the second binary tree the first search again right it will be a recursive algorithm and when you write a recursive algorithm always um the best start is that it will be to think about the base case what is the base case and as usually it is the base case is when the root is equal to now in this case you just want to return straight away because if it's now it means that you can't destruct any leaf values you can't do anything so that's our base case then let's think let's just consider the smallest binary tree with just one value so just with the rows when we reach this value it means that like it doesn't have the left child and it doesn't have the right chart so you cannot expand anymore you can traverse and it also means that you found the leaf value so and if is the case you just want to extract it right this is what you want to do oh let's extract the leaf if you find it if root left is now and root right is elsa equal to now we just add it to our array list if not we will need to go further and traverse until we reach the leaf value and if it's the deeper search algorithm first of all you want to go to the left side so we will need to do a recursive call first of all we need to traverse as much as possible left right now think about it right if we consider this binary tree we start at three is not equal to now and this root right now has the left and the right value we'll go here and we will go to the left side we'll go to the 5 we will do the same thing again and we will go to the six after that so we will reach the first leaf value six will not be equal to now but six will not have the left and will not have the root that right so we will add value six to our array list but after that if we will call after this if statement if you call this method again we will just reach the receive statement and will terminate after that right you will need to basically go to the right side which will mean that like if you start with three you go to the five extract six then you know recursion two seven four and basically we will traverse through the whole binary tree and we'll extract all the leaf values this is the d first search algorithm and once we have traversed through the both binary trees in the end we can just simply compare if the error lists and which we have stored the values are the same or not okay i see one typo okay should be fine now let's run the code to see if it works and it does let's submit guys perfect guys hundred percent um thanks for watching guys i hope it makes sense and it was clear um thanks for watching remember that lead code a day keeps an employment away so make sure you delete code and practice your skills this is a very nice problem then yeah that's it guys i will see you next video guys good luck and take care
Leaf-Similar Trees
split-array-into-fibonacci-sequence
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar. **Example 1:** **Input:** root1 = \[3,5,1,6,2,9,8,null,null,7,4\], root2 = \[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8\] **Output:** true **Example 2:** **Input:** root1 = \[1,2,3\], root2 = \[1,3,2\] **Output:** false **Constraints:** * The number of nodes in each tree will be in the range `[1, 200]`. * Both of the given trees will have values in the range `[0, 200]`.
null
String,Backtracking
Medium
306,1013
894
hey what's up guys this is Chung here and so today let's talk about another like a tree and recursion problem here it's called our possible for binary number 894 it's a classic medium problem I like this problem I'm gonna give it my own like here so what does this problem say alright let's say you're given a number so the input is pretty straightforward just say integer and then you need to generate return all the roots note after possible full binary tree so what does a full binary tree mean right so one node can only have 0 or 2 sub nodes right basically you cannot have one known to only have left or right so even though we're having a children as a child node it has to be both left and right and then you need to return all the node all other roots note of this all those nodes here all those possible full binary trees right any each normal value will be 0 it doesn't really matter you so in this case it's just 0 so with this kind of like every time when you guys see this kind of all possible trees a key concept here is to so how should we generate write how should we generate the possible sub trees right because each of them when you need to have like a unique root and for each of the root the node here they should be like separate right it cannot be you cannot simply do a DFS Traverse and then you just keep distributing different nodes because that won't work because every time we see a new note we need to make a new note outside when we see a new position here we need to use a new note we cannot reuse a previous one all right then that's cut a little bit difficult to understand here because while we were traversing down here right we cannot use the previous credit note so it has to be a new note every time right and the pattern alright the pattern for this kind of like find other possible trees a problem what is the pattern for that right so pattern is gonna be a we're gonna use a recurse a recursive call and we'll get the left basically we'll get the left subtree right forget the left trees from a recursive car a recursive call right and this recursive call this one will return what it will return right it will return on the left side all the roots notes that can be I mean basically all the possible sub trees aren't on the left side basically this recursive will return like let's say the root one right root 2 and the root 3 it's going to be at least after of the tree node that which represents all the possible sub trees on the left side and then we're gonna have a right same thing we're gonna have a right trees here same thing for the for every cursive here and here we're gonna have like a root what root like 4 5 and root 6 right let's just assuming on the left sub-tree we just assuming on the left sub-tree we just assuming on the left sub-tree we have a route one two three and then on the right subtrees are right subtrees with the possible sub trees its root five four five six then how are we going to return all the other possible trees with this tool right which is simply to a4 we do a nested for loop because we need all the combinations right with all those possible left and right basically we just need to pick all the combinations between left and right and then we construct to our current route right basically we're gonna have a left right left in left trees right and then we're gonna have a nested for loop here right all right I'll just I skip that and then here what we do we are here we do a node right so it's gonna be a not node out to a root here so tree node zero right so basically every time since we have all the possible left and right so for each of the possible combinations from left and right we need to create a new root this is the key point here every time we will create a new route because each of the combination will be a new subtree right so do a root dot left-right equals to so do a root dot left-right equals to so do a root dot left-right equals to its left and root equals to write equals to right and then all those roots here so in the end gonna be all red announcer here right kind of year answer here is going to be a list here so every time we keep adding this route inside here and this answer will be our final result here so basically that's the template for all this kind of possible treat problem so with all the possible treat problems first we step is to get the left sub trees right and then you call you do a recursive call with the with whatever you need in this case is gonna be the number left here right and then on the right so you do the same thing for the right tree and then you do a for loop once you have 11 right you just select from select all the combinations from left and right and then for each of the combinations you create a new route and then you assign the left and right to it and then you just return this route list recursively right so then it will give you the final result cool so that's a template all right so then with these templates let's see how can we solve this problem right so mmm okay let's see what can we do here right so which number n here right let's see what can we do here we have this okay so if N equals 2 what if N equals to 1 right so let's have a base point here right if N equals to 1 what's the what's gonna be the result right it's going to be return what the tree node 0 right if there is only one node we just need to return this one this tree node I also what right then if this one is bigger than one right so what do we do a for loop right so I think another key concept here is like let's say we start from the root zero from the root here right and at this moment let's say yes let's give an example seven here right so we have a seven here and equals to 7 right and then we start from this the first root here right so how can we Traverse how can we get the left and right we can they're like different possibilities right see it for this one see we are the left is one right and the right side is like water it's fire yeah 5 and here is also 5 right and in this case what the left is 3 right so this is 1 right left is one left is 3 right and the right side is also 3 and this but when it comes to here right the left side is 5 right so that's how we as you can see here so those are the numbers we can distribute to the left right and then we can just simply for the right side we can simply use the end to deal to substract there's a left side to be the right side subtree node right so yeah so basically we have since we have that now we can try that we can do the coding here let's find the answer here right and it because in the end we've done research returned the answer here so what do we do here right we for right let's do I hear right in range what's in range 1 right because as we notice that right as we noticed that 0 that makes sense right 0 means it's nothing right so we don't have to do it right so but as we notice that you can only distribute it a odd number of are the number of the nodes to the little to the to each side right that's one right like we said this is 1 this is 5 right this is 3 why because if you distributed 2 to the left side right let's say there's a node here and there's a left and right let's say you distribute it if you distribute it to this side right so you have 2 on this side there's no way you can form a full binary tree right it's I think it's pretty obvious if you have one here and then what you have 1 left right it has to be a lot either this side or this side so basically the full binary tree it has to be an odd number you cannot distribute even number on either side so that's why we have here so basically when we have n number here we basically we have the first for loop is to try the for loop it's to try all the possible distributions to the left and the right and then we just try all the possibilities here right okay so E but since we only want to try all the out possible numbers right so we basically that's all that's why we start from 1 and the step is to here and then like I said now we can have like a recursive call here we're gonna have a sub trees here right he goes to the same method here we basically were calling ourselves out possible a full binary tree right and then it's gonna be I here right since we're trying so this I will be our the notability will be distributed to the left side and then the right tree right the right trees will be a possible five full binary tree then what's going to be that so it's in class I'm sorry and miners I minus 1 right so what is the one is the current node rights with any here we need to subtract one for this current node right seven right there's already because besides the left knows and the right note we still need a roots nodes to construct a tree right that's why we need to subtract one here that's so that's the nodes we can distribute to the right side right so and once we have the left trees and right trees which two of nested for loop here right we do a four left in left trees right and another nested for loop right in right trees and then every time we need to create a new node 3 node right so with in our case the value is 0 and then we just do a root that left equals to left and root that right equals to right and then we just add in the end we just answer that we append right up and this out the life what am I thinking root right the in the end which return this answer since we're doing this recursive call right when this is 7 yeah at the beginning this is 7 right so we distributed 7 which are all the distributions we have here and we get the left and right friend for each of the distributions we create a root node here and wait with suspend all the possible left and right to the global answer here and then in the end we just return this answer and this answer will also be returned here right because it's a recursive call so basically every time out so this like as possible full binary tree will return all the new roots notes and we'll be using the root notes along the way here right this is like actually it's kind of like top-down top-down dynamic kind of like top-down top-down dynamic kind of like top-down top-down dynamic programming right because we're using the previously calculated results in so this is a tree as a fir tree problem it's we can only use the top-down because that's how we Traverse top-down because that's how we Traverse top-down because that's how we Traverse down here right I think for this one too we can we use the bottom-up maybe we can we use the bottom-up maybe we can we use the bottom-up maybe yeah but this is like top-down to think yeah but this is like top-down to think yeah but this is like top-down to think the thinking of the top-down the thinking of the top-down the thinking of the top-down as for a tree problem it's more intuitive for me so it is easier to think it from top-down because we have think it from top-down because we have think it from top-down because we have the rules and left and right and I think that should do it right oh yeah I need to redefine that beginning here cool see it works and since we're toxins which we mentioned it's a dynamic programming so one of the improvements we can dynamic programming can usually always have is that it's the memorization right as you can see here so every time we return the answer here but we'll just keep for each node we keep calculating all the possible numbers here right with just keep doing it for each of the number here right so a simple right a simple man yeah sorry so with recursion this one that's the oh I always want to like emphasize this point one more time because Ruby the recursion we need to have a break point right I mean we need to have a base basically N equals to one will be up our base case because one we know there's only one possible trace here if we go to zero there will be that's gonna be empty right so keep this in mind we need to have like pace otherwise if we don't have it we're not going to return anything basically okay so let's define like a global variable here right so let's do a self and let's do a memorization right let's do a diction right here right so what's going to be the dictionary we can do a ma'am one right goes to uh what is that same thing here right three note yeah we can add zero here but I think we don't need a therapy cause because we're not going to do we need a zero let's see one on the left side no probably not no since we are doing this like odd jump we own every time we jump to and with this number if this number is valid we always get like we will always get both odd number on the Left left and right side so we don't need that zero base here yeah but it doesn't hurt I think we can just we can add it here doesn't hurt so towards zero right so what is zero basic empty right empty array right empty list and here right so here since we already have the memorization here we don't need to like we don't need to have this base case here instead or simply to with check if n is in does the memorization dictionary right if then we just return this return the self memorization dot n right and here the in the end we just need to set equals to answer right so that's our the memorization template here every time we child if so we already calculated for this n then we simply return it otherwise within the end we just assign this treat this answer to this memorization list so let's run this one more time three oh sorry typo your tree note cool see so now this time it's much faster right almost beats ninety five percent it's all because of this memorization here because we don't really calculate then the number we had already calculated so that's one of the classic improvement for any dynamic programming and the recursive yeah so yeah just to recap really quick so with all this kind of full binary tree problem so we get left sub trees and right subtrees and then we do a an asset for loop to get out combination from life and right and then for each come each of combination we create a route and we sign this left to the root and right to the root and then in the end we just use this route at I sorry as our result so yeah and all this kind of case is just only for this quite specific problem because we need to decide all the possible possibilities under how many nodes we need to give distributed to the left and right all right cool thank you so much for watching the video guys and I hope you guys liked it and yeah I'll be seeing you guys soon thank you bye
All Possible Full Binary Trees
random-pick-with-blacklist
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tree where each node has exactly `0` or `2` children. **Example 1:** **Input:** n = 7 **Output:** \[\[0,0,0,null,null,0,0,null,null,0,0\],\[0,0,0,null,null,0,0,0,0\],\[0,0,0,0,0,0,0\],\[0,0,0,0,0,null,null,null,null,0,0\],\[0,0,0,0,0,null,null,0,0\]\] **Example 2:** **Input:** n = 3 **Output:** \[\[0,0,0\]\] **Constraints:** * `1 <= n <= 20`
null
Hash Table,Math,Binary Search,Sorting,Randomized
Hard
398,912,2107
904
this is a classic problem to solve and certainly it is asked by a lot of tech companies what they generally do is they will try to play around with the words a lot try to make a whole story behind it but the underlying concept Remains the Same one such perfect example is fruit into baskets on lead code so let's see what we can do about it Hello friends welcome back to my Channel first I will explain the problem statement and we'll look at some subative cases I will also summarize the problem for you such that it becomes a one-liner going forward we it becomes a one-liner going forward we it becomes a one-liner going forward we will start off with a brute force relation along with some diagrams that makes it really easy to visualize going forward we will find an efficient solution and then also do a dry run of the code so that you can understand and visualize how all of this actually working in action without further Ado let's get started first of all let's try to make sure that we are understanding the problem statement correctly this problem is written in a very verbose manner so we will try to shorten it up basically you are given an array where each element is prevents a type of fruit for example in the first 50s you have three elements right but only two different types one and two similarly in your second test case you have four elements but only three different types 0 1 and 2. now you are given two baskets and you have to pick the maximum number of fruits possible such that when you're picking these fruits should be contiguous so how does that work out let us look at the first test case and look at an example I see my first fruit that is one my basket is empty so I add a fruit I look at my second fruit my second basket is empty so I put it over here I look at my third fruit it is one again so I can add it to my basket notice that in a basket you cannot have two different type of fruits so for the first step is how many total fruits were you able to pick you were able to pick a total of three fruits correct so for the first test is three will be your answer let us look at the second test case now in my second test case I start with the first fruit that is zero my basket is empty so I add it my second fruit is one my second basket is empty okay so I can add it my third fruit type is two right now I don't have any empty basket the first basket has a fruit type of zero and the second basket has a fruit type of one so I need to stop over here how many fruits are you able to collect you are able to collect a maximum of two fruits correct but this is not the answer you need to determine what is the maximum amount of fruits that you can pick so instead of starting from the first fruit what you can do is you can start off with a second element that is one my basket is empty so I add a 1 over here move on to my next tree my basket is empty so I add a fruit over here move on to the third element it F2 again I can add the same fruit to my basket so I add a 2 over here so once again how many total food should I pick up I picked up three different fruits correct so once again for this test case three will be your answer similarly let us look at the third test case also the first element is one what happens if I try to add it to my basket okay well and good the second element is two my second basket is empty so I add it over here go ahead now I get a third type of fruit I don't have any space over here right my first basket has one type and second basket has two type so I need to stop over here and how many fruits did I collect I only collected two fruits but this may not be the maximum for what we will have to do is we will have to try again okay what do we do this time let us try to start from the second fruit 8f2 so I add a 2 over here move on to the next element this is 3 right so I add a 3 to my next basket move ahead I get a 2 again and add it to my basket move ahead once again I get a 2. once again I can add it to my basket so how many fruits did you collect you collected a total of four fruits this time right so for the third test case 4 will be your answer so basically what we are doing over here we are given an array and we have to find out the length of the longest contiguous sub array with at most two distinct integers just think about it in the first test case the length of the longest continue this is three right with at most two different elements in the second test case this is the length of the Contigo sub array with two different elements similarly for the third test is also this is my Contigo sub array with at most two different elements right and you just have to return its length so this entire huge problem it can be simply summarized into this small problem itself think about it covers all of the facts you only have two baskets right so you are taking two distinct integers then you can start from tree of any choice right that means this contiguous some array can start from any position and you're only picking one fruit right that means in your array you are including that integer itself and the last condition once you reach a tree where the fruit cannot fit you must stop it simply means that this array should be contiguous right otherwise you could stop and then pick from a later tree right for this entire problem it can be summarized easily into just these two lines for now if you feel that you have understood the problem statement correctly feel free to try this problem once again on your own otherwise let us dive into the solution to start thinking about the solution let us try to take up a generic array so this is a quite big array that I have taken and it will make things easier to understand and to make it even more interesting let us try to add some pictures to it so you know that all of these numbers are type of fruits right so I am just assigning all of these fruits over here so type 1 is Apple type 2 is banana type 3 are grapes and type 4 is oranges so basically what does your array look like your array will look something like this right this will help you to understand things a lot better just trust me now moving ahead what you have to do you have a basket right and you can have two type of fruits so a Brute Force approach will be that okay I start from the beginning right I have an apple over here so what I do is I take this apple and I put it in my basket correct now move ahead I have a banana once again I take this banana and I add it to my basket right now my basket is full I can only have two different type of fruits right or you can say two baskets correct move ahead now once again you get an Apple I can add an apple to my basket right because I already have a basket that has apples move ahead now I see one what happened great just take this apple and you can add it to your basket move ahead now you feel a grape right so you know that as soon as you encounter a fruit that is not available in your basket you just have to stop over there so how many fruits were you able to collect you were able to collect a total of four fruits right so this is one scenario if you think about it we have not traversed the entire area yet correct so there can be more such combinations so with one combination you got a possibility that hey maybe I can collect four shoots but you need to explore more so what do you do now this time instead of starting from the first position you will start from the second position what is the fruit that you have a banana so simply take your banana and add it to your first basket what is the next fruit you have an apple simply take an apple and add it to your basket the next fruit is Apple again so take an apple and add it to your basket the next fruit is a grape so you need to stop this time how many fruits should you collect you collected a total of three fruits right this is less than the previous number so what you can do is you can simply discard it up till now 4 is your maximum number of roots right similarly you can keep moving ahead you get started from the second position right so this time starts from the third position what are you getting you are getting apples so add the Apple for the next location once again add an Apple for the Third location this time you get a grip just take this grid and add it to your basket move ahead now you get the orange once again if you look at your basket you do not have oranges so you have to stop over here how many fruits should you collect you collected a total of three fruits so three is also less than four so this is not relevant for us right once again you empty your basket and you will start with the fourth element now just try to think if you start from an Apple okay you found a second fruit that is great you found the orange again so what is the maximum contiguous surveying that if only the length 2 right once again 2 is less than four so this will not be a condition start from the next location you found a grape then you found an orange and then you form the third type banana once again you stop over here so the maximum length you could find was two is once again less than four so you need to stop start with the orange now and this is where things get interesting you take up the orange and add it to your basket the next fruit is banana take this banana and add it to your basket the next fruit is again banana add it to your basket the next two fruits are also bananas I added them to my basket and the next fruit is orange I add this orange to my basket now how many fruits do I have a total of six fruits correct 6 is greater than 4 right so now I have completed every combination and I can determine that hey this is my answer and this is the maximum amount of fruits that I can pick with all of these given conditions right now this was a Brute Force approach where you were considering every possible condition right you start from the first element second third fourth and then you are going all the way this complexity will be order of N squared so certainly we need a better approach what can you do about it let us look at the problem once again I have the sample array with me right and there are four different type of roots and these are our two baskets correct what we will do is we basically have two pointers this is my first pointer and this is the second pointer what we will do is we will try to add fruits first of all let us look at the first pointer is pointing at Apple right what I simply do is I try to take an apple and I can see can I add it I can add it to my basket cool move the first pointer ahead what do you see a banana can you add this banana yes I have some space so I take this banana and I add it to my basket now what do you do move your pointer one step ahead you have an apple can you add an apple yes because your basket already has apples move one step ahead you see an apple again can you add an apple yes so right now you have a total of four fruits in your basket correct move one step ahead now you see that okay you have landed at grapes and you cannot add grapes because you already have two different type of fruits correct so what can you do now what the second pointer will do is they will try to remove the fruits in the order they were received until and unless I have some space in my basket think about it currently this pointer is pointing at an apple so what I do is I simply remove one apple and then I move my pointer one step ahead I still cannot put in the grates right what do I have over here I have a banana over here so what I will do is I will try to remove the banana I remove the banana correct and now what happens you finally have space for grades correct so what you do is you simply add grapes to your basket and at every instance you just try to determine what was the maximum number of fruits that you can keep up till now you had a total of four fruits right with this combination you have three fruits correct but three is less than four so you do not need to update this value right now move ahead the next fruit is orange do you have space for oranges over here no right so that means I need to start removing fruits which one do I remove an apple I take this apple and I remove it I still don't have space so I move my point of one step ahead once again I see an apple so I will remove the sample now I have some space right so what I will do is I will take an orange and I will add it to my basket now you have two different type of fruits two is still less than four right four we don't need to update any value take the first pointer and move it one step ahead do you have space for banana no right that means once again you have to remove some of the fruits you move your previous pointer one step ahead and you see grapes so what I will do is I will remove grapes from my basket now I have a space so whatever to do is I will take a banana and I will add it to my basket notice that I am removing elements from the previous direction right because you need your array to be contiguous you cannot pick any random elements to remove so that is why you will have to remove fruits in the order in which you had already added them based upon this idea now just keep moving ahead you move ahead and you see hey do you have space for banana yes you can add a banana would have take this banana and add it move ahead you see a banana again take this banana and you add it move ahead now you see a banana again take this banana and add it move ahead now UV and orange can you add an orange yes so take an orange and you add it you have now reached the end and check out how many fruits do you have in the basket you have a total of six fruits correct that means you need to update this value since you have reached the end you know that this is your answer and this is the maximum number of fruits that you can have in your basket you see that we only did one iteration of the entire array let us quickly do a drawing of the code now and see how it works in action before moving ahead I would just like to say that if you do like my content consider joining my channel and becoming a member it really supports me to keep on bringing all of this quality content to you let's get back to it on the left side of your screen you have the actual code to implement this solution and on the right once again I have a sample array that is passed in as an input parameter to the function total fruit the first thing that we do is we create our basket and this basket will be type of a hash map so basically it will tell me that hey this is the fruit type and this is the count of the fruit we just need to make sure that we only have two different type of fruits in our basket right because that is the problem limitation moving ahead we initialize some pointers left is zero right is zero and Max Root is also zero so left is the starting pointer and then right is the other pointer you also have a variable Max fruit that is initialized to zero right now correct you start with a for Loop this for Loop starts from 0 that means you are going to move this pointer all the way to the end right up to fruits dot length and then what do you try to add this current fruit to the basket so you take up this root one try to get its count if it's not available in the basket just add it otherwise increment its counter so right now you don't have this root right so one gets added to this and its count is also one right check your basket size now your basket only has one type of fruit so right now you do not need to look at this while condition and then you try to find out hey what are the match fruits that I have Max fruit is simply a sum of all these count variables so right now I did add one fruit for the value of mad fruit is now one this pointer moves ahead and now I am pointing at 2. does to exist here no so I add the fruit type of 2 and its count is also 1. my basket size is still not greater than 2 so this will not execute and I will update my Max fruit how many type of fruit do I have now I have a total of two fruits right just count these move ahead now I'm pointing at 1 again do I have the fruit in a basket yes what if it's count one so what I will do is I will just update its count my basket size is still not greater than two so this will not execute and I will update my max value for two plus one that is three move to the next value now that is one again what if it's count its count is two so you update it and this changes to three now I still have only two type of fruits so this will not execute and Max rules will update now Advance one more pointer this is where things get interesting the fruit type is three I do not have it in my basket so what do I will add this route to my basket and its count is just one right now correct now look at this code my basket has more than two type of fruits for what do I need to start removing fruit from the beginning until my basket size is less than two so I look at the fruit count at this particular pointer I check my fruit what if it's count its count is three four I do a minus one and then I will add it to my map I increment the counter so my pointer move one step ahead I still have more than two type of fruits so this Loop will run again and this time I am gonna remove the fruit type 2 this value is 1 if I decrement its counter it will become 0 and if it becomes 0 I can remove it totally from my basket so what you have now once again you just have two type of fruits so you will exit out of this Loop try to update the max fruit they are three now but three is less than four so this will remain constant the above for Loop will now run once again and this time you will point at the next fruit that is 4. so now you see how this Loop will go on and ultimately you will Traverse all the way to the very end and this concept will be exactly similar what we did just a while ago at the very end you return Max fruit and this will be your answer just try to go through the code once again and see how this hash map will keep on updating that will give you a very good idea the time complexity of this solution will be order of n because we iterate through the array only once and the space complexity of this solution will also be order of M because we use a hash map to store the type of fruits that we have I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that what makes this problem so special is that instead of an array this problem can be converted into a string as well try to think about it you can be asked to give me a substring that has contiguous characters with only two distinct characters right the entire problem is same you just have to replace the array with the string and similarly instead of two different fruits you could be given an input value K so the problem changes to find a contiguous sub array with at most K distinct characters right so just buy some Twist of words you can form all such different combinations of the same problem right so that is why I always emphasize upon okay just understand the concept how we are approaching the problem then writing the code is very easy right you know how to deal with two different fruits and similarly you can deal with K different fruits so while going through this video did you face any problems or have you seen any other such problems which work on the same concept just tell me everything in the comment section below and it would be helpful for anyone else also who is watching this video you will get a compiled list of all the same kind of questions that will be really helpful and I can clarify all of the doubts also that you have as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also a huge shout out to all the members who support my channel do let me know what other problems do you want me to follow next until then see ya
Fruit Into Baskets
leaf-similar-trees
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Tree,Depth-First Search,Binary Tree
Easy
null
1,727
um hello so today we are going to do this daily challenge largest submatrix with rearrangement so the idea here is we have a submatrix of one and zeros and we want to get the largest submatrix where every element is one and what we are allowed to do here is reorder The Columns optimally um so we can change the order um in whatever way we want so that we get the largest sub Matrix okay so if you look at the first example what we can do here is um we can take the this um largest number of ones and put it in the middle that way basically we get this as the largest sub Matrix and so the area here is four um another option is to also put this one first and then the second one um in the middle that also works but we get the same area this is also one note here about this is lead codes sometimes give you the first example in a way that is to mislead you a little bit from the solution for example in this case they put the one with the largest number of ones in the middle instead of in the first position even though this solution give you the same area you will see later in our uh implementation of a solution here is that it's it would be easier to put it in the first position to put the column with the largest number of ones in the first position okay so that's sort of the idea here now if we look at the constraint we have 10 to the^ of five so this tells us we need an the^ of five so this tells us we need an the^ of five so this tells us we need an oven solution uh oven being basically M byn so basically um in order of the size of the submatrix um okay so let's see how we can optimize implement this um okay so how do we actually handle this so with any like submatrix triangle like what we are looking for here what matters with an area that's what we are trying to maximize the area so what matters here for an area well area is based on the width or the Bas base so this can be called either width or base multiplied by the he right um and so how do we what you want to do to get the maximum area because the area is just going to be the width multiplied by the height so how do we maximize it well you maximize each one the width and the height right um to get the largest submatrix so that's the first idea to keep in mind here um and so now the core idea is okay how can we maximize this well we do know that we can rearrange the columns so we can for example put this one in front so we can end up with something like um having one here all the three ones first and then having this one with the most ones next and then zero so we can change the order of the columns but we can change the rows we can't decide to for example take this and move it here we can't decide to say have one um one zero that we can't do that right um we can change the order of the rows um and you can see also if you change the order of the rows that impacts what the triangle the maximum triangle is because um if you take a look at this one the maximum submatrix is actually here if we change the order of the rows now the maximum one we can get is actually this one right but in another Matrix maybe reordering the rows gives us a larger one but we can't do that we can't three our to rows okay so that's something to keep in mind here um okay so with this um how can we use but now the question becomes okay um why did do I decide to put this the largest number of ones in the beginning is that helpful at all well to do that let's first do sort of a prefix sum because well how do we know that OPP position gives us the largest hate right well the position that has the maximum number of ones gives us the largest number the largest eight and so let's just do the prefix sum so if we do the prefix sum with three setting at zero right because let's say you have 1 0 1 one 0 well this one you have if you do the prefix sum you have 1 two 0 1 0 one two you need to reset at zero here you can't do like the normal prefix somewhere you would have one two three because this is misleading because you can't take for example you can't take this as a submatrix because you have a zero okay and so you need to reset at zero for this prefix sum okay and so how do we so let's do that let's apply that to this Matrix here let's do the prefix sum um like this so let's copy this move it here okay so if we do the prefix sum with the reset then we'd have zero one the prefix sum on each column by the way by column okay so two 0 1 2 3 so immediately Now by looking at just one single uh position you know that you have the largest he of the column ending at that position so that's the benefit of doing this first the prefix at zero okay so now if we look at this what do we see well we first see that for example for this row it's sort of problematic because of this zero is getting in the way right it's not allowing us to get for example this here and so since we are allowed to uh rearrange the columns let's just sort Now sort by what well we let's sort each row by let's just sort each row now we may say okay if we sort each row would the column sort of would like the first position of the column be here and then the second position be here with that be sort of not actually sorting by columns but the answer is no because we are taking the sum the prefix sum so if this one is larger right that means this one was um had a one right and so if we put this one here we will end up putting this one here one as well because we sort in decreasing order every row and so if we do that so this is basically the prefix with reset now here we let do the Sorting so if we do the Sorting at this point we would have 1 0 2 one 1 3 2 zero so you can see each column actually remained the same this column here went here this column here went to the end this column here went here so sorting by each row is this is going to be the same as sorting um basically like rearranging the columns so that's a key idea here as well okay so now knowing this what do we do next okay so now that we have it sorted how can we get the largest area well now it's very easy because since we know this has the most ones right we can just go through our um we can just go through our rows right so we can just go through each row and calculate the area so for example at this position what would be the area well the area is going to be the number of ones which is what we have in this position so let's call this U ones and let's say R now is equal to zero then it's going to be just ones at position zero for the row and then column zero multi so this would be the height because that's the number of ones so this would be the he now what would be the width well the width is this is column zero the width is just the column if we are at column one the width is going to be the entire thing if we are at column two the width is going to be the entire thing and so the width is just actually columns plus one right okay and so that means basically that sorry so that means basically here the is going to be just columns plus one which is going to be 0 + one okay so the which is going to be 0 + one okay so the which is going to be 0 + one okay so the formula is that we are going to use is going to be ones at position RC multiplied by C + multiplied by C + multiplied by C + 1 okay so here the area is one is that the max area no so we proceed we check here the area is going to be zero because we multiply by zero so we proceed here zero and then we go to position uh Row one then we go now let me just put this down here so now we go to r one um so it's the um the he is going to be two because that's the number of ones we have multiplied by um the width which is going to be column plus one so it's two so the max area now is two we go here what's the height is one what's the width is C+ 1 so one what's the width is C+ 1 so one what's the width is C+ 1 so it's two and that's actually what you see here if you do this because this means that you have a one so the max submatrix is just this one which is two which is what we have here so um and then if we go forward a little bit more uh so if we go forward to this position then it's going to be 1 multiplied by 2 + 1 so three so we have multiplied by 2 + 1 so three so we have multiplied by 2 + 1 so three so we have now three and that's actually just this entire thing right now why are we able to do this why are we able to just multiply by the value here because we know that the previous matri the previous column had a larger number of ones at this position right because we sort by the L by the larger and so that means we can this one is the minimum so if you have like let's say something like this with one and then something like this with one1 you know that at least you can do this entire thing as a submatrix because this has a larger number of ones right if you let's say have now one here then you know you can do this one right sorry this is not super clear you know that you can at least do this one because you are guaranteed that this one has more ones at this position so the he that means basically the if the sum here is larger that means you at least have these and so that's sort of the idea here of using C plus one as the um as the width um and so we continue we go here so what does this mean that's 3 multiplied by one so three and then when we go here that's two multiplied by two so now we have four and this is exactly the solution of if we reorder we get this right so we put that for there and then when we go here it's multiplied by zero so it doesn't matter so this is the optimal solution we get okay um so that's sort of the idea of the implementation now what's the time complexity here well we are doing an O by n first to uh to just do the prefix uh sum here with a reset because we go through each position so this is O of M by n first and then we do the Sorting so for each row we sort right so if we say m is the number of rows then it's going to be M log of n because we sort the each row okay so it's going to be MN plus m log in um so that's our uh our time complexity now let's implement this solution and make sure it passes um okay so let's implement this solution so first we need just to get the size of the each the number of rows and the number of columns we'll need this for later and now let's do our prefix sum in another uh separate array of course you can do this like in the same Matrix one but just to make this more clear I'm going to do it in a separate one of course that would mean extra um space complexity um and now this is going to be in range of rows okay and then what we do is we go through each column so that we can record the prefix remember the prefix uh sum is going to be calculated by columns and so once first we know that um first position right is going to just be um Matrix of zero right so the first row for the first row it's going to be just the same values because there is nothing before and now for each row we can start from one because we already handled the first row and so this is going to be just the number of rows then ones at r c are going to be equal to um the previous Row the same column right Plus one but only if the Matrix at that position actually has a value of one otherwise we want to reset and so to reset we just set it to zero okay so now that we have our sort of pref modified prefix sum we can just go for each row remember we want to sort each row in decreasing order so that means we sort in decreasing order let's just use refers in Python and then for each column right we want to calculate the max area that's what we did in the overview for each position in the row we calculated the max area that gives us now we of course need to initialize the max area so to zero that's what we return at the end as well and then here our Max area we're going to take the max with Max area and current area now we need to calculate our current area and we said current area is just hate multiplied by width so what is the hate we said that the hate is just going to be the N the number of ones from our prefix sum because that tells us how many ones we have up so that's the he and then the width we said is going to be just C+ one because we is going to be just C+ one because we is going to be just C+ one because we are guaranteed that anything before this C has more hate so has a larger hate so we at least would have same hate that we can that can be contributed to our sub subm here so that's why we do C+ one um and yeah that's pretty much do C+ one um and yeah that's pretty much do C+ one um and yeah that's pretty much it um now we can this was just for clarity we can simplify it here to be um like this um and we can simplify it even further like this okay um and now we can run this and see if it works and looks like it did so let submit and this passes okay uh yeah so that's pretty much it for this problem um thanks for watching and if you need oneon-one coaching for your coding oneon-one coaching for your coding oneon-one coaching for your coding interview please click on the link uh in the description see you on the next one bye
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
76
Hello hello everyone welcome defect in the flashlight to challenge and fast forward to wish you very happy independence day thursday morning mist subscribe different the independence day came bullet stories from agra in paris about journey of partition and difficult to grow and subscribe Video Subscribe To That Electronic Eighth Exam Video Posting Problem Death And Id ABC Subscribe Length Of The Subscribe Video Subscribe Not The Subscribe To Woman Want The Presentation To Minimal Interesting Left Side Effects And Solving This Point To Point Approach Arvind Subscribe subscribe and this subscribe Video That You Read Frequency Army Canteen Second Currency Are Ajay Calculators Page Elements Present A Difficulty Of 800 What We Will Do Subscribe Will Check Subscribe subscribe and subscribe the Channel Middle School Elements Subscribe To Kwangcho First Explain The Benefit Of Bus Accounted For No Dues Certificate To the length of the district and subscribe The frequency of elements present in do subscribe to that and what you will see next character of birds and The Video then subscribe to the Page if you liked The Video then subscribe to Let's Move Ahead of Bansi and 2004 Reduce Along with this Video subscribe and subscribe this Video subscribe What you see here you will see certificate subscribe The Channel Please subscribe and subscribe the will of another level I have length but will helps identify The Length of the Meaning of Trade Talks All the Character of Living in Fear You'll See the Start 0216 Reduction in All It's Not Been subscribe and subscribe the Video then subscribe to the Joe Alarm's Country Andar Is Here You Saw at the End of Birds Performance Video then subscribe to subscribe Video subscribe Increment in the corresponding to the at character minute starting index in frequency avoid you will update you to the value of frequency Video then subscribe to The Amazing is the software is pointed water retention is point to point question On Unmute Hour In Festival Season That Did Not Possible For Lets Lutia Doob Will Contest All Dual App 200 Let's Move Ahead And The Lord And Equal To Go Away There Difficulties To Minus One - subscribe to subscribe that and share The frequency of turn off but this pin 2051 and you will again due subscribe to 180 exactly two minus one pimples pe that and what does oil olive is folded hai latkan developers and share you will see that this button element key and this frequency to Jio SIM Subscribe Lakshmi Subscribe To Hai So You Found Another Possible Answer And Ancestors From This Starting Point After Till This Point That DOB COD Chief Guest Ki Aunty What I Want You Will Calculate The Length Of The Subscribe To The Most 11:00 - 110 Test Note Alauddin Update The Institute Will Not Starting Subscribe To Switch Up Till What Length Problem Person Subscribe Frequency - 2 - 2 - 2 Candy Crush Mode Treeless Isko Frequency Of Guest Updates - Subscribe That Get Updated To Will U Suppress A Beer Gimmick Meeting And Counter Because Frequency Has Not Welcome Great And You Will Gain Control Now School Of Birthday To My YouTube Channel Subscribe 21 [ Subscribe 21 [ Subscribe 21 I Just One Do Frequency Down Dharmendra Daughter On Pure Account Download This Way Break Point 168 Point Do No And 2nd Positive Way Will keep on moving the point at times you in next video 2018 To connect with hubs pe frequency of see in the frequency of which one will reduce frequency 2015 Will reduce internal body gets reduced to 10m Another possible solution which starts from the end of the Mission Point to this point 9 6 7 Greater Noida will not be possible only through which they see in the map of - - - 2070 Will not be developed here Next Vihar Phase PET frequency and depot - 120 Phase PET frequency and depot - 120 Phase PET frequency and depot - 120 Next Vihar Phase PET see from - 120 Neck Switch Of Birth PET see from - 120 Neck Switch Of Birth PET see from - 120 Neck Switch Of Birth That And Hold To You Will Update The Frequency Of Being From 2nd Year The Frequency Be Coming 20 Minutes Subscribe To Aisa Possible Subscribe And Duties Of Subscribe To 28 - 94 With Slogans And Minimum 28 - 94 With Slogans And Minimum 28 - 94 With Slogans And Minimum Balance Free Beach Sex New Updates Wali And To 4 And Good Dancer Point Se Z From The Prevention Research To-Do List Start Will End In Research To-Do List Start Will End In Research To-Do List Start Will End In This Video You Can Find The Length Of Track Setting On This Point Up With The Length Of Do That Under Consideration That Now Laxman World Record In this section or a digital problem don't worry I will be clear and according five wedding dresses are pretty simple and straight forward hai luta do defined frequency path against frequency of all character different directions of 2030 string extender character update frequency of lord shiva reddy the artist and technician Variables And Lemon Juice Explain The Function Of Close Start And End Points 202 Always Minimum Set Variable To Two Something Point Of The Answer Is The Meanwhile The End Character Industry In Artificial Last 20 YouTube Content That Today Remover is you also all reducer frequency of moving ahead with your and pointed instrument the volume to the impossible solution subscribe - subscribe - 2 - do love you to the first to enter a part air hub print list all possible sallu progress with straw tractor Interest String Instrument Subscribe Now To Receive New Updates The Best Possible Solution subscribe to the Page if you liked The Video then [ Video then [ Video then The British Straightforward and Time Complexity Updates Approach Is Mode Of Length And Plus App Is I Hope You Enjoy Depression Lipid Please Don't forget to like share and subscribe our channel thanks for watching video upload win for more updates dedicated to us c ashtam aur vid
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
63
hello everyone in today's video we'll be tackling a legal problem called unique path 2. this is a classic problem that can be solved using dynamic programming and you may encounter the problem or its variations in interviews every now and then so you should fully understand the technique to solve this problem and be able to pass all test cases quickly and correctly first let's understand the problem statements given upgrades with obstacles we need to find the number of unique paths from the top to left cell to the bottom right cell the grid consists of cells and some cells may contain obstacles that cannot be crossed like this one our task is to determine the number of valid paths while avoiding these obstacles the problem gives two examples let's check the first one Returns the value of 2 which means we have two paths to reach the bottom right cell the first path will be to go right then go down the second path would be to go down then go right notice that you cannot use any path that contains this obstacle then let's check the second example the return value for this example is one because there is only one path to reach the bottom part cell which is to go down first to then go right you cannot go right then go down because there is an obstacle in it to solve this problem we will use a dynamic program approach to see the reason behind it let's first consider how we can calculate the number of unique paths to the second row in the third column here it should be equal to the number of unique paths to its upper sale here because we have to pass the upper cell to reach the lower one we cannot reach this cell from its left because there is an obstacle in it but what if we didn't have this obstacle then our answer will be the additional two parts the first part is the same as before it's the number of unique paths to reach its upper sale the second part will be the number of unique paths to reach its the left cell here are no other possibilities because we can only reach the targets via the two sales there are other cases too but I won't illustrate them here I will talk about them afterwards in the Code walkthrough Parts the point is we can calculate the number of unique paths to reach each cell by using the value of its previous sales which is the essence of dynamic programming that's also the reason why we use this method in the end we will get the number of unique path to reach each cell including the last cell the number of the last cell will be our answer we can return it safely let's write a code and explain each case along the way we first Define m as the number of rows in the grades and we Define in as the number of columns of the grades then we create a two-dimensional array then we create a two-dimensional array then we create a two-dimensional array DP the column counts and the low counts of DP is the same as obstacle grade dpij represents the number of unique paths to reach cell i j from the top left cell so as you can see DPM -1 -1 -1 n minus 1 will be the answer then we iterate through the DP array and fill this value one by one after the iteration we just return DP and minus 1 and -1 and -1 and -1 so let's show first two-dimensional array now let's see how we can set the value of the cell in dpra first if there is an obstacle at IJ like the second row in the second column in this example then there will be no path to reach that position so in this case DPI J will be zero so a obstacle grade i j is equal to one then DPI J OB zero otherwise we check if I is equal to zero and J is equal to 0 2. in this case we are located at the top left corner which means DP i j is what because there is only exactly one way to reach that position which is our initial States otherwise let's check what if I is equal to 0 and the J is greater than zero it means that we are in the first row like here or here the robot can only move horizontally from the left cell like from here to here so in this case VPI J is equal to DP I J minus 1. which means the value of the cell is equal to the value of its left one otherwise let's check the case where J is equal to zero and I is greater than zero it means we are in the First Column like here or here the robot can only move vertically from the upper cell like from here to here so in this case BPI J is equal to DPI minus one Jake otherwise I would be greater than 0 and J would be greater than zero in this case the value of DP will be the addition of two parts the first parts will be the value of its upper cell and the second Parts would be the value of its left cell because we can only reach the position I J from these two cells and after that we just return DPM minus 1 and -1 minus 1 and -1 minus 1 and -1 and that is the number of unique paths to reach position M minus 1 and -1 which is the bottom M minus 1 and -1 which is the bottom M minus 1 and -1 which is the bottom right cell and that's it you can see that this algorithm is pretty efficient I hope you find this video helpful and gain a good understanding of the problem and its solution feel free to implement the code yourself and explore further if you have any questions please let me know in the comments below if you like this video please give it a thumbs up and subscribe to it'll be really helpful for me to continue this channel thanks for watching and happy coding bye
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
816
welcome to mazelico challenge today's problem is ambiguous coordinates we had some two dimensional coordinates like one comma three or two comma 0.5 comma three or two comma 0.5 comma three or two comma 0.5 then we removed all commas decimal points and spaces and ended up with a string s return a list of strings representing all possibilities for what our original coordinates could have been so our original representation never had any extraneous zeros so we can't have numbers like zero point zero 0.00 1.0 basically anything that can be 0.00 1.0 basically anything that can be 0.00 1.0 basically anything that can be represented in a more simple way we don't have any numbers like that so also a decimal point within a number never occurs without at least one digit occurring before it so we won't have numbers like 0.1 we'll have to have at numbers like 0.1 we'll have to have at numbers like 0.1 we'll have to have at least 0.1 or 1.1 whatever 0.1 or 1.1 whatever 0.1 or 1.1 whatever now the final answer can be returned in any order that's good also note all coordinates and the final answer have exactly one space between them meaning the space is right here but okay whatever um so if we're given like one two three as an example like how many possible ways can we divide this up well we can solve this like pretty straight forwardly there's no real trick it's just a matter of how we can figure out whether the numbers are valid or not so what we'll do is uh first think about where the comma can exist now the comma has to be either right here or right here right so after we have that we have well here we have two distinct possibilities but we also need to figure out for each one of these numbers how many possibilities are there with this so like here with one there's only one but with two three we might have two three or we might have two point three so we're going to have like a nested for loop inside um let's start off by first simplifying our string because it has an open and closed parenthesis so what we'll do is just say i get the let's see from one to negative one and that should give us just one two three here okay now we want to get the length of the string and we want to do a for loop so for i in range of 1 through n we want to figure out where we can we put the commas right and here i'm just going to divide it up in two numbers we have the a and b the a is going to be s of up to the i and b is going to be what s from i to the end right so let's just print out the a and b and make sure this looks right as well and there we go we have like one two three or one two three right now we have to figure out how many different numbers can we make from these numbers each right so we'll have to do a nested for loop and we'll say okay for first in and i'm going to write a helper method here i'm going to call it unpack and say return to me a list of all the possible numbers where we can put a decimal point in between somewhere and we'll do the same thing here for second and unpack b and we basically just need to append to some sort of output the possible strings here uh all the possible combinations so output pen i'm going to use string format i'll just say let's see we have this and we're gonna have two numbers so we'll say format first seconds okay so now the key is to figure out how we can unpack this number with all the decimal points in there and this is where it gets tricky uh but if we uh at first i try to use like a converting to a float and then back to a string and i had some success with it but unfortunately because of the scientific notation that brought a lot of problems um so fortunately i had to look up some answers and see how other people's did it basically there's two steps here the first is to see if the number itself we can add to um if it's valid without any decimal point in between at all so without decimal point like how can we figure out if it's okay or not now also looking at the length of n here okay so without the decimal point if uh there's going to be two conditions we have to check for like if the x of let's see if the very beginning does not equal zero then we can definitely append because no matter what it is as long as there's not a zero in front we know that this number is valid uh but we also need to um if it's just a zero that would also count so if x the first number does not equal zero or x equals zero itself then we can append it to our list here so we'll say append the uh the x okay now we want to check to see all the decimal points in between so for i in range of one through n we are going to check um if we can put the decimal in between here and there's basically um the main thing we need to figure out is like from let's see x negative one as long as okay first this can't equal zero the very last digit if we want to put a decimal point in between and ends with zero that doesn't make any sense because we can simplify that uh and we also need to check um if the very like if up to the certain point equals zero here or x of zero does not equal zero if these conditions fit then we can add um our candidate which would be what uh let's see x to the i plus period plus x from i onward right we're gonna append this candidate to our temp now finally we can return our temp here and that should give us all the possible decimal numbers that we can have as well as no decimal one and then we'll just add that to our output and then we turn the output once we're finished here all right so let me see if this works okay that does look like it's working so submit it oh no okay oh okay um i mean that's i made that mistake before so let's try that again okay what am i missing up here one three twelve three oh i guess it's just a space that's concerned about yeah there we go okay so that was just a silly error with the space right there but the real hard part i found like everything else i was able to get on my own but it was this condition here to figure out how can we check to see if this number can be simplified in decimal format um so this works um you know it's kind of unintuitive and i think yeah i mean whatever it works so i definitely took some research to figure this out but uh but hey i'm sure there's some other methods but yeah that's the basic approach so yeah i think i'll send it here thanks for watching my channel remember do not trust me i know nothing
Ambiguous Coordinates
design-hashset
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Array,Hash Table,Linked List,Design,Hash Function
Easy
817,1337
97
hey everyone welcome back and let's write some more neat code today so today let's solve interleaving string so in this problem we're given a list of three strings well not really a list but we're given three strings s1 s2 and s3 and we just want to know a simple question can we form the string s3 by interleaving the strings s1 and s2 an interleaving string is basically when you take two strings and split them up into you know sub strings and then you add them together now they have a description over here but i kind of feel like this description actually just made things more complicated for me like with the absolute value difference being at most one you know taking these strings forming them together basically what we're saying is can we take the string one and string two split them into sub strings like you can see a string one is split into this one and notice how the relative order of these three is maintained that's very important and this other string was also split into two portions this one and the relative order of the characters was maintained you can see that this dbc goes in the front and the a goes at the end so the relative order is important but that's it we can split the strings in any way that we want and then add them together and we just want to know doing that can we form the third string so the first thing you might notice is well if we're taking the string splitting them of course the total number of characters has to match the total number of characters in string three and yes that's true it will have to match and in this case it does we have ten characters and the output in each of these strings is five plus five equals ten so once you kind of understand what an interleaving string actually is the logic of this problem isn't too complicated right for example we see that the first character in string three is a right so for sure we need at least one of the characters from s1 or s2 to start with an a right because we can't just take an a from the middle of one of these strings and then say okay we'll put that at the beginning because remember the relative order of each of these strings has to be maintained so at least one of them has to start with an a and we can see that the first string over here does start with an a right so it's kind of brute force we're just comparing the first positions of each of the charac of the input strings right so now we have a d and we can choose between an a and a d in either of the strings but we're looking for an a in the target string so we're going to again pick from the first string and we can cross that out so now we have another sub problem we have the remaining portion of this and the entire portion of this string right so and we're kind of just brute forcing it obviously if we got to a character such you know let's say at this position we had a z but you know when you look at both of the strings that we have neither of them have a z in that case it would basically mean it's impossible for us to continue at this point but what if we had the opposite what if we had a b over here and you can see that this position is also a b right and let's say we were looking for a b right so then which one of these are we gonna take the b from string two or the b from string one that's the back tracking or the brute force portion right we could take either of them so we pretty much have to make a decision in our decision tree that we are gonna choose both we're going to see if we do it either of these ways is it possible for us to take these two strings interleave them together to build the output string right because maybe one of the ways works but the other way doesn't we do have to try both of the ways but it turns out we can use a dynamic programming technique called caching where we can eliminate a bunch of repeated work so therefore the time complexity of the solution can actually be broken down to m times n where m is the size of one string and n is the size of the other string and you can actually instead of doing caching you can actually do a true dynamic programming solution that will also give you this time complexity i'll explain a little bit about both of those so let me just kind of show you what the decision tree for this problem would look like and then how we're actually going to do the caching so notice how we're going to start at the beginning of both of the strings and we're also going to start at the beginning of the third string right we're looking for this character can we get it from either of string one or string two right so that's kind of how our decision tree is gonna work we're gonna have one pointer let's call it i1 which is going to represent what position we're at in s1 and we're gonna have another pointer let's call it i two it's a little bit messy but i2 is gonna represent the position we're at in string two and we're gonna have a third pointer over here let's call it i3 right but do you notice that this pointer is always going to be the addition of i1 and i2 if we add these pointers together we're always going to get this one right because notice how you know they're both initially at zero right zero plus zero is going to equal zero which is the first one here if we increment one of them right if we take this pointer and shift it over here this is gonna be one so we're gonna take one plus zero add it together and we're gonna get at the position one which is gonna be over here and that makes sense because if we use a character from here that's gonna take up the character that's over here so that's kind of how the math works out so in reality we just have to keep track of two pointers the third pointer can be calculated for the position of this string so we start at the position zero the first zero indicates what position we're at over here second pointer indicates where we're at over here and we're going to compare so does this equal this character of course it does write d does not equal a but a equals a so we can shift our pointer over here and shift our pointer over here so in this case we didn't have to make two decisions we just had an easy job we just had to make one decision so let's call that uh one zero because we shifted our first pointer to the position one and now i'm going to go kind of fast because i think you probably get what we're going to do so once again this is the character that matches in string three so we can shift both of our pointers to the next position and once again we incremented the first pointer so we're going to be at two zero and in this case b does not match d but this character does so once again let's shift our pointers by one and in this case we shifted the second pointer so let's call that two one i don't really know why i'm drawing the decision tree like this but let's continue so in this case you can see we're looking for a b and we can get a b from this one or from this one right so that's gonna be two different decisions we finally have two different decisions we can either do three one or we can do two depending on how we do it so this is kind of where the complexity is going to come right and the worst case would be that we could make two decisions every single time so you can see that if we continue drawing this out the worst case time complexity for a particular uh decision tree could be 2 to the power of n plus m basically the total number of characters that we have but you can see that we might be repeating the same sub problem multiple times right how many different possible pairs of values could we even have like this well we could only have n different values in the first position we could have m different values in the second position that's where the time complexity n by m comes from so we can do this by caching i'm going to show you how we can do that in the coding portion so this will make sure that we have this many sub problems and if we repeat the same sum problem we can just do it in o of one time because we're going to be caching the result of that now what exactly is the value that we're going to be caching well for any particular sub problem like for either of these branches we want to know ultimately from here are we actually able to form the remaining portion of the result string so either it's going to be true or false right we're not storing a value like a number or anything we're going to be storing true or false for any of these and actually if we find a single true then we don't have to cache it because if we find a single true that means we are able to form the result string and then we can immediately return true by going back up to the root that we called this recursive function from so we discussed the memoization solution but let's go over the true dynamic programming solution which is going to be pretty similar to what we just talked about so just to quickly go over what was the base case in our recursive solution that we went over well what would happen if let's say the last uh pointer in the first string reached this position out of bounds and the pointer of string2 reached this position that would mean if we added them together we would get to the out of bounds position in s3 right so basically if both of the pointers become out of bound that's how you know we have reached the base case and in that case that means we built the resulting string and we can return true so when we go over to the dynamic programming solution take a look at this grid that i've drawn you might recognize this as a regular dynamic programming grid this is string one this is string two we multiplied them together because remember it's m by n that's what our cache is going to look like so i'm basically drawing what the cache looks like but you can see that this is the dimensions but i have one extra layer out here which is important in this problem remember what i just said if this if we're out of bounds in this string and we're out of bounds in this string that's going to lead us to this position so that's our base case we want to initialize this with a t for true and a particular value in this grid for example this one means that let's say we had this remaining portion of the string and we had this remaining portion of the string you can see that both of these together form a str form two different characters right two characters in total so what we're asking is if you look at the last two characters in our resulting string we want to know can these two characters a and c form this string a c right that's the target string that we're looking for can these two characters form it of course by looking at them you can tell yes they can form this string right but that's basically what we're going to be computing we're going to be doing that for every single cell in this 2d grid and yes we're even gonna have to calculate these out of bounds positions why is it that we have to do that because they're actually valid positions take a look at this position this means if we had zero characters from string one but we had a single character from string two meaning you know the character a can we form the last character of the target string well the last character on the target string is c this character is a so therefore we can't do that right so we have to put a false over here and similarly from this position we're looking at just these last two characters c a using these characters can we form the target string a c you might think yes but no we can't because remember the relative order of these characters has to match this first character c has to match this character but it doesn't so this is also going to be a false right and of course we would do the same thing for this position right computing this if we had a c from here but we had nothing from here in that case this is actually going to be a true because we have a value here for an arbitrary position like this let me just show you what's going to happen obviously this mat this is a b here and we have a b in this portion as well so if we take the indices of these which is two plus two we get to index four in our target string which is this target character right we're looking for a b now notice how either of these can get there if we used the b from this position like this b what would we do in that case well then we'd want to know okay we if we were able to get a b now does the result in the bottom position equal true why are we looking in the bottom position because we just used this b so we can't use it again we have to use these last two characters but we can use this first b if we want to because we didn't use it yet so in that case we would go down in the opposite case if we used this b we cross it out we can still use this one but we can only use two characters from here so in that case we would go to the right now if either of these in this case we can go in both directions if either the bottom neighbor is true or the right neighbor is true then we can put true in this position if they were both false then we can't put false if only then we can't put true if only one of them was true then we can also put true now let's dive into the coding portion so in the interest of time i'm just going to skip and show you what the memoization recursive solution looks like and then we're going to code up the dynamic programming solution so we do have a cache in this case it's going to be a hashmap and you can see we're passing in two pointers into our function just like we did in the drawing right and our base case is yes if i and j are out of bounds then we can return true that's one base case another base case is if this position has already been computed meaning it's already in the dynamic programming cache then we can just return the result now if that's not the case then we have to go into our recursive case you might not be able to tell but yes this is recursion because we're checking if i is still in bounds right because technically one of the strings could be out of bounds so if i is in bounds then we're gonna check does the character in string one i basically is the pointer for string one does that character match the target position we're looking at in string three like i said we're taking i plus j the two pointers adding them together to find the target character in string three so if the characters match then we're gonna take i and increment it by one right we're incrementing it by one because we're saying we just used the character from string one now the next two lines of code are the exact opposite if the string if the character if the pointer in string two is inbounds and that character in string two matches the target character then we're gonna take dfs and increment j by one saying we just used the character in string two and if that returns true then we can return true in either of these cases we don't have to cache that because if we find one valid result then we can immediately return true from the root function if neither of them return true then we have to dp cache this as false and then return false because we don't have to repeat the work again so that's the entire function i bet it's a little bit easier than you expected and then all we have to do is call dfs starting at the beginning of both strings 0. so now let's do the dp portion and the first thing i'm going to do is just make sure that the length of the strings add up to the length of the target string so if length of string two and string three add up to the length of string one then we can return false if they don't add up let me make that correction if they don't add up then we return false otherwise we can continue so otherwise we can actually uh basically so otherwise we can initialize our dp two-dimensional array i'm just our dp two-dimensional array i'm just our dp two-dimensional array i'm just going to copy paste that in the interest of time so remember we're just gonna initialize this as basically empty in other words we're gonna initialize everything as false and the dimensions are going to be basically the length of string one and string two plus one remember because we do need that outside layer so that's just what this is doing you could do this differently in other languages and for the out of bounds position like the out of bounds position in both strings string one and string two we want to initialize that corner value as true remember just like in the drawing position the drawing picture and i don't know if i mentioned this in the drawing but we are going to start at the bottom right corner and then work our way to the left and then work our way up row by row so that's what these two are uh these two for loops are indicating it's a nested loop we're starting at the bottom right working our way to the top left now the rest of this code is actually going to be very much borrowed from what we just did in the recursive solution so i'm actually just going to copy and paste these two lines to show you it's actually very similar to the recursive solution so what exactly do we need to change the same thing is true if i is in bounds because remember one of these strings could be one of these pointers could be out of bounds because we are uh computing some of those out-of-bound corner positions right so out-of-bound corner positions right so out-of-bound corner positions right so if i is still in bounds then we want to check okay does that character equal to the target character we're looking for if it does we don't want to compute dfs right but we want to know if the result of this is true but we can do that from our dp right we're not doing recursion we're just using our dp value and since we're computing this bottom up we know that the result of this will already be computed so instead of saying dfs let's change this to dp of i plus 1 and j so if this happens to be true then what are we going to do we're not going to return true right because we're not doing this recursively we're going to set dp of i and j whatever we're currently at in this for loop and then set it equal to true right again for these bottom two lines we're going to do the exact same so instead of calling dfs if j is still in bounds and the character at j equals the character we're looking for we're not going to call dfs we want to know is dp of these two pointers still true so we're going to say i dp of i and dp of j plus 1. if that's true then we can set our dp position to true it's possible that both of these if statements will execute that isn't a problem for us right we'll set it to true either way now if neither of these if statements executes we want to set our dp position equal to false but notice how we already initialized the entire 2d grid to false right so we actually don't need to do that third condition and i know i kind of pretty much just cheated by copy and pasting a bunch of this but that's the entire code i'm not kidding so once you do that nested for loop we can just return the result of dp at position zero that's the entire code so yes this solution works it's efficient and we just and i just showed you how to solve it in two different ways so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
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
1,848
all right so this question is minimum distance to Target element so giv integer array and Target value and the star value so what you need to do is you want to find the index I such that nums I equal to Target and absolute I minus star is minimized and return absolute I minus of star so um yeah so this question is actually pretty straightforward so I'm just going to start it and then yeah we'll figure it out so minimum me just say mean all right it's going to be I'm going to say equal to integ max value and what I need to do is I just return mean so I'll have to triers array so this is pretty straightforward I Travers I check the condition if uh num equal to Target so if num to Target and so and this guy right and absolute right math absolute I minus ST which is what uh less than mean right so we'll update the mean less than mean and then we'll update the mean equal to uh absolute I minus St all right absolute I math absolute IUS St so this is something is actually trivial um should be trivial should be so cool so what you need to do is look at what is the problem so the problem is actually redant is actually saying num C Target and this is absolute I minus star and you want to make sure you keep updating your mean if mean is um if mean is greater than this and num cycle Target right and then you want to reset I minus start absolute so time is going to be all of space is only be constant so this will be a solution and I'll see you later bye
Minimum Distance to the Target Element
sum-of-unique-elements
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], target = 5, start = 3 **Output:** 1 **Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. **Example 2:** **Input:** nums = \[1\], target = 1, start = 0 **Output:** 0 **Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. **Example 3:** **Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0 **Output:** 0 **Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `0 <= start < nums.length` * `target` is in `nums`.
Use a dictionary to count the frequency of each number.
Array,Hash Table,Counting
Easy
null
953
hello everyone welcome to the channel today's question is verifying an alien dictionary if you are new to this channel please consider subscribing we sold a lot of intrusion on this channel and that can definitely help you with your interview the question says we Argan with words and order and we need to return true if the words are sorted Lexie Oh graphically according to the given order if you look at example number one we are given with words hello and lip code and if we look at H and L it come before L according to order that means we need to return true and if we see example number two we are you knew the words word world and row so first of all we will compare these two words world and world if we see W and W both are same okay we move on to oh and OH both are same we move on to our and our both are same now we come to D and L and we found that L come before D note D before L that means we will return false now we come to example number three we are given with Apple and F we are in with in order we will compare a and a both are same in the same way we will compare P and when we come to L we found that we don't have any word after P in the app and if there is any scenario in which the first word is longer than the second word in that case we need written false because in any dictionary a smaller word come before the longer word so let's move on to pen and people and let's see how we can solve this question after that we will write the code so I have taken the example given in the question and after looking at the question our first task is how to check the position of H and L so that we can compare whether s come before L or not the easiest way to do that is we will take our order and we'll put it in the dictionary both the alphabets as a key and their index as a value after putting the order in a dictionary our dictionary will look like this and now we can take H and L we can compare the values and from there we can see where the H come before L Oh God so now we are done with our first task so now we will take a for loop in the range of length of word minus 1 for I in range length of words minus 1 and our word one will gonna be words at index I and our word two will gonna be words at index I plus 1 and according to this what one will gonna be hello and were two will gonna be lead code now we will take another loop for K in range of minimum of length of word 1 and length of word too and why we are doing so that we will load get out of the range because as you see in example number three they can be possibilities when a word is smaller than other word or you can say what one is smaller than word - can say what one is smaller than word - can say what one is smaller than word - or what - is smaller than world one so or what - is smaller than world one so or what - is smaller than world one so that's why we are taking the range of the smaller length now if word 1k it's not equal to word 2k if this is the case that means I am saying a is not equal to a then what we're gonna do we will if dict word one K is greater than DECT word 2k10 we will written for let's see the situation in the exam suppose if we swept these words late code will become the first word and hello will become the second word and order remains the same so in this case the value of L is 1 and value of H is 2 so our 1 is greater than 0 so in this case we will return false but in the first example this is not the case we are returning true and if both of the word are same then what we're gonna do we will simply gonna break out of the book and if the length of word 1 is greater than length of word 2 in that case we'll gonna return false and if it's not false that means it's true so at the end we can put a condition of written true so this was the solution for this question let's see the code alright let's see the code first of all we will make a empty dictionary and we will insert all the elements from the order to the dictionary element of the order as the key and their index as a value so this is a way we can do that then we will take a for loop in the range of length of word minus 1 and we will define our word 1 and word 2 then again we take a for loop in the range of lengths of smaller work and if a element of what one is not equal to the element of word - then we will compare their value in - then we will compare their value in - then we will compare their value in the dictionary and if the value of particular element of word one is greater than the particular element of word - in that case we will return false word - in that case we will return false word - in that case we will return false else we will come out of the loop and if there is any scenario where the length of what one is guilt then length of word - in that case we will return false else - in that case we will return false else - in that case we will return false else in the end we will return true so this was the code if you will copy this code and paste it on leet code it will definitely gonna work thank you so much guys for watching the video if you liked the video please give it a thumbs up and help us to grow please don't forget to subscribe
Verifying an Alien Dictionary
reverse-only-letters
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Two Pointers,String
Easy
null
1,817
hello everyone welcome to another video now in this video we are going to look at another arrays medium level question now this question it is about arrays it is in the arrays tag but it is more of a hashmap hash site kind of question okay now without wasting any time let's jump into the question what it says and then we'll look at the how we are going to solve this so I have already written the example the first example over here so what we have given here is that the first we are given this array okay I'm sorry each array has another array of two values first is the ID okay and the second is the minutes what is this minutes this is this shows that this particular minute the user was active which user the user with ID 0. so you can see we have uh ID 0 at three places so ID 0 user with ID 0 was active at 2 5 and 5 minutes okay similarly the user with id1 was active at 2 and activate three now what does this have to do with all our question so basically what we have to find over here is that at how many unique minutes each user was active Okay and at that particular minute how many users were active okay it's a bit uh complex to understand so let's break it down so let's say uh let me write it over here how many users do we have zero and one okay now these are the users how many active minutes they had unique actors minutes okay user zero was activated five two and five so we have five two times okay so we are going to write it only one time so we have two and five now we have one is active at two and three so two and three okay so how many active units do we have for this user two for this user also two one and two okay so remember this we have two users with active minutes equals to two okay why this is important because we have to return an answer whose length is equals to K okay this is also given to us so let's say 0 1 2 I'm sorry 0 1 2 3 and 4. so okay so one two three four five this is supposed to be one indexed okay this is important because this is uh this will be helped this will be helpful for us when we are putting our values back into the array our answer if we take it if we mistakenly take it as zero then our answer will be wrong so make sure you take care of this one index array okay now why what how do we have to fill this answer array okay so let's see this is index one two three four and five okay so we have to see at one minute this is minute let's consider this as minute at minute one how many users were active do we have any unique minute one okay no we do not have okay do we have any minute to okay we have two unique minutes two okay how many users were active one two so we'll write it here two okay now do we have any three over here no okay so we'll keep it as zero four no five no one no so this is our answer okay we need to find the total number of users whose unique active minutes total of unique active minutes is equal to the index of this array okay let's take another example it will be easier okay the example number two we will take it is one two and we have two and three okay let me remove this as well okay and what is the K over here uh four okay so we'll take it sorry K is equal to four okay now we have these IDs one two so total ID we have one and two okay when was one active only at index One n was 2 active two and three okay if it was like this 2 and 3 then also we would have taken only one time three because we need unique minutes okay I'm sorry now how many unique minutes user ID 1 was active one how many unique minutes usually I need two was active one and two okay two so we have this foreign that we are going to return this is going to be 1 2 3 and 4. okay this is one index second index third index and fourth index so at you how many users have unique active units total one okay we have one only here so we'll write one how many users had unique active minutes too okay so we have two here only okay so how many users we have only one okay only user ID 2 has total unique active minutes equals to two so we'll write it as one okay three we do not have any four so this is our answer okay it's really simple and you have to like you can go through the question once and you can it will be very easy to understand the words are given very smoothly and uh very in simplistic manner okay so yeah I hope you understood this so how are you going to solve this okay so since we are dealing a lot with unique right okay so what is the one thing that comes to our mind when we say unique or distinct or something like that so it is set okay set will help us to give us the unique values okay now one more thing that you can see here is that we were finding the unique activities for that particular ID so for 0 we had 2 and 5 for 1 we had two and three now this looks something like a map okay we are mapping these values okay to this IDs okay so we will be also using math okay but I'm sorry here if you will see we want only unique values so for this we'll be using set okay so what we'll do is that we will find we'll create a map which will map the ID to that set of unique minutes okay so ID is going to be 0 will be mapped to the set um two and five one will be mapped to 2 and 3 okay at the end what we'll do is that we will check the size of this particular map okay and whatever the size that we get we will increment that value in our answer array okay so let's say it is 2 the size is 2 also we need to take care is that we need one indexed array right so for that what we'll do whatever value size we get will minus 1 decrement this so like they are asking for one index okay so technically it should be here value should be here but in our arrays it whatever it is given even if we are given two India is there the computer will take it zero indexed only we have to uh organize it in that way so computer will always take it as zero index okay so for two index we need to put it at one index that's why we are going to uh negate one value with from this uh size okay so that it comes to the particular position I hope you understood this and it is quite easy if not then you can continue to look at the code so without wasting any time let's jump into the code now okay so the first thing that we need over here is our final result right so let me create that so this is going to be the result whose size is going to be K okay next thing that we need is our hash map and the first value is going to be the integer the second value that is going to be a set okay set of integer okay our map is ready now let's go through our array which is the logs okay so I'll be using like uh for each Loop okay you can use Simple loop as well now here what we need to find we first need to find the set that we are going to add into our map okay so for that let me create that but this is not going to be a normal set right will not be using like new or new hash set integer okay what we'll do is that we will get it from our map okay but this will not be a simple gate okay we have another method get or default okay because we are not sure like we have any value or not yet okay so what we'll do get or default okay if we have our value okay then we'll get it otherwise we'll create a new hash okay now why are we doing this because let me show you over here okay uh let it be you tell me in the comments like why are we doing it like this because I have already made a video on I've already done a problem with the similar approach okay and if you have seen this and if you know about hash set and hashmap the functions that we have of hashmap okay then you tell me why I am doing like this and not by using simple uh creating a new hash set okay now what we'll do we'll simply add our temp of zero value I'm sorry Tempo one value okay which one value this is our temp of one okay and what we'll do is map and I will put it back to at index temp of 0 and what set it's that easy now that our set is ready and it is back in the map all our values are ready what we'll do is that we'll go through our values okay our hash set user with a set only okay we'll go through that map Dot values okay this will give us the second value this is a dictionary right map is like a dictionary we have a key and value elements so we are getting the value okay and what we'll do is that our result in that result at what index the size of our set and as I said it is one index so we are going to negate one value and we'll increment this okay and we'll finally return our result why are we incrementing this because whatever value we find let's say 0 and 1 we had 2 5 2 and 3 okay now this is 2 and this is also 2. we have answer equals to something okay now first we find this two so we'll increment this and again we find two willing to find this okay it will be like that so our task is done the code is done let me submit this okay so it was that easy and yeah I hope you understood This and like this it was very simple and as I said it is not very hard it is it should not even be in the medium level question it should be in the easy level question but uh you know we have it so that's that so yeah I hope you understood This and like this and uh you know get to learn something new so thank you for watching and do let me know if you have any other problems for me to solve from any other platform I will see you in the next one till then keep coding
Finding the Users Active Minutes
calculate-money-in-leetcode-bank
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Math
Easy
null
138
hey everyone this is this site hope you're doing well so let's start with the question so the question is copy list with random pointer okay so again a linked list question so you're given a linked list of length n is given such that each node contains an additional random pointer okay so there is an additional random pointer which will point to any node in the list or can be null okay so what you have to do you have to construct a deep copy of the list so deep copy is basically you have to create a new nodes again and the next pointer points to a new node again and the random pointer also points to a new node again so if you see like for example if there are two nodes x and y in the origin where x dot random points to y then for the corresponding two nodes x and y is in the copied list okay so you have to return the head of the copied linked list okay so let's see with an example okay so let's take this example so we have given this 7 then it's next pointing to 13 it's next pointing to 11 and 10 after this it's 0.21 and after and 10 after this it's 0.21 and after and 10 after this it's 0.21 and after this it point to null okay so this is for the next and for the random so it's saying 7 is pointing to null okay so random is point at here okay now 13 is pointing to 0th index so 0th will be this then you see where 11 is pointing to 4 your 10 is pointing to 2 okay and 1 will point to 0. okay so as you can see this single direct is next pointer and this going in that this direction it's a random point okay uh if it is a simple straightforward linked list let's say it's just like 7 13 11 and one then we can easily create one temporary node and just do the copy create a new node and then point to next node similarly we will do for all but in this case we have random pointer also okay so because of random one second so because of random pointer i need to check whether that linked list or like whether that node is already created or not okay so let's take this example so we'll create a new note 7 okay and we will say the next is point to this okay so next we'll point to this we'll create a new node for this okay now it's saying random pointer point to some node null okay so how can i check but let's say in this case it's a null so let's assume we point it to a null okay now you will go further you will do like 13 next is pointing to 11 so you will create a next new node you will point it next now it's saying random pointer points to 7 okay now seven how can you confirm whether seven is already great or not like what you can do is you can create a new node like by pointing a seven a new node but how but seven is already rated okay so how can you identify whether it is already stored or not okay so for this what we can do is we can create some sort of a map okay so we can take a map and whenever some node is created we will insert that okay so whenever we need the same node again what we will do we will take it from the map and if the new node if let's say this is eight okay then eight should be created new otherwise if it is seven take that previous seven and point it here okay so let's see the approach okay so let's see the previous approach with an example so what we will do we will create a map of node type and this node like this key will be a previous node like this current node okay this head and new will be created so it's a deep copy okay so what we will do we will take a variable from here we will take a current from here okay so every time we need to check three things okay first thing we need to check whether this node is present in the map okay then second thing we need to check whether it's next is present in the map and the third thing is whether it's random pointer is present in map or not okay so let's see so we will start from here what we will do first we will check okay is 7 is present in map so we will check 7 so there is no element in it so 7 is not present so what we will do we will insert first 7 this node okay 7 and we'll create a new node of the same value so this will be a new node okay so this will be stored here now we'll check for its uh next element okay so we'll check for 13 okay so 13 is also not present so it will do we will insert 13 and we'll create a 13 new node okay similarly we will check its random pointer so random pointer is null so if any element is point to null uh will not insert it okay so what it will do so what we will do we will create we will we have already create a node in the map now we will get it from the map so we will get we will do like we will take our or let's say new element is equal to map dot get current okay so we get this element what we will do new node will take this element as like this so we'll get this seven okay after this what we will do new node dot next equal to map dot get current dot next same for random map dot get current dot number okay so current is pointing to seven so current dot next turn out next is 13 okay so we'll check for 13 so 13 we will get it so we will take it like this 13 will be there then we check for its random is pointing to null so it will give us null only okay so this will be pointing to a null element okay well after this will increase our current so we always do these three steps okay so current is now at here okay so first step we need to check whether 13 is already present or not because we don't need to create it again so as you can see 13 is already present in the map after this what we will do we will insert its next and random element if it is not present in the map so 13 next is 11 okay so we'll check in the map 11 is present no it is not present so we'll insert 11 previous like old node and create a new node 11 okay similarly we check for uh it's random so it's random is seven so we'll check seven is already present so we'll not do anything now we do this three step okay so first we get this element map dot get so we get this 13 okay after this we point its next element to map dot get current dot next to current is pointing to 39 and its next is 11 so we'll take this node 11 okay and we'll take its random variable also so random is pointing to current dot random so current dot random is 13 random is seven okay so we'll take this from the map and we'll point it now we'll move further okay so current is here okay so we'll check for 11 first 11 is present yes it's present so first it's done so we'll check for its next okay so it's next is 10 so first step is to insert or if it is not present so we'll insert it so we'll create a new node okay now we check for its random so it's random is one okay so we'll check whether one is present or not so one is also not present so we'll insert it okay after this what we will do we will get it from the map okay so we have insert current next and random in the map okay so now if we will get this new node so we'll get this new node so this is 11 current so this 11 is come here now we'll assign it next so it's next will be current.next so it's next will be and 10 is already present so we'll take this 10 okay now we'll check for its random so random we have already inserted we will get it and we will insert point it okay after this we'll move further our current okay so we will again check for 10 whether 10 is present you know so as you can see 10 is so 10 is already present so this is the use of taking a map because we don't have to create it again if the same node is present okay so 10 is already present okay so we'll take it and we'll assign it's next and random so first we'll need to check whether this next is present so next is also present and it's random is 11 so this is also present okay so we'll assign it's next so 10 pointing to next okay and it's random will be 11. after this we'll increase our current okay again we'll check whether this is present so this is present okay it's next pointing to null okay so we'll point it to a null and it's random will be pointing to seven okay so seven we already created in the map we will get it so seven okay so these are some steps to complete a deep copy with random variable okay so the time complexity for this we are going for only one uh over one iteration so it's a order of n and there's a length of linked list and the space we are taking a map and map will insert all the nodes so that is also order of n okay so let's write the code okay so what we need a map of node and map equal to new hash map okay we'll need a current variable so node current equal to head okay while your current is not equal to node we'll do something okay so what we will do we need to check whether if current if map dot contains key this current okay if it is not present what we will do we will insert into the map dot put current then create a new node dot value okay after this we need to insert its next and random also so first what we will do we will check current dot next is not equal to null so this is necessary because we will not consider null element and map dot contains key current dot next we'll put in the map dot put current dot next new node current dot next dot value okay so we'll do the same step for random also if current dot random is not equal to null and it is also not present in the map we'll insert into the map also okay map dot what current dot random new node current dot random dot value okay so we have inserted into the map after this what we need to do we need to assign the next and random to the new value okay so we'll take it from the map node newnode map dot get this current okay assign the next equal to map dot get current dot next similarly assign then random map dot get uh current dot random okay after this what we will do will move further our current okay so we'll insert all the element into the map and it's next and random is also done after this we written map dot get add okay so head will have the latest uh the starting element okay so let's run the let's run it so as you can see this is accepted let's submit it so our code is submitted hope you like it thank you for watching my video
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
69
hey everyone today we'll be doing another League core 69 square root X in this problem we will be just finding the square root of a given number but we cannot use any built-in number but we cannot use any built-in number but we cannot use any built-in functions uh that's it straightforward problem but if you encounter a case like this like X is equal to 8 we will be just returning the ignoring the decimal points and just returning the ground value so to do that we will just be using the binary search and comparing if the midpoint square root is midpoint and multiply it with itself and we will be getting the square root if we are not getting the square root we will compare it if it is greater than the given number of quality if it is less than the given number and if it is less if it is greater than the given number then we will be decrementing our end and it will be an and vice versa we will be incrementing star if it is not greater than so will be pointing uh we will be first checking if x is equal to 0 X is equal to 1 we will just return X and like I said we will be using as uh two pointers one at the very beginning and one at the very end to do binary search and this will be X so now we will start our while loop while less while star start is less than equal to n we will let me give you an example like in the case of 8 we will be comparing glass two and finding the midpoint which will be for taking the square of 4 is 16 so which is obvious that 16 is way higher than 8 so which will be um decrementing midpoint and then adding it to end so this will be our next uh midpoint and now we'll find it between these four numbers and we will do this whole process again and again until we find the exact number so if a maid will have it will have midpoint uh start and divided by 2 and now sqr will hold the square root made multiply by made and if square root is equal to the given number then we will just return mid because made at this point is holding the value of for in case of 16 you can say or in case of not 16 in case of 4 you can say 2 will be the midpoint and we'll be getting our square rooted square root value at the very first step like this so if not uh if square root is less than x we will add made plus one and then so and we will be saving the value of made because we are not going to exit our loop from here uh to exit our Loop we will be making and less than start in else case made minus 1 and if we return answer the are good to go I think so there is a question why I made answer is equal to Mid here but not here this is because um and at this location Loop will not exit for example start will be 2 and may end will be to Loop will not exit Loop will be exited in The Next Step but in the next step the value of will be lost we will not have the value of mid so I am saving in it uh answer and that's it let's see if there are any errors so there are no errors and oh I okay they ignored it I was thinking this will give an error and that's it
Sqrt(x)
sqrtx
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well. You **must not use** any built-in exponent function or operator. * For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python. **Example 1:** **Input:** x = 4 **Output:** 2 **Explanation:** The square root of 4 is 2, so we return 2. **Example 2:** **Input:** x = 8 **Output:** 2 **Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. **Constraints:** * `0 <= x <= 231 - 1`
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
Math,Binary Search
Easy
50,367
516
hey there and welcome to another B code video So today we're going to be doing uh problem number 516 longest palindromic subsequence and we are saying find the longest pound dromic substance subsequence in the word we have and the difference between this and a substring so let me show you real quick here let's just do this so if we have um let's see okay there it is yeah okay so if we have this the longest palindromic substring has to be continuous so it would have to be this and so let's think of how we would do that first so let's say this problem was the longest boundaromic substrain set of subsequent so think of how we would do this well I think this is actually another problem so you can look that up but I'm just going to explain how to quickly do something like that and then we can figure out what changes we'd have to make to do this so what we can do for that if it has to be a continuous sequence of letters is we can actually start at every single location at every single letter and at every single spot between the letters so let's say we started at this uh let's say we started this location B we can simply expand a left and right and check if we're out of bounds or not and if the two characters are equal and that means that we still have a palindrome and we can keep expanding and keep expanding until we don't so in this case we're out of bounds so we wouldn't have a palindrome rate so then we can start here now and we would expand out okay so that works then we expand out again and we can't so the longest is this so that's our longest so far then same thing we start at this B and then this wouldn't work so we would stop we started to say this would work then we're out of bounds so this is the longest and now the other thing that would give us all our odd ones right like if we start add a letter and we expand out it's going to be like one plus or sorry one plus two so it'll give you only odds and for evens what you need to do is you actually need to start at a left and a right letter and so it would be like this you'd start at every two adjacent letters so you'd start here you'd be like okay that works expand out can't okay then you'd start at these two letters expand out can't these two letters these are already not equal so it doesn't work and then these two letters and they're already not equal and that's how you get every single unique or that's how you would get the longest palindromic substring now for a subsequence we are allowed to actually get rid of letters at any point as long as our order is maintained so this is a palindrome because we can just chop out this letter and so what we would do with this is typically when you can drop out letters a good idea there's quite a bit of problems only code where you can do the subsequent this is and for most of them the answer is going to be dynamic programming and so what we would actually have to do is we would follow the same thing as the unique palindromic substring but instead we are going to start at every odd or even so let's say we have a left and a right which is the index of the left and the right letter right and so for the odds our left and right are going to be the same so let's say it's going to be left equals zero right equals zero they're going to be the same and then all we do for a I'm going to talk about the recursive solution but this lead code problem is kind of annoying because there are cursive solution the dynamic programming recursive solution actually doesn't pass so then I'll talk about the trick you need to have it pass or the other way you can have it passed so there is a solution let's say we start with these right and we can just have a for Loop for every single letter and for every single combination of letters and so let's start these and we'll say okay if they're equal then all we have to do is do one plus and then we Branch out right so then when we Branch out now our L becomes negative one and then we're out of bound so that's going to be kind of like a base case whenever we're out of bounds we're just going to return zero so we're going to Branch out then the substring starting here is going to be one because our recursive case will be zero now let's say we start here so same thing we're going to do one plus we're gonna go over here and go over here now this is uh zero and this is 2 because this is index one so then we could say okay are they if your two letters are equal it's pretty straightforward you just do one plus and then you do the next recursive K so in this case they're equal you do the next recursive case and we're out of bounds again so we can't do anything there we can't skip something or for out of bounds so that's going to be that one now let's say we start here so let's try to do this again so we go here and here okay they're not equal so we would have a one originally right because this would be equal to itself but when we Branch out these are not equal and so what we'd have to do is we'd have to actually try to skipping either one and seeing what's our max value going to be right and so let's say we skip this a so instead of branching out twice pretty much or sorry if they're not equal what we need to do is we need to try to go over here and that's going to be one case where B is this or this is the right this is the left and then the other case is we keep this a but then we Branch out over here so this is the right and this is the left and so you can see kind of anytime they're not equal we would just do the max of going left or right so we'd keep one index the same but then we'd we would go out with the other one and if they are equal then we just do one plus we go left and right and there are other problems like this like uh longest common sub string I think or longest common sequence and this is that's kind of the problem we're going to quote up and so the problem we're going to code up is going to be similar to the recursive solution for this except that recursive solution for this doesn't like I said doesn't pass only code so we're going to code up something else and we're going to do a little trick and so actually if you can tell by the way so remember we you can either start at one letter that being the same so left and right are both one letter or the other case when we do this uh loop we can start what would be our actual optimal solution here so our optimal solution would look something like this our left would be one and then our right would be two right so we're going to try every single possible we're gonna go we're gonna try left and right equals zero one two three four five and then we're going to also try left equals zero right equals one and then left equals one right equals two and so on to get every single odd and even so this would be the case for an even and so left is here right is here so let's just look through this real quick how the recursive dynamic programming solution would look so here we would have a b and a b so we would do one plus remember and then we would Branch out so then our left becomes zero and our right becomes three then we would say okay so actually this wouldn't be one plus by the way um so if what we would actually have to do is if the left and the right are different and they're equal it would actually be two plus right because it's two letters but if the let if the left and the right are the same and they're equal then it would be one plus so that's a simple thing you can do in the minimization where if you're left right and they're the same letter then you do one plus and if they're two different letters they need to do two plus but anyway so this is zero this is three now they're not equal so remember we can branch in either direction so let's try to Branch left okay so we try to Branch left we're out of bounds so that's going to be one of our base cases where if we're out of bounds we are just going to return zero so it's going to be some Max right of the left and the right so the left is going to give us zero so that doesn't work well now let's try to Branch instead of to this a let's try to branch of this B okay well this so now we're going to be at this index and those are equal and they're two different ones so then it's going to be Max of zero and two so it's going to be 2 plus 2. and then the other thing you can do is you can actually cache all these different indices and so the number of different indices you can have here is let's say the length of the string is s all of these index can be up to length s so be S squared so the complexity of the memorization solution would actually be S squared and the complexity of the next solution I'm going to show you is also s squared but the problem is just the way they have the uh the whatever they're testing on a leak code the minimization doesn't pass but actually if you do want to code this memorization and you want to code up the true dynamic programming solution that does fasten the code but let me show you the other way and this is actually going to be easier to code and it's like another problem so instead of doing that let's do this right so let's uh let's take this bbab again and what do we know for a palindrome well a palindrome is equal to its reverse right so what we can actually use we can reverse a string so the reverse would be B A BBB right okay and what we can do is we can actually do a longest common subsequence on this not just a pound dromic but a longest common subsequence and let me just go over longest common subsequence really quickly so actually let me just uh redraw this a little bit so make it better so BBB a b and then the reverse is b a b okay so now oh it uh it's pretty straightforward what to do in a longest common subsequence so all we do is we start at this index so we're going to have the same thing we're going to have two different uh two different values so let's just call this top and let's call this bottom let's say okay and they're both going to start zero and then our cases are first of all our base case if one of these is out of bounds then obviously like let's say our top index is here then obviously the longest common subsequence can't be any bigger so that's going to be that's going to turn zero so if any one of these is out of bounds that's our base case and then we're going to turn zero now we're going to compare the two and if they are the same exact letter then we're going to include that inner subsequence and so that's pretty straightforward right so like these two should be the same exact letter so we're going to include them so then we're going to do same thing we're going to do one plus right then we're going to be over here as our next two letters now if they're not the same we're going to make a choice we're either going to move here or move here and so let's see what that would look like right so let's say and then we're going to get the maximum so they're not equal so let's say we move this top one well let me move this top one it's still not equal to a and then now we can move this right and then clearly you can see that this is not going to be our best solution because the most times these can be equal is twice now so that's going to be a problem so that's not going to be what we're going to want to do we're actually so the optimal solution is actually going to instead of moving this top one is we're going to move this bottom one and so we're going to move this bottom one and yeah once again so if they're not equal we just say Max of let's say top plus one the DP of that or bottom plus one right we move one or the other and we just return the max but let's say we move this bottom one now these two are equal okay perfect so now we're going to have one plus one then we're going to move them both so now they're going to be over here we're going to they're going to be equal again one plus one again now we are here and so once again we can move either one so if we move this then we are out of bound so that would be the worst solution but instead we'd want to move this and then this would be equal to this so we do one plus one so I'm going to code this up and then it'll be a little bit more straightforward um on how it works but basically yeah all you need to do is you need to do a reverse of the string and then you just need to do a longest common substring and the longest common substring of a string in its reverse is going to be guaranteed to be the most common pal the longest com uh the longest palindronic subsequence and you can try a few different equations you can try a few different um substrings to and see that and then you can um you can show it to yourself that's the case and even if you do have something and it's reverse right like let's say we have this and then we have CBA or let's just say we have some letters in here right so ZX whatever CBA so you might think that like oh well if I reverse this string now these will match and there's going to be an issue well really what's going to happen is it's going to be like this right so then there's going to be some stuff here whatever and then uh ABC right or it's actually going to be no it's going to be CBA as well here I believe and so the longest uh let me see if that's right actually ABC so this would actually be ABC as well I believe yeah and so the longest common subsequence even though these do match is actually going to be this and so even though there is a reverse if you take this stuff out in the middle then this whole thing is also a palindrome so basically no matter what you do even if you do have some string and it's reverse in the actual original string it'll be fine and so let's actually code this up and then I'll show you it'll make a lot more sense once we're coaching it up so we're going to code up remember we're going to code up um the longest common subsequence that so and you can actually find that problem only code as well but this is going to be the code for that so what we need to do first of all is we need to do have this reverse ring so let's just say rev s equals s and then that's just going to be this reverse I think I believe you can do that so let's just try to print that just to make sure let's just return one or something for now okay so b e b a b and then yes this is the reverse okay perfect that's what we wanted now we do need to have a memoization array because this is going to be a memoization solution and yeah this is going to be the same time complexity as this original one where we did have the left and the right but this one passes on Lee code so technically it should be the same time complexity just the way they have the uh the questions one pass and one doesn't so it's pretty close Okay so now what we need to do is have the visited same as usual for memorization now we just need to code up the DP right so deftp remember we're going to have two indices we're gonna have the top index on the right and the bottom so we'll just call it top and bottom Maybe okay and remember that our base case is when we're out of bounds on either of them so if top is greater than or equal to Len s so technically actually yeah so these should be the same length so we can just oh well but that doesn't really matter so this is just return zero and then so if top is greater than or equal to or bottom is greater than or equal to remember little s is going to be the same length as res so we can just do this or rev s okay so we can return zero now our other case is if our index has already been checked and that's also important because you can get to the same index multiple times and you're going to have a lot of repeated work because if you have differing indices that can happen right so if you have like um I don't know let's just say like a b c d and then you have EF GH so they'll start here but on the neck remember you get to move one of them so let's say you move this one then you move this one you're going to be here but you can also move it the other way right so you can move this one then you move this one so you're going to be at the same place and it doesn't really matter how you got to these two indices as long as they're the same like the previous work doesn't matter for the DP Okay so let's just make sure we do that so if top bottom and visited then we're going to return that set top bottom okay now remember if the Le if the letters at the current index are the same for longest common sub uh substring we are going to add one because we're always going to take that because we can always since we're popping other letters the optimal solution is just always going to be greedy where if the two letters are the same we're always going to take that so we're just going to say or as equals um zero and then we're going to say actually we're going to say res equals yeah zero and then we're going to have multiple cases here so if um s top equals and then this is Rev s bottom then we are always going to just do res equals 1 plus the biggest one right so we're going to try to or sorry it's not going to be the biggest one so here when they're equal we're going to just do one plus and we're going to move them both right so if these two are equal we're going to move them both we're not going to move one or the other we're only going to move one or the other if they're not equal so then we just do DP of top plus one bottom plus one okay else now we try to move each one so res equals Max of DP top plus one bottom now we try to move the other one it's a DP top bottom plus one then we just uh cache that right so I visited top bottom this res return whereas now we just call our DP and we return that right so return DP and we're going to start at index zero for both okay let's try that okay so that did work but yeah you can code up the other Dynamic for or the other Dynamic program resolution but honestly once you realize that this is the reverse once you know this trick I think coding up the um longest common substring is also just more intuitive than this palindrome where you are starting at the difference between this palindrome is you would have to have a for loop as well right so you'd have to have like four I in a Range Len s you would have to pass in I and then you'd also have to pass in I and I plus one you have to pass in all these combinations because I and I would give you the odd and then this would give you the even so you'd have to do so if you did code up the other one that's what you'd have to do okay so let's think about the time and space complexity for this one all right so time so how many states can we possibly have so we can have this top in this bottom and top can be length s and bottom can be length that's and we have it memorized so we're never going to be doing the same work multiple times right once we compute any one of these we're gonna be done so the most possible cases we have is N squared here which would be n is the length of s space so this same thing can also be completely full so if this visit is completely full every state we have is N squared okay so it's going to be an N squared solution and hopefully that makes sense to you and if you have any questions leave them in the comments and if you want to try the uh the memorization with the left and the right pointers and see that fails and then you can also try to code up the actual true dynamic programming solution for that one and that would actually passively code so that would be a good challenge to do if you're Rusty with bottom-up memorization you're Rusty with bottom-up memorization you're Rusty with bottom-up memorization or bottom-up dynamic programming and if or bottom-up dynamic programming and if or bottom-up dynamic programming and if you want me to do an actual uh how to do that I can do that in another video so can you please um like And subscribe this video If you like this content and I'll see in the next one thank you
Longest Palindromic Subsequence
longest-palindromic-subsequence
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`. A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** s = "bbbab " **Output:** 4 **Explanation:** One possible longest palindromic subsequence is "bbbb ". **Example 2:** **Input:** s = "cbbd " **Output:** 2 **Explanation:** One possible longest palindromic subsequence is "bb ". **Constraints:** * `1 <= s.length <= 1000` * `s` consists only of lowercase English letters.
null
String,Dynamic Programming
Medium
5,647,730,1250,1822,1897,2130
67
hey guys let's take a look at this easy 167 ad battery we're given two binary strings like 1 we need to return the Sun also binary string the string both non empty and contains only captures 1 was 0 so this well this just a similar as the previous question we did it's 66 please take a look at there which means we only need to handle the carry over yeah so actually we can just create a new array and a some of them up and some each digits of them and yeah and handle the carry over that's very pretty straightforward yeah let's do that's carry over 0 right and left result equals how long is it so mm-hmm this would be a question so mm-hmm this would be a question so mm-hmm this would be a question so let's say and N equals a not man anyway let's result equals array and it would be mass max but the longer one after your string right okay fill them with 0 okay so let's I equals mmm okay let's we should do something like this let's max land at the polls this an addition as a result to all zeros and 0 and let equal zero means the index of the digits from right left so while I is while I am smaller because it's zero so it's more than tax some because some would be we don't know which array is bigger which part which is number is bigger so you will say a dot n minus I or is it or 0 if it might be undefined right or it says some respect a zero smother zero then it should be zero which score if not it should be a like this nice one to take this it was the same for B okay be okay so results max then cleanse I equals sum divided by R by 2 the only chance that's that okay let's say it's some yeah it smart body by two they should be zero or one so and the carryover would be some divided by one awesome by to your son is to name Terry page one don't forget carry over yay I got it so now all the digits are some to the maximum end of the longer string length of longer string right yeah and now we check if there's carry over there you still carry over again zero oh yeah Oh however this yeah it's updated all the time one or zero it's okay so this day we should all shift to one then finally we join there is nothing of time complexity in this problem just some just how we handle the carry over I think you should were for God to floss I forgot to floss plus increment I my bad code hmm not a number what okay if it's uh oh maybe should be minus one I'm told mm-hmm still we max is too right so here mm-hmm still we max is too right so here mm-hmm still we max is too right so here is them zero then I will be 1 0 to 1 we updated Oh here is the problem mmm it seems okay cool were accepted actually this problem is not difficult but just pay attention to the index that then thing mimics takes and attention to the extra carryover when all the iteration is done so that's all for this one see you next time bye
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
1,781
so lead care 1781 sum of beauty of all sub strings so the beauty of a string is the difference between the most frequent character and the least frequent characters counts so for example the beauty of this is three because you have three a's minus one because you only have one b which is the least frequent character and that's equal to true and now you're given a string s and you need to return the sum of beauty of all of its substrings okay so the way we're going to solve this is we're going to loop through all of the substrings and add to our result the beauty of the substring and then we're going to return the result so here's how we're going to do that so first of all we split our string with nothing so now we have an array of characters and we map that array of characters to their character code normalized with the character code of the smallest letter in our alphabet so we only have lowercase english letters so the smallest letter is a and so now we have just an array of character codes perfect now we're also going to have our result which is going to be the sum of beauty of all of these substrings and then we're going to later on return this variable so this is going to be our return variable and now we also need a count array that basically counts the character code instances so the frequency of a given character code and the english alphabet length is only 26 so we just need 26 cells and we fill them with zero so this is going to be our counting data structure perfect now we can do our two nested loops so that we get all of the substrings of s and keep in mind this can only be done because the constraints are pretty low so we only have 500 at most length perfect so now we have our two nested loops the first one just a normal for loop then we for every uh for every outer loop we always want to fill our account array back with the original value so we always want to reset to zero and now what we can do is we can have our nested loop that goes through all of the characters in our substring and what it needs to do is it needs to update the count of the current character and then update the result with the beauty of the current substring that we are looking at okay so first of all we increment the frequency the count of the current charter that we are looking at and then we update the result with the beauty of the current substring that we are looking at so we add to the result the difference between the maximum value of a frequency and the minimum value of a frequency and here a common mistake is to forget that here we actually need to filter the frequencies because we don't want this to always result in a zero so for example if you have a string abcd or something like that if you just keep the code like this then the beauty would be calculated as one because for example you have zero charges of z of the letter z and so what you actually want to do is you want to calculate the minimum of the characters that appear at least once so you want to filter this count and you want to only have the charters that appear at least once you don't have to do that here because of course there is at least one that appears once and so that's actually it so i'll submit the solution to show you that it works and the time complexity is o of n squared because you have two nested loops on the same array with two different indices and you should also mention that there's also a factor of the length of the alphabet so this max function here is looping through 26 cells so truly this would be 26 times n and the space complexity is just the space to store the string and the count array so it's o of n where n is the length of the string plus o of k where k is the length of the alphabet so that's it for me today thank you for watching and bye
Sum of Beauty of All Substrings
check-if-two-string-arrays-are-equivalent
The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters. * For example, the beauty of `"abaacc "` is `3 - 1 = 2`. Given a string `s`, return _the sum of **beauty** of all of its substrings._ **Example 1:** **Input:** s = "aabcb " **Output:** 5 **Explanation:** The substrings with non-zero beauty are \[ "aab ", "aabc ", "aabcb ", "abcb ", "bcb "\], each with beauty equal to 1. **Example 2:** **Input:** s = "aabcbaa " **Output:** 17 **Constraints:** * `1 <= s.length <= 500` * `s` consists of only lowercase English letters.
Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same.
Array,String
Easy
2184
42
hello everyone welcome back to algorithms simplified today we are going over leak code number 42 trapping rainwater first let's go over the question itself so in the description of leak code this is what it says given n non-negative integers representing an non-negative integers representing an non-negative integers representing an elevation map where the width of each bar is one compute how much water it can trap after raining i find that this is a little ambiguous and is a little hard to interpret so i put it in my own words for your convenience essentially what they're asking is that you're given some sort of input and it's an integer array let's call it h for now and for every single index value pair in h the index plus one column so because we start at index zero so the first the second and third column is value units tall by one unit wide so if we have one if we have some sort of like one two three as h then that means the first column is one unit tall second column is two units tall and the third column is three units tall that's basically what it means and because we are working with units here um obviously the value has to be non-negative because we're not working non-negative because we're not working non-negative because we're not working in some other sort of dimension here we're working with the real numbers and real dimensions right here the output is an integer so the question asks for the total unit squared of rainwater that the columns h can hold so let's go over an example to see exactly how this works here i've just drawn up a graph according to the example given in lead code example number one you can go on and look at it yourself so these are the numbers given in the array and these represents the heights and underneath i've written the indices and here i've just drawn up a little graph to represent what this means so the bar number one two three four five six seven eight nine ten element twelve represents the index plus one position for example at the first bar there is zero units tall at the second bar it is one unit tall for the third bar it is zero units tall so on and so forth and this right here is our graph or map and now the question is saying that there is rain water so some sort of rain is coming down and there's a very heavy rain so it pretty much covered everything it's asking between the boundaries of these columns right here how many units of water can it hold so should water come down it would come here because there is a gap between the second and fourth column that allows water to be trapped here there is none because there's nothing left of column one to support the water for here we have all this area right here covered with rain water and here we have this covered with rain water and however this cannot be covered with rainwater because there is no wall here to hold up any water so in total if we were given this h right here our number that we should return should be one two three four five six so we should return six so now that we understand what the problem is asking let's go over what the brute force solution might look like look at its limitations and see if we can make any observations to make it more efficient to reach our final solution so a brute force solution would be something as follows so every single column we're going to keep going forward adding up every single unit so every single difference between its current height and the next unit over or next column over until we hit another column that is equal to or greater than the current column's height or we reach the end so let me illustrate what the sign of brute force would look like so we start at uh the first column and we keep going forward until we reach column two but because column two is larger than or equal to the height at column one we stop and in total we have zero units because that is the dimension of the height at column one okay now that we have reached column two we're going to keep going forward well column three is shorter than column two so we keep going forward we hit column four we see that there is exactly one unit at column three that can hold the water so we add one at column four we do the same thing well here at column five there it there is a column but it is shorter than column four so it can't catch any of the water so we add 1 unit so the difference between the column 4's height and column 5's height and then for column 6 the difference between the two heights is two units and for column seven we keep going because it's indeed still shorter than column four so that's one more unit until we reach column eight and now you might be thinking wait a minute that's really efficient you're not wasting any of your time going forward however that just happened to be the case for the first two columns here when we reach column eight our highest or tallest column if we do the same maneuvers say i'm gonna use a different color now let's use pink so here i would you know color here i would count this in until i reached the end and realized hey there's nothing that's going to be able to hold all this rain water up so everything i did starting from column eight is completely useless i just wasted all my time doing these calculations so i need to go all the way back and then start at column nine and keep going forward and then so on so forth well in this case this sort of brute force algorithm for this example might not be too bad because there are such a limited number of columns that we can traverse and there's i guess only a few calculations that we make that are extra but since we're talking about if we're talking about worst case analysis what if the kind of the bar looked like this you know like so then in that case using that same algorithm i starting at this column i would keep adding everything until the end oh no there's nothing there it's zero let's go back to the next column do the same thing it's zero go back to the next column so on so forth in that case we would have a o of n for every single calculation after a certain column and we need to repeat this n times so our brew force is o of n squared so let's write this right here o of n squared this is very slow well the main issue with you see the brute force method it's not necessarily the calculation in the difference between the heights it's the fact that we don't know if there necessarily is a column after the column we're currently at that can indeed hold the water now if we are sure that for some column we are at there is indeed something taller than it then we don't need to worry and we can keep moving forward and we can make sure that we won't reach the end and do all these extra calculations for nothing one very interesting thing that can help us with the solution is realizing that no matter if we go left to right so in increasing index order or decreasing index order the calculation for the rain water should be the same because these are column structures whether we count this way or that way shouldn't affect the total area of water that can be held how can this help us well say we are at some column let's say we are say traversing this way left to right and we are at some column here on the other hand i'm at another column some other column in the graph and i'm traveling this way well it has to be that one bar between the two of these has to be the taller one or the equal one right so let's say for argument's sake that this is indeed the taller one and this is the shorter one in that case i do not need to worry and from this column right here i can keep traveling doing the same thing we did in brute force knowing full well that i am able to hit at least one column that can hold the water that i'm calculating because either there's going to exist some other column here that we're going to hit first that's taller than or equal to the column orange or we're going to be able to hit t or the purple pink column as a guarantee and this is true conversely because if say was the other way around orange being the taller one and uh pink being the shorter one then we can travel instead left to right doing the same calculations knowing for sure that there is indeed a wall at least one wall afterwards to quote unquote catch all the rain water that we've been accumulating up until then well what does this mean this means that because we have guaranteed a way to not need to come back to the next column over redo calculations come back we can guarantee that we only need to go to each column once in order to calculate the total amount of rain water accumulated great so let's put this more efficient algorithm and visualize it on our same example so here as before let's have two pointers one starting at each end and traversing towards the other end so as before i'm going to have a pointer here starting at the first column and then another column or another pointer for a column at the other side the end which is going to travel this way and the orange one is going to travel this way let's see if indeed we only need to travel to each column once so now we compare first we compare the values between the first column and the 12th column because that's where our pointers are well we see that the first column is shorter than the last column so we know that if we travel forward from the first column we are not scared of needing to undo our calculations because there is at least one wall afterwards that can catch the rain water at column one well we keep going from column one and since we get to column two and there is a wall or a column that is taller than the height at column one we stop and we see that since there were zero units between them we don't add anything to the total so let's keep a count of a total right here now let's compare again well again you know orange if it travels forward since it's the exact same height as the column at the pink pointer we know for sure that there is something there to catch the rainwater should at least one column so we don't need to undo any calculations again we keep moving forward we move to column three we see that column three between it and column two there is a one unit gap so we add that to our total and then we move forward from column three to column four and we stop because column four is taller than column two and we've hit something that's a retaining wall now when we compare between the two pointers again we see that the pink pointer or the column right here is shorter than the column at the orange pointer so we know that there exists at least a wall specifically at the orange pointer that is going to be able to catch all the calculations leftward of the pink pointer wall so we have no fear of going leftward with the orange pointer so we go leftward and we meet 11 and since it's taller and there's zero units between those two we don't add anything to the total now comparing the two again we see that you know we can go either way but for the sake of uh you know consistency for between column four and column eleven since they're equal we know that column four at least has column 11 to catch it so we're not scared of needing to redo calculations we keep going forward we reach call we reach column five we see that there's a one unit difference we add that to the total and then we keep going forward column six we add that to the total that's two more one two and then here we go to column seven we add one more that's five and then we reach column eight between column eight and column eleven so where our pointers at we see that 11 is shorter than column eight so we travel leftward from the pink pointer knowing full well that there is at least one wall to catch it so we move leftward from pink to column 10 we see that there is indeed one unit of water that we can catch so we add one more so total is now six and move forward to column nine from column nine uh from column nine and column a we compare two we see that column nine is shorter than column eight so we move forward knowing full well we can reach something so now that we've reached column eight and we have nothing to add we see that the two pointers are overlapping so they're on the same column now so do we have to keep moving forward no we don't because no matter where these two meet either somewhere in the middle like this or it could be that you know say the first column was the tallest and they end up meeting at the end or the last was the tallest and they ended up meeting at this end we know that we have traversed the entire graph of columns with each column being calculated for the rain water so since we traversed each column once and each addition so each adding and subtracting is o of one we know that this algorithm is only o of n so that's our solution so right before i head into the coding part of the solution if you've made it to this far in the video and you like the content you see please do consider subscribing and liking the video so that i can make better content for you now without further ado the coding solution so as we described before let's first initiate or initialize some variables let's have left index and right index as the pointers to the front and the end of the list respectively next let's have a pointer column height this variable is going to refer to the column that we are counting the rain water from so we initialize that to zero but let me comment so the height of the shorter column we are moving from great and total rainwater we will initialize that to zero great so while left index and the right index have not met yet now there are two possibilities if the left index's value is less than or equal to right index's value so height of the right index we know that so we know that there exists at least one column right of left index that can catch our rainwater you know there's two possibilities here either we have reached a column that catches water or we have reached a starting column that is about to catch the water so if the pointer column height so that refers to the height from which we're counting from is greater than or equal to the height at the left index we know that we're actually counting the water difference between the two so total water is going to add the value of the column we are counting from minus the height of the bar or the column that we're currently over so let's comment that so this is when we have yet to reach a column to catch water and the next possibility is that we have reached a starting column and what i mean by that is this is a column in which we start counting from because if you know say over here we have uh we were you know here at the left pointer and now all of a sudden we reach this column right here that's a starting column that is larger then we know that we actually have to reset the pointer column height to the value that we're currently at so height of left index great and no matter what happens we have to advance the pointer in order to not get stuck in the while loop so left index we move rightward so increasing index there we go and for the sake of simplicity i am going to you know it's mirrored on the other side so i'm going to copy this here and i'll change this we know that so in this case if the height on the right side is left in the height on the left side for the pointers then we know that there exists at least one column left of the right index that can catch our rainwater so if the pointer column height so the height we're counting from is greater than or equal to the right index we have yet to ha reach a water or reach a column to catch the water so we add the difference between the two and here we're going to use this instead of left index great and otherwise we have reached a starting column let's add the word column because starting is a little difficult to understand there we go a starting column so what that means is we need to update the pointer column height to the current height and then we advance the right index forward now some of you might be thinking wait a minute why do we have the same variable to represent the heights we are counting from for both the left side and the right side pointers moving different directions well if you think about it we're only advancing from the shorter or equal between the two of the pointers therefore the pointer column height which refers to the column we are moving from has to be the short height of the shorter column we are moving from so it doesn't matter if even if we had two variables uh one referring to the left column pointer's height and right column pointers height it wouldn't really make a difference we actually end up wasting a little more space okay great so now that we have done that remember to return the total rain water at the end now let's submit and see if that works oh total water oh i guess i named it total water instead of total rain water so let's do total rain water submit great
Trapping Rain Water
trapping-rain-water
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. **Example 1:** **Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\] **Output:** 6 **Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped. **Example 2:** **Input:** height = \[4,2,0,3,2,5\] **Output:** 9 **Constraints:** * `n == height.length` * `1 <= n <= 2 * 104` * `0 <= height[i] <= 105`
null
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
11,238,407,756
338
foreign and we've returned an array of ants of length n plus one such that for each eye from 0 to n and of I is the number of ones in the binary representation of n so we're given this example with the input as n equals two so basically we have to find the number of ones for every number starting from zero all the way up to n equals two so zero one two for each of those numbers we have to find the number of ones for each of those digits so that's what it represents so if n is equal to two then we have to return an array of n plus one where each of those indexes are the number which we have to actually find the number of ones in its own binary representation so let's get started so as always I'd like to start by identifying what the input is in this case the input is an integer and we're going to take the example as n equals two and then we'll identify what the output is here the output is going to be an array of n plus one number integers in the array and let's also look at the let's also understand what the constraints are to this problem so our constraints to this problem provided constraints is going to be the N is from 0 to 10 to the five so that is our provided constraint and so the number of numbers is going to be n plus one which is in this case is going to also maybe 10 to D5 we also have like try to like um shoot for a specific time complexity and space complexity so in this case our time complexity we can try to like shoot for uh what we have and we haven't we have n so that means n plus ones we'll try like shoot for a Time complexity of O of n plus one which is basically all of n and um and then after that our state complexity will try we definitely have to return an array so we'll have to have n plus one space being accumulated okay so let's try to understand the logic behind this so the logic for the problem we are given a number n which is two so basically we are going from zero all the way until like two so we're basically we're iterating zero one two so what is actually happening is for each of these numbers so zero in binary Alpha the reposition is going to be zero let's say we're uh yeah we're just taking four spaces four decimal four binary spaces in so zero is going to be represented in this form and one is going to be represented as zero one and then two is going to be represented as zero one zero so this is our zero this is our one and this is our two so what the output that we're returning is going to be the number of ones in each of these binary representations um that's what our operator is going to be so zero and so there are zero ones in the first in zero and there's going to be on one uh one in our binary representation of one and then there's only going to be one in the binary position of two so let's understand how we're actually trying how we can actually do this so how do we do this so what we're going to do is we're first going to create an array of um zeros an array of n plus one zeros because our n is our the total number so we're going from zero and zero n and since arrays are zero index we have to start from zero so n Plus One will give you the total length of the desired output array and after starting with zeros what we have to do is um what we have to do here is as we're iterating through it we can use since we're using python what we can do is we can use a method called like bit count this will actually count the number of one bits for each of those numbers which is which in this case is going to be 0 1 2. so zero is the zero one two is the decimal representation of each of those numbers are those like specified places so if we apply the bit count method for each of those numbers which is zero one two it would return the number of ones in each of those spaces for zero it's going to be zero four and it's going to be one and for two hours it's going to be one and then we will just returning the end we'll just like return the array so let's get started on coding this so let's get started by coding this so the very first thing we'll we're going to do here is we're going to define the array so the array is going to be uh n plus one zeros and so that's how you define n plus 1 0. in Python and then we're going to iterate through um the length of that array so for Num in range Len of array um now in this what are we going to do we're going to say array of num is equal to num dot bit count okay now that will assign the number of ones associated with that specific number and then just return that so towards the end we just have to return the array uh yeah so that's pretty much it uh let's free let's see if this actually works yeah so there you know it actually works let's try to submit it as you can see it's pretty efficient and memory wise it's probably not as efficient um that's because we're actually defining actually we actually have an array of LinkedIn we can always make it more efficient by using a dynamic programming approach which I can explain in the next video but we can try to run this again you can probably it'll probably be a little bit more efficient memory wise there you go it's a bit more efficient memory wise now but if you want to make it even more efficient there's another approach of doing dynamic programming which I can explain in another video but thank you so much for watching and I hope you have a great rest of your day
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
417
hey everyone today we are going to solve the question Pacific Atlantic water flow so this is a very long description so let me summarize it so we get a 2d metrix so we can think this metrix as a island and there is a Pacific Ocean and Atlantic Ocean and the island receives a lot of rain so you can think each number is like a height of water and then uh we need to identify all the point in the metrix from where water can flow to both the Pacific Ocean and Atlantic Ocean so we can assume that the water can only flow from a high higher cell to lower cell and not basser and we can also assume that the water can flow on any like Direction like up down left right so uh let's see example so okay let's say we are now five if water um goes up so there a three so current uh height of water is higher than um next uh height of water in that case the water can flow like this okay from three so let's see the right side of um water and the height of water is four and the current height of water is three in this case we cannot the water cannot go right because uh right cell is higher than current cell so we can't go right okay so let me explain with this example so to solve this question I use a breast fastar so my strategy is that um so look at this position and this position so what I can definitely reach the Pacific Ocean from this position because these positions are next to Pacific Ocean so we use this position as a starting point for breast F search so as I explained earlier um so water can flow from like a higher position to lower position so but we start from these H places so that means if current position is lower than next position that means water can flow from next position to uh current position right yes so same thing from three uh if current position is lower than next position in that case water can flow from next position to current position right so actually we compare like opposite way so actually we do the same thing for Atlantic Ocean so for Atlantic Ocean uh we start from uh this uh red position and from this red position for same reason these red positions are next to Atlantic Ocean so we start from uh J's position and then um in the end um we want to create two metrics one is for Pacific Ocean and uh showing like a what position uh can reach the Pacific Ocean so the other metrics is for Atlantic Ocean and showing the what position can Le the atan equation and finally uh we uh check the each position in the B metrix if both metrix has like a two at some position in that case uh the position from that position uh water can flow both ocean so let's um let's see the one example so um we start from one so as I explained earlier so we start from hge places so if current position is lower than next position so that means water can flow from like a next position to current position like this and then um again we check the current position and the next position if current position is lower than next position that means uh water can uh move from next position to uh current position like this so from five so look at uh green arrows and red arrows so from five water can flow um to the like a edge of um metrix like a two until two and one so that means from five the water can reach both ocean so that means this position is a one of answers and let's see the forse case quickly so from three um so next position is lower than U three so that means uh in the metrix of Atlantic Ocean there is a two at this position but uh let's look at the Pacific Ocean so to reach Pacific Ocean there is two ways um like up or left but uh both numbers are greater than three so that means water cannot uh flow from three to 5 3 to four so we water cannot go to next position so that means from three uh water cannot uh reach the Pacific Ocean so uh in the metcs of Pacific Ocean so this position should be false so in the end um when we look at the same position in the both matric so Pacific Ocean is false and Atlantic Ocean is true in that case uh that is not answer we have to find the position where the water can reach uh to the B um ocean so from this position uh water can reach Atlantic Ocean only so that means uh this is a false case yeah so that is a basic idea to Sol this question without being said let's get into the code okay so let's write the code first of all um if not Heights in that case just return empty list and first of all calculate the number of rows and the number of columns so rows and the columns equal length of height and length of heights and zero and next so we follow the uh these comments so first of all uh initialize the um Pacific and Atlantic breast SE Q with a border points so this is a little bit complicated but uh so how can we do that so we use a DQ so from collections import DQ and uh let's say Pacific Q equal DQ and uh I and zero so and the four I in range and uh length of rows so this create like a partical edges and then um plus so we uh create a so horizontal position edges so um zero and the J 4 J in range and start from one to L of colums so we do the same thing for atantic Q so atic Q equal DQ and uh I and course minus one um and uh four I in L and rows and plus rows minus one and J for J in range and the course minus one yes and then after that I'll use uh bre search to mark all position uh reable from uh Pacific and Atlantic Ocean so pafic equal bre such and passing the Pacific q and the height Matrix height and then um we do the same thing atantic reavel umal and atantic Q and height okay so let's create a like a PR pass such def bre pass such and taking a Q and metrix and first of all create a visited list equal all positions are initialized with false multiply columns for underscore in range and the rows and uh we need a directions so we need four directions so that's why first of all one zero and I'll copy this and minus one Z or 0 one or 0 minus one so we need four directions and then uh so check the Q and if Q has a data so first of all um pop the very left data so row that is row and columns column so Q do pop left and then first of all Mark the current question so visit it and the row and the columnal call through and then oops check all other J sent point so for Direction X and the direction Y in directions and uh so let's say um new row and new column equal low plus DX and colum Plus Dy if uh the adjacent point is uh not visited and is higher or at the same um height in that case add new position to the Q add a new position to the Q so if uh zero greater than equal new row and uh less than rows and zero greater than or equal a new column and less than course and then not visit it new row and uh new colum and the Matrix new row and then new column is greater than or equal Matrix and a row and a column Corum in that case um add Q to a pend and a new row and then new column and then uh visit it new row and a new column equal to yeah uh and then just visit it and then uh finally we implement this um comments find the intersection of two reachable sets so first of all um initialize a result variable with empt list and then so um for I in lens um number of a number of rows and then for J in range uh number of columns and then as I explain earlier if Pacific um L um current position in Pacific and then um current position in Atlantic atantic if uh both metrics have a true in that case that is one of answers so let do append and uh I and J and then after that return result variable yeah so let me submit it yeah looks good and very efficient algorithm so beta 90 or beta 94 for memory so time complexity of this solution should be order of M multiply n so M and N are like a dimensions of input metrix so we visit each Place once so that's why order of M multiply n so space complexity is also order of M multiply n so to like a store the two reachable Matrix so that's why order of M multiply n yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Pacific Atlantic Water Flow
pacific-atlantic-water-flow
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`. The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_. **Example 1:** **Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\] **Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\] **Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below: \[0,4\]: \[0,4\] -> Pacific Ocean \[0,4\] -> Atlantic Ocean \[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,3\] -> \[1,4\] -> Atlantic Ocean \[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,4\] -> Atlantic Ocean \[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean \[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean \[3,0\]: \[3,0\] -> Pacific Ocean \[3,0\] -> \[4,0\] -> Atlantic Ocean \[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean \[3,1\] -> \[4,1\] -> Atlantic Ocean \[4,0\]: \[4,0\] -> Pacific Ocean \[4,0\] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. **Example 2:** **Input:** heights = \[\[1\]\] **Output:** \[\[0,0\]\] **Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans. **Constraints:** * `m == heights.length` * `n == heights[r].length` * `1 <= m, n <= 200` * `0 <= heights[r][c] <= 105`
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
24
lead call Fortune 24 swap notes in pairs give a linked list swap every two adjacent nodes and return its head you must solve the problem without modifying the values in the list node that is only nodes themselves may be changed in this first example there are two pairs the first pair and the second pair so in this case original linked list one two three four becomes two one four three after the swap one swap was two and then three swap with four so the idea for solving it is first we need to have a dummy node so that's a common technique for link the list so just points to the Head node just points to the Head node just points to the Head node just points to the handout of the linked list and then for this case we need to have a previous pointer and then current pointer so basically previous pointer points to the previous node and then the current pointer or points to the current node so this current node is always the first node for each pair that we are going to swap so the reason why we need the premise node is so for the for example when we move to the second pair so we need and then this nose three becomes the current node now suppose we already finished swapping the first pair that we swap node one with node two and now we are moving to consider the second pair and then the current points to the node three that is the first node in each pair current points to know three and then we during the swap this node 3 is previous node should points to the node 4 instead so in that case we need to know the current nose previous node so that's why we need to keep track of it that's why we are using a previous node and then for the swap let's go over the process after we have a we initialize the dummy so we have the linked list let's use example one so dummy points to 1 and 2 and 3 and 4. for the first operation basically we make dominoes point to the node 2. instead of node 1. so instead after this operation let's say we have dummy points to node 2 and then no 3 and 4. the last two notes now changed and then we have the node one also points to node two so node 1. next is node 2. and then after that let's do another operation so in this operation we points node one two notes node one's not next two no three so instead of pointing to node two so Node 1 is 0.203 node two so Node 1 is 0.203 node two so Node 1 is 0.203 so this is the uh link this is these are the notes after this operation so basically got dummy two three four and then we get the this node one point to the Note 3 so node 1.x is node three Note 3 so node 1.x is node three Note 3 so node 1.x is node three and then after that we make another operation that is no two point no to the next node for node two is node one install node three so basically no two dot next is node one instead of node three so in this case we swap the first pair and then we can move on to swap for the next pair so this is the logic for solving this problem let's start coding so we need to have a dummy node so that means this node and then the value is just zero and then the next is just the head because is the head because is the head because is the head and then we initialize previous and then the current so for the previous node it's just the Domino and then for the current node it adjusts the first the head of the LinkedIn list and then after initialization since we need to consider for every pair in this linked list so that's why we wrap this operation inside the while loop so well current node and then also current down next that means okay we at least have two nodes that week as well if you only have one note then there is no need to swap okay in order to get a for the first operation that is dummy the next so dummy it's our previous so previous style next here's the no two so no two is curved down next so here we need to know so basically it is current using this example this current when we switch when we swap the first pair this card is just the first node and then this current.x current.x current.x in just second note and then for the first operation we make dummy points to Note 2 instead of node one so in that case that means next we adjust the second note that is current.nex and the second note that is current.nex and the second note that is current.nex and then since we want to do this apply same logic for it and repair so basically this Dom is represented as the previous we just use the first uh first pair as an example to go through this logic and then for the second operation we need to change this first notes next node so in that case the first note is current and then curve next node current next node is just the third node instead of the second node so the third node is represented by current.next.x so in this case we make the first notes next to be the third node and then the third node is just so remember current is the first node the current down X is the second node and then the third node is just current dot next and then after that we change the next node of the second node from the Note 3 to this node 2. to this node 1. basically we change the second node's next note from the third node to the first node so in that case the second note right now is represented by previous dot next so basically here previous downloads is the second node and then we change the next node the reason why is basically right now one thing you need to change is originally the second node is the but since we have is the but since we have is the but since we have already updated current.x so in this already updated current.x so in this already updated current.x so in this case the second node here just previous dot next the reason why is because we have original we have already updated the current.x so in this case current.x so in this case current.x so in this case the current on X is no longer the second node instead we have already swapped it to the right location so that is the previous dot next so the next note of that is just previous dot next that should be the third node and then we have not updated the third node yet so in that case external still count down next on x and then after that last update the previous and the current node to move on to the next pair so initially previously just dummy node and right now when we are doing the update we want to update the previous to be the first the second node foreign to be the third node so the second node after Swap this the second note after swap already been changed so that's why the second node is no longer current down next but it's current because we swap the uh the nose the first node with the second node already swapped and then the third node is just currently done next so after that we just return the head of this linked list so we'll return dummy down next oh my bad this is this should be current on X because this is already on X because this is already on X because this is already been updated so okay let me see so is so okay let me see so is so okay let me see so is current.nex this is second note right so this thumb so the Hat should be the second note so that's what this does and then the second note's next note should be the third note so that's why current I have the next is Cardinal next and then by this point we already updated previous dot next and the current.x current.x current.x so in that case we want to the second note of the second note should point to the second note in this case should point to the first node instead of the third node so in that case it should point to the current node so this so I made a mistake here so basically what are we are trying to do this one is here we are trying to go from this uh online 28 and 29 to the linked list on line 34. so in that case we just need to change the next node of the second node from node 3 to node one so in that case the second node because it's already been updated to the uh to the current location so in our case the second node is just represented by previous down next time previous dot next so that's the second node and then the second notes next note should points to the first node the original the uh the original first node that is the current node okay so this solution is accepted so for this solution you answer because it's a little bit tricky so you need to make sure the order for the swap is done correctly so let's go over let's choose these three steps one more time okay basically the first step dummy points to the second note instead of the first node so we update so dummy done next so that is previous dot next we update it to the second node the second note right now is still represented by current down X and then after that we need to update the first nodes next to the third node so in that case the first node right now is still represented by current because this current has not been updated yet so we can still represent the first node by this current so current.next this current so current.next this current so current.next the next note for current node is just the third node and then in this step the second note next note should become the should be the first node instead of the third node so that's why for the second note it should be previous down next dot next that's the second note snacks so second notes right now is represented by previous Dawn next and then it's next node it just originally the first node that is the current node so I know this solution is a little bit tricky but you can see this is how it works so another more I would say a more intuitive way for writing this out is to use some temporary variables to store the node so let me change the code so in our case we just change those three operations so basically we are changing those three lines so what are we are changing those three lines too so basically first we need to actually store the node so let's store the second node the second note is just curves down next and then the third node that is curve down next so in a swap we store two temporary variables second node and third node so basically assign the original second node as their node to those two variables and then we will do the swap so in this case previous star next they're just the second node and then basically we points to the waypoints we make the SEC originally second node now the head of this new linked list and then after that we update the second note's next node we update the first node the originally first node's next node to be the third node so in our case we can update so original personal cards done next is just the third node and then for the third node so after that basically the second notes next node should be the first note so in that case second note down Max virtually let me use this one so see you previous dollar next on x it adjusts this uh adjust the first note that's the current note okay so this one remain unchanged so let me just run this one okay this solution is accepted so this solution is assertive but why we need those two uh dummy bear why we need those two variables second and third node so the beauty of this is okay if I'm writing it this way you can now tell the difference but what I can do right now is I can actually swap the sequence so the order of writing of doing the swap let's say here for this one let me just move right after here so in this case let me run the solution so now it's still accepted so in this case the point I want to illustrate is that okay if we are using some temporary variable second node and third node the other we are performing those swap operations can be changed so basically originally this line is the third operation but now we swap it to be the second operation we can do this with the help of the temporary variable but we cannot do this if we can if we do not store the second node and then the third node with the variable second note that second and third node
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[2,1,4,3\] **Example 2:** **Input:** head = \[\] **Output:** \[\] **Example 3:** **Input:** head = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. * `0 <= Node.val <= 100`
null
Linked List,Recursion
Medium
25,528
213
hey everyone today we're going to be doing another Elite code problem 213 house dropper 2. so let's read this problem your professional router planning throughout houses along the street each house has a certain amount of money stashed all houses displays a range in a circle let's pull open okay and that means the first house is neighbor of the last one meanwhile adjacent houses have a security system connected it will automatically contact the police if two houses are broken into on the same night giving it an injury nums representing the amount of money each house return the maximal amount of money you can rob tonight without alerting the police so this problem is an extension of house rubber one and the only difference between that and House robber number one is let's say we have this first example so we have two three two so in house rubber one these houses were connected like this where you couldn't Rob adjacent houses now the only thing they're adding is these two houses are connected as well so if you rob this house you can't Rob this house and so because the state of what you're doing is affected by what you choose you should be able to recognize that this is a dynamic programming problem and we're going to break it down and we're going to try to solve it in every way and we're going to see what this difference is so first what we're going to do is we're going to pretend that these houses aren't connected and we're going to figure out a way how to solve this problem and then we are going to figure out what changes we need when the two houses are connected so let's say first of all that these houses are connected like this how would we collect the most amount of money well in this case we would Rob two and then we would Rob 2 here so it would be a total of four and okay that's the case let's say it's this longer thing now what's the most we can rob well I think it would be this three and this one but how do we think of what to do how do we think of the way we're going to be robbing so what we want to do is we want to start at the end and then we want to make some kind of recursive case of how do we go backward to the front and then from there we'll figure out what to do and so the easiest way to do that I think is we want to have a base case and because we don't know if we're going to rob this house or whatever let's add another house at the end with zero and we're going to say that once we get to this index then we're done and so let's call this house last and this house second to last or something so or we can even call it first so let's call it first and last first here okay this number will be one now let's figure out the recursive case in the base case so here these are two houses so our value from robbing this house is zero now what's our value here when we're here well what do we want to do we know that this house is zero so the most we can Rob if we start oh by the way so this last means we start here and first means we start here so let's just say we start here and what do we want to do well we want to figure out what's the best thing we can do so obviously when this is when this last is zero we're going to want to Rob this house so the maximum we could drop here is one the maximum we can drop here is zero so let's just start writing these values down so let's say we have an array of all these elements so let's just say initialize it all to zero for now this is zero okay and we're going to say that this is last this is first okay so here we are definitely going to want to Rob this house because our two options are either Rob this house or don't Rob this house and so we know that this better throughout this house so we're going to change this value to 1. now what we're going to do is we're going to move these last and first back so we're going to do that we're going to move these back let's just say this is L this is f now let's say we're at these two houses what do what should we what could we do at this house we can either Rob this house but then we have to skip this house or we could skip this house and then go here and so what would we want to do well if we rob this house then we would get a value of 3 and then we have to skip this house and then we can add whatever is over here so this would be 3 plus 0 is over here it would actually be over here so we're saying we see we have to skip this house but then from once we get here we can do whatever we need to get the maximum from this point which is zero so if we rob this house we get three now if we don't Rob this house then we're here and then we get whatever the maximum we can rob starting at this house is which is one so we take the maximum of the two so it's either three or one so that gets a three now let's move these back again technically we don't even need if we have an array we don't even need a first and I'll ask we're just going to move this first or just the current location where we're at so actually let's call it instead of doing it that let's call it just C so now we're at here so now we can either Rob this house or we cannot Rob this house and then we're over here so if we rob this house sorry if we rob this house then we can rob this house and then take whatever values here if we don't Rob this house we can take whatever values here so let's try to Route this out so if we rob it we get 2 and then we get the value that's in here the maximum we can draw from here which would be one so it's two plus one which is three now if we don't Rob this house we get the maximum value which is here which is three so either way it's three so we're going to make it three okay we're going to go back and we are going to go back here and the same thing so we can either Rob this house and then take whatever value is here because this is the maximum we could drop starting at this location because you have to skip this one or we can not Rob this house and get whatever's here so let's try to Rob first so if we rob we get one then we get the max I'm starting this location which would be three so one plus three which is four or we skip this house and we get the maximum starting from here which is three so four or three we would want four and then four would be our output and let's just double check that so we rob here that would be four so you see at our recursive step is at each house we either Rob that house like let's say we have this array and we iterate it backwards at each step we either we have a Max of uh and let's say let's call this array let's call this the DP array and let's call this nums so we have a Max of nums at our current index so let's just call that c plus DP C plus two because we are robbing our current house then we're skipping a house then we're going to the next house and whatever is the max we can get from there is what we're getting or DP of C plus one so this is our recurrence relation for a general House robber problem where these two aren't connected and that would be yeah so if we don't Rob the house then we just get whatever's at DP at this next index so hopefully that makes sense where our choices either Rob this house and then get the max two houses forward or don't Rob this house and whatever we can get the max one house forward okay so what we're going to do here is we're going to try to code a memorization first for House robber and then we're going to code a true dynamic programming Solution by the way so for memorization let's see what that would look like as well so let's say this is for this one two three one let's say this is index 0 index one index two index three okay and let's see what that looks like so we start at index zero and we can either Rob the house or we can go past the house so it's going to be Max or let's say on the left we're going to rob the house so it's going to be nums at our current index so zero Plus DP at index two okay now if we don't Rob the house then it's going to be DP at index one and so this DP at index 2 now is going to do the same thing so it's going to go nums of two plus DP at four and then our last index here is actually yeah four sure okay and then this is going to be if we don't Rob the house starting at two it's just going to be DP of three and so we're going to keep doing this until we are out of bounds so let's say we do start at index two here which would be right here if we do Rob the house then we go here and if we're out of bounds and that's fine because that means it's zero so this is our recurrence relation with memoization we're going forward so we either we take the max of robbing the current house plus DP of two houses ahead or the DP of one house ahead so let's try to code this up for House robber and then we're going to see what we need to add to make it work for House robber 2. and by the way also uh with mobilization you're going to have repeated work so you're going to want to have some kind of thing to store our previous results because like this dp1 would be nums one plus dp3 but we're doing dp3 here as well so we're doing dp3 multiple times so we're just going to want to have minimization to make it faster so let's make a visited dictionary here and this is going to be the houses that we already robbed so we're going to call defdp and the only thing we need is the index that we're currently at and so what's our base case so let's look again so if we are at something like this like let's say we're at this last one and we robbed the house we get one if we don't Rob the house then we go here but we can just have our base case saying if index is greater than or equal to length nums that means there's nothing unless there's nothing left to Rob so we can return zero here okay now what else are we doing so if it's invisited we can also return that right so if index and visited return visited okay now remember our current relation is we try to rob the house that we're at and then we call dp2 houses ahead because we can't Rob the next one or we call DP on the house right after this one because in memorization we are going forward and with the dynamic programming solution we'll be going backward so right now we're going forward so we start at index zero we try to Rob index 0 and here or index one so let's do that I just have a res equals Max of nums I think we don't even need a res here this can just be a one-liner so I this can just be a one-liner so I this can just be a one-liner so I visited index equals Max nums index plus DP nums index plus two or DP of nums index Plus 1. so it figures out which one we do then we just return so this should and then once we call this DP on zero we can get our memorization solution so now let's figure out what we need to change so that would be a solution to House Server one now the difference between House Server one and House Server two is like I said so this 232 this would work for how we can just go through this real quick just to make sure so we started to and then we take the maximum of this number plus this number or this number so it would be 2 plus DP here and DP here would be the maximum of taking this number and something over here or not taking this number so clearly this would be two so two plus two or three we take the maximum and it would be four so that would be right for House Server one now in House robber 2 the difference is sorry let me actually draw it like this 32 this last and this first house is connected meaning that if you rob from the first house you cannot Rob from the last house and if you're out from the last house you cannot route from the first house so what we can do to fix this the trick to do this is we know that if we rob from one of these we cannot Rob from the other so what we could do is we could split these up into two different house server problems the first house survival problem is going to try to rob the max robbing these two in some way and then the second password problem is going to rub the max robbing these two in some way we're making two different arrays where one has the first element and one has the last element and that way we make sure we can't Rob the first or the second we have to pick one so then what we can do is we can actually make a function called robber and it would take some array so let's just say this is r we do all this and now instead of this nums it would be r so r and because we broke our house robber up into everything but the last element and then everything but the first element we can just pass these two arrays into the robber and return whichever one is the max so we either use the first house or we don't use the or we use the last house and let me see what other changes we would so we would have something here and then we would just return in here DP starting at index 0. okay and so this is going to be our memorization solution and now what we basically have to do is just pass in our two different arrays so we would do return Max robber everything except for the last element so this would be nums so we can do something like this in Python minus one would be the last element and when you do this kind of splitting the right is the Stop and you don't include this value and then we can also do robber so this is not without the last value now we need everything except for the first value so we could do something like this would be nums as well so this would be everything from the first value and forward now I think we do have to actually yeah so this would technically work however there are some edge cases that we're just going to take care of really quick so for one if there's only one house and we do this then it's going to be a no house array and if there are two houses then we can just return the maxim house so if it's our array is just 2 and 3 we just pick whichever one's the biggest so let's do that and then after that we can make sure that now our array has multiple elements so let's just say here if Lang s is less than or equal to two return Max nums so if it's two we're going to give you the biggest number and if it's one we just take the number that we have and I think this should be all the code so let's double check this probably did something wrong but it's okay let's index out of range so let's see what we did here length r okay yup okay so I see what we did here so this needs to be not r index plus two this needs to be index plus two and this needs to be X plus one so we don't need to be accessing the array at the index here we just need to be passing in the value okay let's try something now okay that worked so let's think about the time and space complexity here so for time so if we have this 2 3 2 4 let's say or whatever we're taking the first couple elements and then we're taking the last couple elements so time we're going through every house one time which means it's Big O of N and even though we do have so for this 2 3 2 4 we are technically doing two three two and three two four this would just be 2 times n and this 2 cancels out so we are doing this twice but it rounds down to Big O of n where n is the length of nums and space so we do have this visited and this visited will take most houses and so it will um it will be also open where n is then n is the length of nums okay now let's try to change this into the dynamic programming solution and then let's see if we can make that better so we're just going to once again we can do the same thing we're going to call robber on these two subsections of the array but what we want to do is we may we want to make robber a the true dynamic programming solution instead so once again let's say we have this one two three one example and let's just say this one two three one is what we're passing in so not the Chop but the actual um let's just say this is what we have okay this so our numbers are one two three one let's say yeah this is what we're passing into robber even though technically we're going to be passing in one two three and two three one so what we want to do is we want to have our very last item have a zero so we're gonna make an array of size whatever we're passing into this robber so we're passing in one two three one it's gonna have four we're going to have a Fifth Element now we're here and this is going to be equal to this value this last value in the array now so let's just make these indices so this is one zero one two three four and this is 0 1 2 3. okay so now that we have this 2 what we need to do is we need to see okay we can either Rob at two and then we can Rob at four or we could drop at three so our recurrence relation is going to look like so let's say this is r here and this is our DP array so our DP at an index is going to be the same kind of thing as in our memorization it's going to be Max of we rob our current index which means r i Plus DP I plus 2 or it's going to be DP I have plus one so let's take a look at what that looks like with this so at this two we're at house two so we can either Rob house two and then we can see what's at house four which would be 2 plus 0 or we can skip house two and then we could see what's at this DP has three and the bigger values two so we're going to put in two so now same thing here we can either Rob here which is 2 and then we add whatever's here so that would be one so our total would be three or we skip this value and then we rob here what this is the max this array is what's the max you can rob starting at this house if you so if you rock so if you skip this house the most you can Rob is this number here and so this would be if you do Rob here you would get two plus one which would be three or you would get two and so three is bigger and then zero same thing we can either Rob at zero then Rob at two which would be one plus two which would be three or we could drop here directly so three or three and let's double check actually I think we did this a little wrong somehow so let me do because if we were up here and we rob here this would be four so let me just double check here what I did wrong so this is this should be one this okay so we screwed up here so this if you Rob at this should be three so this number should be three then this number should be Rob at one which would be three yeah so this is Ray and then this should be one plus three so that should be four so our output here should be four because we rob here that we were up here so this we're going to have this on the side here and we're going to use that to code up our hooray actually I don't think we can have it on the side but that's okay so let's comment at this code and we're going to make another robber but now we're going to use the true dynamic programming solution instead of the melonization So Def same thing r so we're going to need to make an array of length R plus one so let's do that so we can call it DP equals and we're going to initialize everything to zero R plus one okay now we are remember we're going to make the last value should be zero and then from this picture the value of this should be this so DP of minus two second last element equals nums not that I'm sorry R minus one because this is the last element in this Elementary here because we want to initialize it because we're going to be checking in every spot the value of itself one element ahead and two elements of here so if we do two elements ahead it'll be out of bounds so we're just going to initialize this now we are going to Loop through until we get to the front and so the way that we would do that would be for range length GP so this is starting at the third to last element so this is actually going to be -1 minus two minus three -1 minus two minus three -1 minus two minus three yeah third July Solomon okay then minus one DPI equals Max of or so remember it's the element at our current location so our I Plus DP so if we are all our current cell then we have to go two houses ahead or we have to go one house ahead okay and then we just return DP of zero so from this picture DP of 0 is the most we can rob starting at the first house either we rob it or not and so that should work so let's try that oh very good it might be a matter real this page balance double Chuck or we just had some kind of infinite Loop but it looks like we might have to just reload the page so let's try doing that yeah so there's some kind of error in leak code it's weird okay hopefully it'll load okay looks like it's loading slowly is unfortunate but it's okay so there we go so let's run it okay let's wait a little bit don't have premium so okay now let's try to submit okay so that looks like that works now let's figure out our time and space complexity for this solution and so for this solution we are making an array and we are storing every single number in here minus one but we're doing it twice so it'll be big of n because if we have like a million numbers this will be a million minus one let's face the same thing we're going through each of these one time so this will be Big O event as well okay now let's see if we can make this more efficient so we have this array but as you can see this do we really need this array the most we're ever going to check is two elements forward so like here we're going one element two elements so we don't really need this whole array we just need to store a couple elements and this is where the first and the last comes in so let's see what that would look like so let's say we have this once again we're gonna we're only need to focus on the solution to House robber not House robber 2 because this will take care of that so let's get rid of this code let's comment it out again and let's think of what we could do so what if we say what if we use this first and last idea so let's say and let's just try to do the same kind of thing so let's say once again we're going to have this 0 here and then this you know that the value that you can Rob sorry from the last house is always going to be this value so what if we make last equals zero and first equals one okay so now what can we do if we get to this three can we just use these values to get this value and update them let's think about that so this is last this is first so the value at this three is just R of 3 Plus last or it's going to be first and it's going to be the max here right so it's just going to be Max okay so that's going to be the value Here and Now once we have this value well we need to move these so this last needs to be over here and this LA and this first needs to be over here so now this value needs to be first and last needs to be the old first so we're just taking these and we're moving them back so now this will be first this will be last and will be here same thing we get a value we make first here now we make last here we do that again we get a value and then once we get a value for this first thing here then we just return first and the nice thing about this is since we're only looking two elements ahead we just need to store two elements and then we might need some kind of temp value for what we get but that's about it so we don't we can get rid of this whole array so let's try to code that up so we're going to have another upper our final robber here it's gonna be def robber r so like I said we're going to have last first equals last is going to be zero and first it's just going to be R minus 1 because the amount you can rob from the last house is just the value at the last house and now we need to Loop from the second to last element in the array till the start of the array so for eign Pi in range so the second to last element is going to be Len r minus two same thing We're looping backwards so what do we need to do again we need to update our values and so in Python we can have a cool trick or we just do this we don't even need a temp variable but in another language you would need a temp variable so you would want to have some temp variable store a value and then you would need to make first that temp Fair sorry you would need to have some kind of temp store the value at current index and then you would need to make last equal to First and first equal attempt variable but in Python we don't even need to do that we can just do something like this so this would just be R would actually be Max r of I plus last so last is two elements ahead of where we're at or first and then last is just going to be first and so let's just do one quick example of what that looks like and then we'll be done so two three one so this is going to be last this is going to be first and we're saying first and then actually sorry so this are this is not technically going to be last and this is going to be first because this is kind of like representing our DP array so our DP array is like this so this is last and then we make this one this is first so that's what it looks like and so now that we're here we're going to say okay well this value equals this Value Plus last or first and so that this would be the bigger value would be 3. so first is going to be three and then last is going to be the old Value First and you're just moving these over so this goes here so you're taking these two pointers and you're shifting them one until they end up like this and now what we need to do is we need to do this now what we need to do is we just need to return first and first should be the first house that we were at let's try that let's see if we screwed anything up okay last first equals zero right now as always okay submit that okay so I hope that wasn't too confusing and now let's think about the time and space complexity again or what did we do we use the same DP that we had here the only difference we still went through everything except now instead of storing these values into DP of I we just have two variables and because we have two variables we don't have this array anymore so this just becomes constant time and that's it for this problem and I'll see you in the next one
House Robber II
house-robber-ii
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[2,3,2\] **Output:** 3 **Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. **Example 2:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 3 **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
Array,Dynamic Programming
Medium
198,256,276,337,600,656
1,206
and this one we're gonna be looking at the link uh skip list which is probably number one two zero six it's specified as a hard one i would tend to agree it's kind of hard especially if you have not seen any data structure like that so read the problem it's essentially saying of log n for searching with inside the linked lists so basically to give you an idea skip list is a multi-level linked list you have multi-level linked list you have multi-level linked list you have multiple linked lists in a way that at least the visual way where you can go at different levels and you can have a different list and you can traverse them differently but the whole idea is that you would start from the top level and then if you find a node then you would come down all the way to the bottom for that level and then you can return that so that pointer could be used for either searching or could be inserting or removing so you'll see more of that in a moment but in general the idea is you will have let's say i'm gonna show you the transition so the way we specify a skip list is you define a head pointer is uh into max minus infinity and the reason why we get the values is because it's a comparative uh um linked list so you do comparison at every node and then you figure out the right value to insert so you certainly want to have some values which makes sense for comparison so when you start the construction of the skip list you want to have something of this sort so basically a double linked list where you have a head and you have a tail pointer and these are pointing to each other and as you can see this the nodes look like doubly and they also have top and bottom pointers so when you construct the first level you don't use the up and down but this is what you use but as in when we decide by flipping on the flipping a coin that we need to raise the level we'll use up and down pointer you're going to see in a moment so let's say this is the first lev uh you know this is we just constructed the skip list and you're looking for an element so if you're looking for an element of course you wouldn't find it so you're going to be inserting some something inserting here so when you insert the element basically heads next is going to be here the previous of this is here and then this is here now when you insert this element here then basically depending on the flip of the coin we may be asking should we go to another level and the way it happens is you would if the left the element that you're inserting doesn't already have level on the top of it you're gonna go to the left until you find the one which has a level so and then since it doesn't have any level right now what we do is we would create a new level and we can say let's say this is h and this is h1 and t1 so we would connect these two and then h1's down is going to be h and h up is going to be h1 likewise here and then we'll move the head pointer to here and the tail pointed to here now once we construct another level then since we are still inserting we're in the middle of the insertion we'll say okay fine we have another node here which is the same value let's say we're inserting one and then you'll point this to here and then this so basically you know when you insert an element go to the leftmost which has uh another level uh and then if there's another level then you're going to be adding that element there now let's take a look at the code and i'll come back to here for explanation so the code i submitted in this code you can see entry as i mentioned next previous up and down and there's a value for that so this is what a node looks like and then the skip list will have a head and tail pointer and a height of -1 and tail pointer and a height of -1 and tail pointer and a height of -1 before we do any initialization and then for random you have this is flipping the point so as soon as you construct this skip list you have built level the level is basically constructing the head and the tail pointer so when you start this you just have a head like head is going to be equal to n tail so head is h and tail is t so basically like i said here you just in that step when you construct this you would just have head and tail and then they will be pointing to each other just the stubby lung list so this is what happens when you build this now let's go to the add so when you add an element so what you do is you look for the nearest value so let's take a look at what happens in the nearest you are starting from the uh head and you look for the value that is less than equal to the target and if you find a value then you go down and then you go all the way to the down at the bottom and return that node if you're just doing a search that for that you could just return from the top that's going to be optimal um coming all the way down it i think the coming all the way down the impact of that is how many levels you have so that's going to be added complexity for coming down but i think what happens is it just makes the life much easier and i think i'll say it's uh if it's a reasonable constant value so i wouldn't worry about it but at least in this case you come all the way down and then we get the point to the bottom and you know it just makes the life easier for uh erasing inserting and writing a common method for everything so you'll see that in a moment so basically uh to give you one more idea about how this method works so you start with the head pointer and then if you check the right value is the has the value less than equal to target then you go to the right and if this condition doesn't satisfy you come down and try the same thing so here we start with that it's right is t and this value is positive infinity so since we cannot go we'll try to go come down which is now so we'll stop right here so if we were to add an in a node one here we'll look we'll add a node we should add an over here but let's say if there was a node one and we was looking for that node so let's say i add a node 1 here so this first condition is going to be satisfied because h start h dot right that value is less than equal to the target so it will let me go to this node but this one is going to fail so it's i'll try to come down because it doesn't have any download so i'm just going to stop right there and this element is going to be returned so this is how search works so this is look up nearest so if you don't find the exact match you just return the nearest entry and for and we find the nearest entry bit where we need to insert and as you remember we search from less than equal to so our insert is going to happen on the right side so we create a new entry that needs to be inserted and there's a method had to chain and i had to chain what this does is it's just going to insert this new entry next to the given entry so basically like i said you're adding one here and you're heading after h so basically take this pointer point to that this point to that and this pointer so this is what we do here add to chain now we start with the i equals zero and then this is the logic where we decide we need to raise the level or not so since i is zero and then the height was zero to start with then we decide to build the level because there is no further level so we build the level here and again this is happening with the flipping the coin so what we try to do is if the entry where we are adding doesn't have any level up so since it's a new fresh entry here one um it doesn't have any level up what we'll try is now we'll try to go on the left side and see if that has any level up so in this scenario what will happen is uh just to demonstrate that method what happened is we added h t and then let's say it was like that and we added one here now the level i was zero h was zero so we decided to raise the level so h here t here and this got connected this is connected now we're saying go to the left until you find something has up since we build another level head is going to be connected again one more thing i wanted to call out that new head is going to be pointing to this and the tail is going to be pointing so you go up here to this head and then this is going to be your entry object so you move to the entry and then you find this up so this is going to be this head now and then you create a new entry and then add to the chain so essentially you take this another copy of this one and you're gonna be adding here so now this is connected to this and since you went on the left side the first left entry which had a level you don't really need to worry about other complications because that's going to be the only entry that needs to be connected here so and then you would certainly want to link these two entries together from up and down and then you set the new entry as the this entry so that you can continue looping through till uh this returns false so basically you are raising the level based on flipping of the coin so this is what the ad is for erase what we do is we find the nearest entry and then basically um so let's say we are trying to delete one so since the lookup nearest returns you the bottom entry so what you'll do is you'll point this to this so that removes this node now you go up and do the same thing here so that's the loop here that's precisely the loop so one more time the entry will have next previous up down and the value so basically a node can be connected all four sides up down left right and then you build the level when the um you know the loop value that you're looking at is equal to the level so that means you need to raise the level so when you raise the level you always have a new head and tail and you switch the main instance level head and tail to the one that you create and you also link to the uh the new heads down as the existing head and the existing heads up as that and then you basically you're gonna keep it connected now look up neatest you basically find the nearest value which is less than equal to target you come down all the way and return that node you could have stopped as soon as you find the top one that should be fine for look up nearest but basically the code to come down all the way to the bottom for adding will be written that needs to be written by add or the delete method so this basically takes care of that by adding additional complexity of the depth or the height now erase like i mentioned you just come from the bottom and delete all while going up and is slightly tricky but i think it's okay so what you do is you create a new entry and then you enter the chain and link it and then basically you flip the coin and if i is equal to height then you build another level and you go on the left side if the new entry that you adding doesn't have any level up then you go on the left the first left which has one level up you go that you create the entry after the chain and then you connect these two entries are connected as well and then this entry becomes the new entry to be connected when you raise the level up so with this i did submit and i think i got 92 so i'm gonna share this code uh lead good as well thanks a lot for watching hopefully it helped you learn something new thank you
Design Skiplist
corporate-flight-bookings
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Array,Prefix Sum
Medium
null
637
hey everybody this is larry this is me in a new city as you can tell maybe all these new hotels so technically it doesn't have to be new city but uh yeah uh i'm in the city of entire in turkey so yeah i think i have a drone video but it's just been very tiring so i don't know we'll see uh hit the like button hit the subscribe button join me in discord let me know what you think about today's farm and that being said let's get started uh let's see oh yes wish you first to ac look at this click 10 coins baby yes okay too excited there but that's the average of levels in binary tree what does that mean okay we turn the average value of nodes on each level and form of an array okay so you know the first thing you should know when you hear average is that you break it down into components right total over um count or total over number or whatever so let's just sum up the level count the levels and then that's it right so let's get started um you know i'm just going to put something like uh you know uh toto's count is equal to right and then now we do some sort of recursion we uh you know we have a node we have a level and then yeah and i know that people do default levels that's fine it's up to you if you like it or not but if notice none then we return otherwise um if level is greater than or you go to length of total is it great now just create it or you could do yeah um then total append zero and also counterpart zero and then after that we just go to the add know that value count we add it by we'll just add it by one and then we go node.left add it by one and then we go node.left add it by one and then we go node.left level plus one go no that way level plus one uh i would also say in general this is way much um very much expected to know so definitely get very good at stuff like this so yeah because i think this is just a very basic recursion problem to be honest that's going to be on your interview pretty much well like i mean you know like that's expected to be known on your interview whether you know it or not so uh yeah anyway answers you go to a sip total account we do tc and this and then we just do to see for the detail and then i guess we're going to return this we don't need a serial ray and that's pretty much it i think uh oh i guess that makes sense but that's did i miss something am i using something weird i guess we're not manipulating the way we're doing an append operation which is why but uh oh maybe that's why okay i think that's why because i made a mistake here i meant that this is this i was wondering why because we were not i wasn't manipulating the thing so that shouldn't require it but uh even though uh the nuance there's a little bit uh whatever but anyway let's give it a submit and see hopefully no silly mistakes and there we go 885 day streak and you are those of you who have been following the last couple of days will know that i'm pretty happy to hear that so yeah uh that's pretty much all i have for this one that's all i have for today let me know what you think and also if you like the ins the drone videos or whatever uh come join me on instagram at larry somewhere or something uh it's on the description uh no did i say or something like that i don't know anyway uh this is linear time linear space uh did i say that no yeah just because that's how recursion works i mean oh if h space if you want to be a little bit more precise in terms of the depth uh but yeah but you can't believe you know as a binary tree problem or just a tree bomb in general uh and that's it's about is a search tree uh but uh of some sort or b tree or whatever a structured tree maybe then uh you have to look get every note for to do stuff like this uh cool uh that's all i have for this one let me know what you think stay good stay healthy take your mental health i'm so tired please so i'll see you later and take care bye
Average of Levels in Binary Tree
average-of-levels-in-binary-tree
Given the `root` of a binary tree, return _the average value of the nodes on each level in the form of an array_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[3.00000,14.50000,11.00000\] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return \[3, 14.5, 11\]. **Example 2:** **Input:** root = \[3,9,20,15,7\] **Output:** \[3.00000,14.50000,11.00000\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,107
732
cool 7:32 my candid we implement a my cool 7:32 my candid we implement a my cool 7:32 my candid we implement a my calendar 3 class to story events a new event can always be asked I always be added your class with one method book starring an end for my discipline set represents a booking on the half open interval start and ok yeah better scientist inclusive but ok the range of real numbers X such that X is less than X which is best an end ok booking your friend happens when K events have some non-empty intersection events have some non-empty intersection events have some non-empty intersection there's sometimes I has come to all K events we each quote to the method Mike and at that book we turn it integer K represents the largest in address such that there exists and K book in the calendar ok I should practice this more - oh yeah and feel free to ask questions - oh yeah and feel free to ask questions - oh yeah and feel free to ask questions if you have any questions while I'm doing this better cool first events coming book can't destroy is it all just book okay so there's no like delete you friends and boy in this excellent then the maximum camera is a to booking okay there shouldn't be two I think I okay there shouldn't be two I think the thing that I always look for when I look to see these problems which actually didn't happen the previous form because they didn't have a section for it's kind of look at the constraint as much as I can so gravitated that there will only be four hundred so on your course which immediately sets off things in my head that like okay now I could probably do things n square maybe even n Square log N or something like that if necessary I don't know just applies here but yeah well N squared log and totem so in theory you can do a sort on every thing so like you could do an N log n per book or maybe I mean I don't know I mean I'm that's quite like the feeling of what we would need to do I don't know that's the right complexity but uh don't cause the wound and sorry okay and it contains start and end okay um yeah um I think that uh I think so the only took to be honest they're only two questions for me one is trying to figure out I wanted to heap or a regular sword on each of these course as we mentioned we could end again we have probably about n log n time yeah uh damage on now I mean you're exactly right I was thinking about that exactly yeah we just needed to sort an encounter overlapping segments I think yeah the only like I said the only thing question I have is maybe and I guess in some way they're both so it's better but like oops what a quick but like read again just sort the entire thing every time or what you require or maybe put in an heap to kind of save some time should be put in a heap yeah I think there's some benefit and put in a heap even though they're both and originally sort i mean you sent you that's what you're doing with insertion so I think that saves us some time yeah you can also insert an order um hmm not quite sure oh you mean like what record not really insertion sort but the thing with inserting things in order it's kind of tricky to do necessary because either you have it you do it on a linked list type thing which allows or one insertion but then you get like an N squared type situation by me that's fine no because then like you don't have random access I think which means and what that means is but then it's linear time for inserting for a linked list so then like it just may be okay maybe that is the same as well maybe you're right yeah now I think you're actually onto something there I wasn't I mean yeah at the end of day we're talking about the constants on the end again because when you go with a list that would change I mean you can probably play around with more complex data structure but I think the constraints such that you don't have to die yeah I hope I'm that well but okay let me just go do something and we'll see I think what so yeah maybe out doing here because I think I know I just feel like that's lower variance coding thing that I'm gonna do I think the other thing is if I do it any other way you may be it I don't know yeah I mean I just worry that I do another way like there may be some educators that I'm not familiar with and sometimes you just have to be you know you have to do the thing used to tow that you're familiar with okay no I'm think of something else pit I was just launched its first but they wander to smaller numbers out just gonna make sure that this is what I expected to be like the man confuse 5.2 expected to be like the man confuse 5.2 expected to be like the man confuse 5.2 a hip key okay just seemed to offer away okay I think the only thing I have to make so I'm just giving touch just to make sure that I implement them in the right order I think we do the pop first as a resolve is being negative to it as a tiebreaker so I think that was just ER yeah the refraction it's just what we need like for example you have like something that goes from 10 to 20 and then another thing that goes to from 20 to 25 it should only have one at the highest because the 20 stone - overlap so you because the 20 stone - overlap so you because the 20 stone - overlap so you want to get rid of the 20 at 20 first yeah if not go play around with it but uh we don't care about it Oh yes hmmm that's unfortunate yeah hip is easy to implement also cause someone has done it for me yes it's intentionally I do it backwards I wish forget which way I wanted to saw it okay it's potentials but this is more like that's wits oh I think I now I have to actually be careful I know I start to a smaller bigger well I mean I just confuse myself too much a little bit more let me try anyway cuz I give interpret okay that looks okay in this class only thing I've worried about one time yeah okay so now I guess we have to get a little quicker than I thought it'd be a break okay so I guess 405 I think it's our bomb ticks I think we just gives me a timeout what I mean just watching I guess maybe they just a lot of cases and I that's sums up to it being out of time I guess we have to do slightly more clever than let's think about it for a second I was hoping there would be just a little bit having the problem with and some and these are things that a little tricky sometimes because yeah depending on the system you're implementing or sometimes the time limit exceeded represents like one test case where some other systems that represents the total amount of time for all the test cases so which sometimes they don't tell you how many test cases there is right so I think within one test case we're definitely fast enough but it's I guess in this case we have enough test cases that the ninety-eight test cases then that the ninety-eight test cases then that the ninety-eight test cases then maybe take too long for each of them are kind of the edge of things okay but what something that would be short but okay so let's think about what that means then I mean there definitely some we're definitely doing although we don't drink all extra work because require can take advantage of the fact that you know the system doesn't change that much and we're adding certain things to it but so yeah so doing cuz this is n log n so into an N log n on each book seems like we have to be at least faster so and faster and I think the other thing is also we have to think about what does it mean to end you know insert a segment and whether we can kind of will take advantage of some stuff okay so I'm actual okay hmmm I think so yeah particularly a little bit better I think what I'm thinking now as well mmm and I think it probably comes down to some sort of I want to say that this kind of reminds me of Lizzy called my quadtree type surgeon data structure or like a tree types right data structure where Widow also try to figure out how the incan cooperate that way and what's essentially I mean these are like log and operations which is fine but I think the thing to note when we insert something is yeah I mean maybe we just have to do that like this stuff having Python it actually supports but anyway but when we insert something you look at the neighbors well you know where it fits in and died cannot the answer can only go up where you when you're inserting and now I have to represent that in a data structure that allow us to do it in hopefully log in time but and also set up the data structures of that so that you can or it will definitely do it okay and I'm trying to think of an array is good enough you could definitely confine some of games and we can definitely cache some of these answers but also like them this happened we also just trying to work out the complexities in my head I think so you can insert things in log n time but then it takes n log n to get like I sorted this out welcome I consider switching languages okay don't quite around some c++ st there's a what's that some c++ st there's a what's that some c++ st there's a what's that function be Louis or something like that lower bad I can fight you slower bound so I think one thing I'm just like doing in general is especially when it comes to trickier problems to do as little manually as possible so because there's just more room for mistakes the lower bound will probably come in handy okay I think I have some idea so it's basically we want to kind of think as I was saying similar to what we did in two heapsort in concept but we wanted we want to have a data structure that take advantages of it right so when we ensure that you friend me one I guess the last event that's smaller than or similar or the same as this number and then increment one to it and similar but the opposite for the end of it and an insert an entry into a sort of a tree set type train now you have a solution work for you or also hi near - did it work for you or also hi near - did it work for you or also hi near - did it work for you or I got timeout that's why I'm doing it now I don't know if you saw me doing it earlier but that was not even that side I mean I'm and I could even show you when I ran this on this example I did anyway yeah like it ran in a second but hmm I mean when you say now you just mean like you inserted and then you kind of like off and maybe yeah maybe you're right yeah maybe yeah okay let me try this again and no - maybe away I think I again and no - maybe away I think I again and no - maybe away I think the other way to go about it is maybe I just over toilet a little bit I think also people because I think lists in pipeline also has it's like a pseudo away it's not a something like that it's a point where it's a list not in a way so I'm quite handles that for you wait really yeah time to sort through this I mean this way you're just slow what do i do something to PS then I live I mean I didn't use the heat turned up just for fun mmm-hmm I was good way to do something mmm-hmm I was good way to do something mmm-hmm I was good way to do something more crazy with vigor and then we try this before I really dig deep into it I wonder soil is also like optimized for this as well like if it's all like the idea that it's almost like it's already almost was almost sorted maybe it takes much slow faster than n log n maybe it's mana to do that I don't know that kind of makes sense actually I guess in this case home no just probably out of place Wow you're right this is much faster look maybe the almost that's interesting right well I guess that's see if this is actually bluffing like no I don't know any of this point to a pilot fine let's just try again and this actually in fact this was really fast uh because I guess the time was spent printing all right huh well I guess I tried to do the coding well first of all thanks ik thanks Nell to for kind of the hint I don't know what to say so you think hmm I mean I have some ideas it's just that uh I think I protect against the worst case sometimes but yeah I mean I don't think that's it per se I mean that's definitely part of it I think that I think I would actually say that it's quite related to this or dienes of the thing where like it's quite you know cuz because we do keep so it's almost like you have to look at like it's actually like it's bounded where like every operation just login and so it's my again like Prive very tight net and login because you have to do like an ish operation every time because when you take off to the top you like it go over bottom where I think in this case because this you know self dot heap actually this is just a bad name now I looking back well now I'm looking back because we just changed it a bit but I think this is because every time that we do this sort we have in a way that is sorted - to element - to element - to element so I think like maybe there's something that's owed in this and I think but some of that is maybe Python yeah fine it doesn't use a way so it just does some magic tier and I guess no I mean I think now that I think about it excuse me I mean I think now that thing about it you're what I think actually Johnny mentioned this earlier and I quite dismissed him a little bit because I didn't really think about the bounce in this week cards but if you think about even just using a that's how you're using a dumb naive bubble sort and in this case because the sword in this sword enos the sword in this is almost like it's like literate the only two elements out of place on it right so that means that we used bubble sort and you sort or yeah you use publisher and you bubble just these two numbers to the right place yeah okay maybe you have a lot of swaps but it's only two times n right so you only need two one bubble sort two iterations of the published sort so in that case in that realm so you can actually even optimize that a little bit more inferior because I just don't know how this gets I mean I have some idea how its implemented by don't know how like it actually you know codes it for in terms of like these kind of strange cases but if we think analyze it that way we just say we did it some scratch and we use bubble sort instead this is actually like two times and so like oh and for this bubble sort and then this is obviously linear so this is n so actually the in that world we had two iterations of the bubble so here this code would actually be off and instead of oh and again which is log of n improvements and improvement but yeah but and I think like to some degree sort probably like it's smart enough to terminate things in a little early or something like that instead of doing like a full n log and sort so that's why we're there speed comes well but yeah they also apply I mean I to be honest I'm not I don't necessarily understand how Python internals work with respect to how you know there because there's a lot of possible poisons of optimization we expect to raise and this and so forth so I don't want to speak too much of it something I don't know about but uh I think like given without knowing that if we reframe the problem or a solution rather as a published sort that wants to iterations then yeah and I think Wow NIDA Newman to be honest yeah well I mean I like this problem as a resolved that I think it actually forces you to think about things you already know I mean people should be familiar with published short or something one of those type of sorts I mean it doesn't have to my for yeah I mean it isn't optimized for which McCoy it does not demise with number Swapna so but your complexity is the log and thank you I think I definitely was a little you know I hastily dismissed just distorting parts and login but really thinking about can we do better on the sorting point but I think something that you just take for granted and I take for granted is that so I don't know is n log n so let's just do this other thing there but actually like if you only one you know like almost like you know there are many ways to if you make some if you actually understand the context of which you put it you see sorting toast and maybe you don't know in this case I mean it's yeah so I think like that forces you to analyze swings in the way and asks you to contextualize the stuff that the tools that you have in a way that maybe is novel but he's just maybe uncommon so I think I actually really take this problem as a problem solver what everybody call me but it's an interview question as a I mean I think this is I said we saw actually really like this as an interview question as someone who's a person the viewer I think I mean I think there's some improvements around like you know kind of and some of this you know because an actual interview is interactive so that will kind of suit brings out what's moving things out a little bit in terms of expectations so but just having to bounce and stuff like that in a good place I think yeah I'm really I mean I do dictor the thinking that gets you to the solution right and in an actual interview you actually talk about you know how your wife it is and not just like oh I have some code that hopefully it works right so I so that would kind of come out my only hesitation would be that this is this maybe it's a little bit too little coding for a 40 minute or an hour interview and in doubt like there's only ten lines of code which whatever it is twelve lines of code which makes things a little tricky to see you know how someone I mean it definitely demonstrates someone's problem-solving demonstrates someone's problem-solving demonstrates someone's problem-solving ability but maybe on the coding ability I'm not so sure that I would learn that much about it but I have to think about how maybe ways to kind of modify this to make it more interesting in terms of programming but I think I really take this form and thanks again now to four oh yeah I'm excited yeah definitely yeah I don't know if there's a easy way to share your code without not be kind of cool to see kind of what optimizations you're doing but yeah because I think I mean by not sorting it I assume you mean just like doing some sort of insertion inserting up insert operation and I think yeah I'm them they'll definitely wait I think that I feel like I used to optimize one is maybe the insertion and used length minutes or something like that I don't know how to trade office for random memory and stuff like that versus whatever so but I feel like given then like we gotta cash this so that this you don't have to run it for the entire way so you have to probably run it for this segment that you overlap in so I know so at least in terms of the Big O sense it's the same but there is some optimizations there yeah hmm but yeah well yeah thanks again l2 for kind of giving me a heads up I actually was about to do something like really complicated she can't see me do and it saves me a lot of time cool yeah enjoy this file okay oh yeah it's um I don't remember how when I picked it up but I definitely remember at some point I yeah not this farm obviously because right then I would know I was down but uh but for in turbos I think to you friends yeah I mean I think in the end of day they were all the same where like you to save me a few operations or something I think that I always strive to do a little bit is yeah it also makes you like just less error-prone because some like just less error-prone because some like just less error-prone because some owner like the less you have to type the clearer it is and this I don't know I guess I just worked out over years and I don't think I came a bit I think I did apply it somewhere that like you know allows you to you know my philosophy is the best you typed unless you're you know going to make errors and the less mistakes you make and I make about typing mistakes though especially in Python where you know it's not a type language and it get that you do things let me just take a quick look down man I actually are not familiar with oh so I'm really lucky that there's no like not stay forward at all right and I never know these things and then we're getting 12 news I don't know but I cool um I think bisectors to think that I definitely read up on some weird but I just kind of I think I need to actually do it to learn like because I think I alluded to this a little bit in yeah exactly I was gonna say alluded to this and see pass first over bamboo or not and not for me with bisect but I need to yeah one of those but I've I need to I mean you know they're the more tools you learn the better and so I think that's cool so yeah I mean I think this is descent like similar to what I was thinking about doing except when c-plus class except I doing except when c-plus class except I doing except when c-plus class except I was and I didn't know if this was gonna be fast enough so I was gonna do some crazy thing with Stegman caching type thing but it's good to know that it works so thanks again no - I would works so thanks again no - I would works so thanks again no - I would definitely read up on this and hopefully you know in the upcoming streams out that try to use it more or something data yeah seems like I'll be useful because I do binary search in silly ways sometimes
My Calendar III
my-calendar-iii
A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.) You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events. Implement the `MyCalendarThree` class: * `MyCalendarThree()` Initializes the object. * `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar. **Example 1:** **Input** \[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\] **Output** \[null, 1, 1, 2, 3, 3, 3\] **Explanation** MyCalendarThree myCalendarThree = new MyCalendarThree(); myCalendarThree.book(10, 20); // return 1 myCalendarThree.book(50, 60); // return 1 myCalendarThree.book(10, 40); // return 2 myCalendarThree.book(5, 15); // return 3 myCalendarThree.book(5, 10); // return 3 myCalendarThree.book(25, 55); // return 3 **Constraints:** * `0 <= startTime < endTime <= 109` * At most `400` calls will be made to `book`.
Treat each interval [start, end) as two events "start" and "end", and process them in sorted order.
Design,Segment Tree,Ordered Set
Hard
729,731
86
hello everyone welcome back here is bananas and today we are diving into Political daily challenge number 86 partition list and we are doing it in go or go link so linked list might sound uh hard but trust me once you get the hang of it they are super fun and immersed and Powerful especially in go where everything just flow alright so without further Ado let's break this down step by step so first let's understand our objective so our goal is to partition this linked list around a value X all nodes with value less than x come before nodes with value greater than x or equal to X so uh sounds fun so let's dive into example so this is our linked list and X is free so here is X and values that are less than our partition X is 2 and 2 as well so two goes here and notes that are equal or greater goes after so it's four three and five and also we need to preserve uh the order so how can we uh solve it so basically uh if we have uh number one for free to five and two we will have a two partition uh before and after so it will be before and here will be after and we will have a dummy of value 0 just to have a pointer it will be helpful for merging and returning merged uh linked list and we processing every value in respect to our Target X so one is less let's go here then four is greater let's go here a free greater go here to less goes here uh five greater goes here and finally our two is less than three so it'll go here and then what we do we have start at this node so we are pointing to one and also our uh tail from before A Link at least points to uh yeah uh this note so it will be after next pointer and we are merging those to list and output uh this particular uh node okay so now when we understand it uh let's dive into implementation so before will be list node and after will be list node as well and before current will be before and after current will be after this will help us easily build our two separate list or partition before and after and we also have before after and before current and after current so we also need two pointers before current and after current and why uh because they are pointing to our dummy uh notes and think of this as our little Builder crafting our before and after uh list so now here is where the action begins so we are going to Traverse our list a note by note so four hat not equals nil if hat value less than x so now where the core of algorithm goes so for each node we check its value against our X so if it's less we will append it to the before list and if it's not it goes to after list because it should be equal or greater to X so before current will be next head and before current will be before current next and else we have after current next goes head and after current will be after current next so now head will be head next so see how our pointers so before current and after current help us in this process and they are always ready at the end of our list ensuring a smooth appending process and we are almost at the finish line so once we Traverse the entire list we just need to combine our before and after list and guess what our dummy notes make this process a breeze so we have our dummy notes and let's join it so after current next will be nil and before current will be next after next so now we use our after dummy node and before next we'll point to our merged list so uh yep and that's it so let's run it to verify everything work so yep for this case we have X3 and we have successfully partitioned our linked list and time complexity of this solution is o n time complexity so linear and space complexity is o1 so it's constant so now let's run it for unsynthesis cases as well so hopefully it will work it's processing a bit long so I don't know why three milliseconds uh really strange but as you can see rust implementation took 0 millisecond python 39 and yeah let's rerun one more time for on synthesis cases so as you see now I go run also in zero milliseconds so probably here it was some leg so as you so and yep our implementation is efficient it's between 100 percent runtime zero milliseconds so it's probably rounded and also beating 98 with respect to memory so perfect so that's all for this video and if you want to see how logic transform uh and translate in other programming languages like python rust C plus and much more head over to description below and I will provide a link to both GitHub and Lead code and yeah thanks for joining me on this coding adventure and if you enjoyed this video give it a thumb up and share it with your fellow Cutters and don't forget to subscribe for more uh tutorials Solutions and much more and most importantly keep practicing happy coding and see you next time
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
1,071
Oops, let's start another exercise here for the 1071, right, in this exercise here, two Strings will be passed to us and we will have to return a shelf that divides the two splines, right, it's explained here, right, it has to be divisible, right, in this case, there the ST will be able to divide S if s was equal to t plus something else T, right? So this is what the rule for me, right, to be able to do a streaming division, example here, right, you ABC and 52 ABC So what will divide it will be ABC then you can divide the two Strings in this second example here open And then 32 ab what can divide these two is a b example here as they are totally different nothing divides the two, right despite the i and is in both Strings, right, no, follow this little rule here so what will divide the two So let's start first thing I'm going to do is going to be creating two variables to store the size of the streaming after I wanted this variable here I'm going to create a condition, right, just in case this happens here, right, if this third example happens, I'm going to return nothing at once now, so this one would be the condition precisely for this third example here, now I'm going to write the code here, right, and then I'll explain what happened the idea of this resolution here Okay, so now let's go to the explanation, okay, I'm going to call the function that I created here, right, passing the two parameters, then I'll go first I'll look, yes, two are the same it is different from zero it was equal to zero I simply pass it on one and that's it if not two is different from zero it will do it from here, right it will take one it will divide by a two and it will store the remainder of the division then he will replace one two and not two because for the rest then he will go back in the loop, right he will see if number two is now different from zero and not two we are from zero he will do the same thing again if it is equal to zero it returns the new number, right in this case it replaces one two then it does a Slice here, right it will take the value zero up to the value of its answer here which will be in this case what it its answer here which will be in this case what it its answer here which will be in this case what it found So let's explain just one a little clearer here, take this first one here, it's blood one, there's also a 6 and 32 is a size three, right? rest is going to be zero, right, this one, after I'm going to do it, I'm going to replace this, it's going to turn into Ezequiel is going to turn into one two, right, doing that substitution, right? Then he's going to go back in the loop, as in two is zero, he's going to return one that now it's 3, right? No, at first it was six and one two was three, he did the division, replaced one, it became three, one two zero, he starts the group again, one two is equal to zero, so it returns to one, right? Then it won't come here, right? a Slice from zero to the value three, right, we will take the value zero to 3, it will give ABC, right, now taking this other example here, is 6 and here is 4, right, so let's go here, 16 / 4, but there is what to remember and we are only going to / 4, but there is what to remember and we are only going to / 4, but there is what to remember and we are only going to use the whole number, okay, so we don't use the number after the decimal point, which will be one, the rest will be two, right, 4 becomes the 1st and the two becomes the 2, right? new, right, it's going to be four divided by 2, here's two, it 's going to be zero, right, then I found the 's going to be zero, right, then I found the 's going to be zero, right, then I found the remainder zero to return here, which is two right, so returning one two he's going to find the first two, take Estevão and he's going to make one slides with the first two letters, finding AB the answer here, right, so let's see if it 's working, sometimes I got something wrong, 's working, sometimes I got something wrong, the three examples, right, so let's send reminding people that we can always take a look at other people did the exercises and we learned from them too, right, so that's it folks. Remembering that below there will be my blog with a whole code and an explanation of how I did it, but that's it and see you next time, thanks
Greatest Common Divisor of Strings
binary-prefix-divisible-by-5
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Array
Easy
null
6
I come hello everyone start students problem call teacher planning limit problem in this and half 100 twists and turns blushing egg white from the slow pace of this video a little teacher relief subscribe for quality thank you want to from bottom cross subscribe now to receive New Updates Reviews and Does One Basically a the Best Us of Baikunth Times of Gold in This Time to Two Hua Tha Ki Don't Thing Which Hua Tha Ki Don't Thing Which Hua Tha Ki Don't Thing Which Basically Sports Travelers Ko Main Dard Last Store Which is 10 M ons But the First Poetic -story The In The But the First Poetic -story The In The But the First Poetic -story The In The Second Remedy Wishes For This Means Sacrifice Of Two Adi Stand This Pattern List Listen 281 Adheen Subscribe University Phone Number Dial Duis Atam Questions Aliens Ashok Das Ko Isko Solution Swayamvar-2 Is Oil Ashok Das Ko Isko Solution Swayamvar-2 Is Oil Ashok Das Ko Isko Solution Swayamvar-2 Is Oil Store And Every District Provides Na Dharo Chair Is to all the characters in adharon andhe for this is this plz subscribe and subscribe the main office number us size dhan guava absolutely guava office notice given in the eyes which mp distick ki naav articles in the tag of calculated for intense loot singh2 comments ki Gaon Aag Misbah-ul-Haq Poison and White ki Gaon Aag Misbah-ul-Haq Poison and White ki Gaon Aag Misbah-ul-Haq Poison and White Vinegar Basically a Lot First Iodine is a Journal Gurdas Meaning Idli batter for age group Soft Delhi For This Use This Loop 20 Subscribe to my channel Must subscribe a video Please subscribe and subscribe the Channel Kulwant Singh Chintu Mintu Double Bed If this work is done then we will ask for romantic reason etc. Starting from the speakers along with this and the most visited subject from one - most visited subject from one - most visited subject from one - Meaning Sacrifice in Field and Workshop Samay - My Sister in Indexing Starting from - My Sister in Indexing Starting from - My Sister in Indexing Starting from in LS Basically from 08 2011 - - in LS Basically from 08 2011 - - in LS Basically from 08 2011 - - Dept of Numbers - ₹2 Lax Om Nam Romance Dept of Numbers - ₹2 Lax Om Nam Romance Dept of Numbers - ₹2 Lax Om Nam Romance to NFC turn on near organic garden expert will always be superhit turn on in the morning not angry clean just agenda of corruption servant after this fast will be caused in to -Don't forget to subscribe to the do list in to -Don't forget to subscribe to the do list in to -Don't forget to subscribe to the do list and that me attend the meeting with you do series price meaning first things first president she is the video then subscribe to the Page if you For watching watch videos to thank you
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
1,780
hi everyone welcome back to lead coding i'm your host faraz so in this video we'll be looking at the second question of lead code by weekly contest 42 now in this question we are given a number and we have to tell whether this number can be represented as a submission of unique powers of three now first of all i thought that let us do this question uh using brute force and then just use memoization and convert into a dynamic programming uh but that doesn't seem to be a really good solution so i thought a bit about mathematics so i try searching the plot of 3 raised to the over x and 3 raised to the power of y so if i have 3 raised to the power x plus 3 raised to the power of y these are the two variables here we will have such a plot with this plot we can predict something that they cannot be another x 2 and y 2 for which this equation is going to satisfy so if this is equal to z if it is equal to z then for this to satisfy x should be equal to x 2 and y should be equal to y 2. so this i got to know from this particular plot over here all right okay as uh this plot is not overlapping it is not overlapped hence we got to know this so if i try breaking a number into 3 raised to the over x plus 3 raised to the power of y these x and y this pair of x and y is going to be unique all right also other thing that 3 raised to the power 15 is equal to this much which is about 10 raised to the power 8. so what i can do is i can start searching from 3 raised to the power 15 for which i will use a for loop for int i is equal to 15 i greater than equal to 0 and i minus i'm going so these this i denotes the power of 3 so int x is equal to power of 3 raised to the power i so i'll be going to all the unique powers starting from the 15th till 0 and i will try reducing this so n minus equal to x only if this x is smaller than or equal to n then i can perform this operation and in case n is equal to zero if we are able to reduce n to zero then we can simply return one from here that is true otherwise at the end we can return zero that is false so let me just quickly submit this and it got accepted now talking about the time complexity this is a constant loop as we know it is only running at most 15 times and this power uh actually it is logarithmic in time complexity so it is basically log of i because i is the number that we are going to pass as the power so it will be log of 15 plus log of 14 plus log of 13 and so on all right so this is it about the time complexity the space complexity is constant and if you like the video make sure that you hit the like button and subscribe to the channel also you can check out my channel for resources for your interview preparations here's the free interview preparation series which you can follow if you want to prepare for your coding interviews or if you want a quick revision here i'm going to cover all the topics and i will be conducting live doubt sessions as well you can check out the link in the description for both the telegram channel and the free interview preparation series thank you
Check if Number is a Sum of Powers of Three
lowest-common-ancestor-of-a-binary-tree-ii
Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`. An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`. **Example 1:** **Input:** n = 12 **Output:** true **Explanation:** 12 = 31 + 32 **Example 2:** **Input:** n = 91 **Output:** true **Explanation:** 91 = 30 + 32 + 34 **Example 3:** **Input:** n = 21 **Output:** false **Constraints:** * `1 <= n <= 107`
Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path
Tree,Depth-First Search,Binary Tree
Medium
235,236,1790,1816
118
Hello friends, welcome to the new video, question number 118 is in the robbery, the name is Paas Kar Triangle, it is a question of level, it is a race question, let's see once, what is Paas Kar Triangle, what is called Paas Kar Triangle, there are number of roses in Paas Kar Triangle and You will see that the first element and the last element of each day have happened and the new row that is being formed with the help of the previous disease. So, let us look carefully at this diagram and we will see how the forest is developing. Plus one becomes two, this two plus one becomes free, it becomes 1113, then this below three plus 114 6300, so the latest one is the previous cry, help in developing it, media and something like this, if we have to make fiber then fiber like this If you see something like this then the input is our interior, we have given a number for each day and we have to develop it for each day and in the output we have to print a list play list which we will make and print all the days. This is a simple question. There can be a few ways, I can approach once. Let's see, now coming to the approach, how will we make the triangle? First of all, you know one, then you will see that the first to control will be one and the last will be one, the third stop will also be the first and the last one, but the third stop will be that. The elements in the middle will be those which are being formed by adding two elements of the old Rok which became OnePlus One Hate You, then its last element will be Chinese elements, the third will have three elements and then there will be four elements in it, so the first and the last will always be money. It happens and there will be four elements in the throw. Now how will the middle two elements be made? By adding these two, we will write three. It is here and by adding these two, you will again write, then in this way, three elements will be made by adding both of them, then by adding these two, three will be written in the throw. If you have elements then the first will be the last then one is always ok and you will access the old Veri E M Roko and will not stop with their help then this OnePlus 3 is our phone then we will add this three plus three this sequence will continue this phone Done plus three plus one if we add this also I thought this body z6 here and this three plus one this phone is done so in this way five forms have been made Okay let's start courting before that a small officer observation and This is our list, there will be some indexes in the list, let me say that the first list is the second list because we have to attend the list and this is the fifth list, there are five lists, so if you are making roti, then it should be of that list of 1000. We remember this. So that it becomes easier to code, if you are making Road 2, then the list in it will be Alaska index one in our answer and the texture will be Road 2. Similarly, what will happen to Road 3, which will be Rohit's list index? That will be ours and that will be in this way, if we add this to the list then it will be ours and if we add the index for the list in the final, then our fifth disease is to be seen in such a way that you are coming, okay if then If we have to make through, then our list is for, so if we want to make feeders, then which loot should I use, then we have to use third, and we have to use to make, basically, if you see, you have to reduce two, if you want to make cars, then we have to make 108, you have to make So, for the first index, we will have to use this, okay, so the calculation is like this, if we make five, then we will have to use this, basically two less is sitting, okay, so let's code, this is a simple code, first you have to Write down the list of what to return. Now whatever has to be returned, this is Enter. Okay, let me name it as result. Oh yes, and people have also given names like triangle etc. We call it result. There, let's make lace and make sandals from the base. Let's take the basic and you will not make anything, then what will you do, if the number of days is zero then you return the MP list, okay, now whatever we will save, there will be five more in the result, if we want to make you feel then one. Let's do the work, let's run the loop from 1 to whatever we have, if the number is five then I will write the numbers that it is okay, number five then we will choose the number and we will have to run all the diseases, we do it in this way and finally when we process Okay, 5 more are being made and all five are being made, so you saw in the first promo, there is an element in control, there is an element in the third, there are three, in 434 row there are four, there are five in opposition, so in all these indexes, we will read about making elements. Let's know 106 What should I do, why should I get a lab assistant? Let me tell you, I killed because now this one bay is not sanctioned. If you have to make 5 heroes then they should be less than 5. If the fifth one is there, then basically they will go from zero to four. Well, we covered the fifth roll, so I came to London. There is no need to tease me to make the fifth roll, but at face value it will open in 5 minutes, which you see below, okay and what will we do after finally making the bomb, some photos. In this way we will return our result, all our diseases will fail within it, we have returned it, now how will a single fix, single stop be made, for single stop, we will have to make many cries again and you can make a new list, okay. Now if it works for the first time, it will become the first form, then again it will become the control, all the romance will work, it is us who are creating it, we are creating the role inside it, finally stop losing, we are adding the final inside the people, if the result is ok then the result is fine. We are doing first row control third office phone, okay, so they make all the crops, they make all the templates, write the templates, all the romans will go, so basically what did you see, if this was zero, jain and our last element was this was york, okay. After all, what will happen to us, then there is always one in these two positions, this is zero and the last position is always in Bermuda Triangle, so what is the last element, if we look at 500, the last element is this - look at 500, the last element is this - look at 500, the last element is this - if this then what is we in ours, what is ours in ours 151 but If this is not the decision, then how will you ask people to develop you with the help of the old list? Okay, look carefully at the ancestors, this is a throw, the first element of the throw, how is it being formed, the first element of the row and zero. If I write something like this, the first element of your throw is being formed by stopping the previous zero and plus the first element. Okay, how is your second element of throw being formed? Yours is being formed by adding the first and second elements. Okay, so how is the third element of your ancestors being formed? It is being formed as yours by adding the second and third elements, so if it is to be done in this way, then I will write the same code or So basically what will we do from our recent which is our result in which all the roadies are saved? From that we will take out the previous stop. Okay, we will take out the previous stop like this. If you are on then you need four throws to develop. I did not know in the fourth Roka index that it will be free, only then I had written separately that fourth disease will be hands free so that you can get confused now, doctors are needed to make the throw but not to get confused, it will be for prediction, so I am accessing i-to I reduced it by two, i-to I reduced it by two, i-to I reduced it by two, okay and now what did I tell you here, if you want to make one, then you have to add zero and one, then basically Jain and like one less, if you want to make two, then two has to be taken above the previous rocket and stop the previous one. If you want to take also, then I will take the previous Roka in the same way and will add it to the previous Roka exactly minus one, so in this way, we are becoming an advocate in our 5 triangles, but the final answer to this is fine, we have not added it in our row. Do it, I also add it to the row that if I add it to the row like this, then it becomes mine and all the bread is done in the romance result, final, I stop it, return the result, just do this little work, otherwise let's see, I remove the approach. Next year you must have understood that if there are some compilers then we will fax it, this city can come because we did not comment on it, once I turned on all the alarms, I had set this, I had put Enters Winus, there were many compilers, once I had put all the I have corrected the sentence, let's run it once, it is accepted and I would like to submit to see if it is running or not. Our code is being submitted and see you in the next video, we will cover some more questions, till then thank you. You will get the code in the description. You can subscribe this channel. Thank you very much.
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
147
Hello hello guys welcome koi gautam miding obscene subscribe Thursday subscribe Video subscribe the instructions for telling jhatak praise subscribe to ko uttar pal phase loop fluid subscribe nayyaan kids pe loot subscribe point to point loot your birthday old Person Floor 800th Urs To Do Subscribe My Channel Are Appointed That Element That After All Doing Is What We Do Ingredient That Temple Witch Cold Have App For Scheduled To Return Were That Itsel A Heavy Lift And Logic And Kids Will Look After Time Notification Lakshmi Lutelute Recent Events Every Time They Should Subscribe To Is Normal Ukhta Sanstha Art And Will Stop Stopping Start Value Ko Subscribe Now To Receive New Updates Time To Subscribe To Decade In Cases Of Values ​​But In Between Decade In Cases Of Values ​​But In Between Decade In Cases Of Values ​​But In Between Students Subscribe Is Vansh Dividend Was Last Time To Mode Start S It's Not A Good Time Jhal Show Me To Aadha Fuel Time Duis Atm Don't No Point In Way Video Subscribe Next Main Office Look What Mintu Isse Tomato Loot-Loot Code 's Pimples Operational Quality Well - Switch to 121 Giving Correct Results For Mother, this tree and organization thanks for watching till it is over.
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **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\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
910
hey guys welcome back to another video and today we're going to be solving the leak code question smallest range 2. all right so in this question we're given an area of integers a okay so for each integer a i we need to choose either x equals negative k or x equals k and add that x value to a i and we're only going to do this one time after this process we still we have some area b okay so what's going to happen is that we're going to go to our area a which has integers in it we're going to go to each of the elements or values and we're either going to add negative k or we're going to add positive k to it and after this we're going to end up with a completely new area and let's call this b so what we're going to do is we're going to return the smallest possible difference between the maximum value of b and the minimum value of b okay so i think the question is a little bit confusing the way it's worded so let's just go through a simple example so let's go through this example over here so which is a equal to 136 and k is equal to three okay so just ignore whatever is up top and let's just do it from here so a is equal to one comma three comma six and we know that k is equal to three again just ignore the top part sorry okay so over here we have two options okay and let's write down what these options are so we know that our k value is equal to three so at each number okay so at each of the numbers inside of the array we have one of two options so let's go to option one so in option one we're going to be adding the k value which in this case is three and in option two we're going to be subtracting the k value which in this case would be negative three right so what exactly is the main goal of our question over here so the end goal over here is we have to make this operation so either operation one or operation two and after doing it we want to find what is the range between the maximum number and the minimum number so let's take an example right just for the sake of an example let's say we do one plus three so now that gives us a number of four let's do three minus three giving us zero and let's just do six plus three and that gives us a value of 9. so before we calculate what the range over here would be what is the range of the original value so in the uh for the original thing the range over here is going to be the smallest value which is 1 and the maximum value which in this case is six and the difference between them which is six minus one giving us a value of five so in the beginning we have a range of five but now when we did these operations we actually ended up with the range of the smallest value being zero and then nine so nine minus zero giving us the range of nine so obviously a range of nine is square so that's not going to be our ideal solution so hopefully you understood what our main goal over here is and um so i'm not gonna go through how we're finding the solution yet so let's just see what is the answer they got so in this case they had p equals to four six and three okay so they got four so they did one plus three then they got six so they did three plus three and the other value they got was three so that's six minus three okay so this is their new area over here so what is the difference of this area over here so the difference of this area is nothing else but the maximum minus the minimum which is nothing else but three so this over here gives us a difference of three or a range of three and as you can see that is already smaller than what we had originally so in this case we're going to output the difference over here which is three and also make sure we're not outputting the b value here we're only going to be outputting the difference which in this case is three so that over there is the question and hopefully you understood what is uh the main idea behind it and another example let's just say so we have zero and 10. so in this case what they did is it's 0 plus 2 and 10 minus 2 giving us a 2 and 8 and the difference between them is going to be 6 so that's what we output okay so hopefully you understood what the question is asking for and now let's kind of talk about how can we solve this question okay so to understand how we can solve this question let's go back to uh this question here okay the first one so a is equal to 1 3 6 8 12 and 13. so over here we're going to be making an assumption and that assumption is that a is sorted okay so to solve this question we're going to be sorting a beforehand but before we actually go to the actual solution uh let's just understand what's impossible of ways we could solve this question are so at each uh point we have two options and the two options that we have are going to be either plus k or actually let me just change this into plus three minus three let's just make it plus k or minus k right so over here uh i can either do plus k or i could do minus k right pretty simple so at each number we have two options so one thing we could do is we could kind of have like a recursive backtracking solution where we try out each and every possibility so but so that actually sounds pretty good for smaller numbers right but when you look at bigger numbers this is going to increase exponentially so the time complexity would be 2 to the power of n and let's say we had something with the length of 100 we would have a greater than so we would have i think more than 10 to the power of 30 uh possibilities so that's quite a bit right so that will be taking up a lot of time and that's probably not the best solution so now let's think of another solution so the backtracking solution is going to take too much time so now what we want to do in this solution over here is we're going to go through these elements one by one and we're gonna make another assumption so let's just say we're iterating through these elements and let's just call this a i uh or actually no let's just call it a i okay so a i refers to each of the indices or each of the elements inside of area a and over here the assumption that we're going to make is that this over here so whatever a i is um okay so this over here is the max value okay so we're going to assume that whatever is at a i is the maximum value and based upon that assumption we are going to find its minimum and maximum value so how exactly is this going to work so the reason this works over here is because we don't need to output the array b instead we just want to output what is going to be the smallest range that we are going to have we just care about the smallest range so let's see how this is going to work so we want to find the minimum value and we also want to be finding a maximum value okay now what exactly do these minimum and maximum values correspond to so when i say minimum value i mean the minimum value with respect to a i again remember we're taking the assumption that a i is the maximum value so let's just start off with the maximum value and actually before we actually go to this part here uh since we know that our area is sorted what is going to be the smallest value so we know beforehand it is sorted so whatever is at the zeroth index is going to be the smallest value no matter what simultaneously the largest or the biggest value is going to be whatever is at the very ending which in this case is 13. so that is going to be the smallest and the biggest value of that we have so that is something that we want to keep in mind okay and before we actually go through this uh i just wanted to say one last thing and this is kind of a very intuitive thing right so let's just say we're assuming so we don't care what these numbers are okay so let's just say it's some sort of area with numbers okay so let's just assume that whatever is over here is the maximum okay that's the assumption that we are making so uh again remember that this list over here is sorted okay so we're assuming that this is maximum so how exactly can we make it the maximum when our list is sorted and there's stuff on the right of it so to make it a maximum we're going to take this and we're going to add k to it that way it could possibly uh just make sure how i'm saying possibly be a maximum it doesn't have to be but it could possibly be a maximum value so let's say we make this plus k in that case let's just assume that this is now a maximum value over here so now let's see what is going to be the minimum value for this over here so the minimum value assuming that this is a maximum is going to be whatever our smallest value is plus k and why are we going to add k to our smallest value and the reason we're adding k to our smallest value is because we want to be as close as possible to this value over here so that is one possibility right so we could go to our smallest value and add k to it and that could be a possible value for being the smallest of value assuming that this element over here is the maximum now what is some other possibility so another possibility is that we could go to one value to the right so over here so this whatever values over here and subtract k by that so those are two possibilities of finding the minimum value that we have now why does this make sense so let's just look at a and let's take it six for an example so at six what is going to be the smallest value so over here we have the number six and we're going to assume that six is our largest number uh again this might not work out for some reason but let's just assume that it is okay so we're gonna add three to it since we're assuming it's the largest so now it's going to become nine so now we want to find what is going to be the smallest number so since it is sorted the smallest number is going to be whatever is at the zero index which in this case is one but remember we want to be able to make the smallest range possible so for the smallest range we're going to go to one and we're gonna add k so in this case we're going to get one plus three giving us a value of four so four is going to be one possible value now what is an other possible value so another possibility is that we go to 8 over here and we do 8 minus k so that's nothing else but 8 minus 3 giving us a value of 5. so those are going to be the two values four and five and what exactly are we going to end up choosing between four and five well in this case we're going to end up choosing the value four because we have to choose the minimum value over here okay so uh that's how we want to choose the minimum possible value and those are going to be the only two possibilities for getting a minimum value so now doing the same keeping the same thing in mind what is going to be our maximum value now remember that the assumption we're trying to make is that this over here the current element we're on is the maximum value so let's say that this is the maximum value so in that case one of the possible solutions that we have is that we go to this over here and add k to it so this could be a maximum value but it doesn't have to be and in order for this to be a maximum value everything to the right of it we're going to subtract it by k and the basic reasoning behind that is that we want it to be as close as possible to this value and we know everything to the right is greater than it okay so instead of looking at each and every one of the elements we're just going to look at whatever is at the very ending so in this case we're just going to go to this value which is at the very ending so this is going to be the greatest value and over here we're going to subtract whatever this value is by k and by subtracting it by k what's going to happen is we're going to choose the maximum between this value over here so whatever element we're on plus k and the maximum value minus k so if this element over here even after adding k to it is not the maximum when compared to going to the largest value and subtracting it by k then in that case this is never going to be a maximum so when that condition happens so let's say this over here is the larger number so then even after subtracting k let's say it is the larger number so what we're going to end up choosing is we're going to choose the maximum so in this case we're going to end up choosing this okay so um let's just go through this uh more specific to this example in terms of the values that we have so we have to start off by finding a value to start off with so we're going to have a results value and in the very beginning result is going to be uh whatever we start off with so that's just going to be 13 minus 1 the largest minus the smallest and that is going to give us a difference of 12. now why does this uh and you might be like we're not doing anything to it so doing 13 minus 1 is the same as just adding k to everything or subtracting k to everything the difference is not going to change so in this case we're starting off with the value of 12 and again our goal is to minimize the result okay so now let's start off with our minimum value again the assumption is that a i is the maximum value so for our minimum value we're going to be taking the minimum between whatever the smallest value is plus k right because we want to get as close as possible to the maximum value and the other possibility is going to a i plus one right and doing minus k and you saw an example of this when i took six as the maximum and then uh tried it out with eight and one right so this is another possibility going to the next value and subtracting it by k okay so those are we're going to choose the minimum between those two and for the maximum value we're going to take the maximum between a of negative 1 and the reason we're going to negative 1 is because that's the very ending and to that we're going to subtract k and the other value that we're going to be looking at and again the reason that we're subtracting is uh because let's say a i is at 6 everything to the right of it we want to get it as close as possible to six and the best way to do that is subtract everything to the right of it by i that's the basic idea so that's what we're doing 13 minus i uh in other words the greatest value minus k not i sorry k not i okay so the that's what we're doing so going to the greatest value and subtracting it by k and the other option that we have is we're assuming that a i is the largest and since we're assuming it's the largest to make it the largest we're going to add k to it okay and we're going to choose the maximum between these two and at each time our result is going to be equal to the maximum value minus the minimum value okay so this is going to give us one answer but what we're going to be doing is we're going to comparing it we're going to be comparing it with our original result at each point okay so uh in this case with the previous result and we're going to compare our new result and each time we're going to be taking the minimum between those two so let's just look at this exact same example and see what our result values will look like and which one we actually end up choosing so over here we have this the exact same area 1 3 6 8 12 13 and k is equal to 3. so in the beginning our difference is going to be 12 and each time we're going to be choosing the minimum difference so let's just look at one iteration so let's say we go to our very first value over here so that is going to be equal to one and over here the two options for the maximum is going to be between one plus three which is four and thirteen minus three so which is ten so we end up choosing ten so the maximum value we have is going to be ten which is nothing but 13 minus 3 and now let's look for the minimum values the minimum value over here could either be 3 minus 3 which is going to be about 0 and another possibility for the minimum value is going to be the smallest value so this is one plus three which is going to be four so we take the smallest between those two which in this case is zero so ten minus zero gives us a result of ten so that is going to be the result at that iteration so each time we're going to be doing the same calculations and we're going to be having the smallest range at that by performing those calculations so at this point so at the next iteration uh we get 7 and after getting 7 we end up with 6. so at these points we might have gotten different values but we're still sticking with the number six because well so far six is smallest and at the ending of this we end up outputting the value six and that is exactly what the expected answer is so now let's see how we can translate the same algorithm that we just talked about in terms of code okay so i'm just gonna go through this because i think that's pretty simple once you understand what's going on so the first thing is that we're sorting our area a and after doing that we're going to start off by defining our result and in the beginning it's just going to be the maximum value minus the smallest value and in simple words the maximum is whatever is at the very ending and the minimum is going to be whatever is at the zero with the index so that is going to be our result now what we're going to do is we're going to go inside of a for loop and we're going to be going through the indices and we're going to start off at the zeroth index and we're going to go all the way up to the last but one value so that's where we do length a minus one right so we don't want to go up to the very ending and the reason for that is because we have to account for the index plus one value over here okay perfect so over here uh we have to find the minimum value and it's the same thing that we talked about earlier and this is over here the maximum value and we calculate that and then we're going to take our result and for the result we're going to choose the minimum between the previous result and the currently formulated result that we got and that's nothing else but maximum value minus minimum value and the previous result which is uh well just res okay and we're going to do this for all these iterations and at the very ending we're going to return whatever result value we have okay and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and yeah don't forget to like and subscribe thank you bye
Smallest Range II
nth-magical-number
You are given an integer array `nums` and an integer `k`. For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after changing the values at each index_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 3 **Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Math,Binary Search
Hard
null
326
Hello Everyone Laddu Solve Question No. 326 Power of Trade Today To Give Shape In This Question Were Given And Interior For Example Shesh 9n Vs To Determine Weather Its Power Of Tree Not To Not Considered To Power 2012 Similarly Saffron Represents Power Will Return Force Okay So Let's see circular solution for this problem solution which can extend to the prime numbers the show for example 357 2100 ok straight forward solution first effigy in this list and one should not power will return for a key and what will do is will give dividing Will Give It And It's Divisible By Three Look And Have Or Face Divide Rocky Dividing Road Visual Methane And Indra And Will Check If N Is Equal To One Which Will Stop At One Of Its Difficult Acids Bases 512 MB View It's Okay Subscribe 15053 Vikram A Pipe Notice For This Not Divisible By Three Little Pigs Is Look And Will Get In This Will Check This Condition Is Indicative And Tennis Request 510 Will Return For Us Map Combustion Of Glucose To 9 Vacancy Date Individual Life In This World Will Enter This Look first will make any query for ok from which in which country li that your after in this view divisible by this vital and mental figure main course to one ok no vendors not divisible by three most welcome on air at will check weather and request 1st request one Solution with which we have controlled that Lakshmi this election 123 walking lets check and 5 one by one it has happened that this shift in all states walking as well as 406 the city was walking Lakshmi decor a that avoid of youth summit submissions and tried to different things suede shoes working ok this is a solution so let's say solution avikal solve this ok so 500 index solution what we will do it is will take the patay sisai the problem description what we will do it will take to the greatest number withdrawal which is the power Of This 231 - Subscribe For Example Of This 231 - Subscribe For Example Of This 231 - Subscribe For Example Main Isko Pardesh Jo Sudur Power 31.22 The Power That's Even And The Jo Sudur Power 31.22 The Power That's Even And The Jo Sudur Power 31.22 The Power That's Even And The Great Is In Which Is The Power Of Three Languages ​​In This Is To The Power Languages ​​In This Is To The Power Languages ​​In This Is To The Power Notification Printed Spelling OK Suggestion From Shiv 1000 Prime Number VPN Se Data 119 Is Oil Divisible By Value Research Center Power 04023 The Power Of That 19th Correct Too Difficult Eminem Which Is A Word To Successfully Divide Into Power - 01 2010 To Reduce Power Of Three Okay Power - 01 2010 To Reduce Power Of Three Okay Power - 01 2010 To Reduce Power Of Three Okay Let Me Tell You One Second Sisakti Is The Prime Number 90 Power Is oil divisible by values ​​from there power 0232 power 900 by values ​​from there power 0232 power 900 by values ​​from there power 0232 power 900 withro power in the middle east and solution and similarly solution to the prime numbers where given the power to two things on a wick in this way can find the greatest value of five to the power wich Acid rain for example in more just not example for this is the correct way we will take and difficulties with this book will be with us one person one and any possible to divide and rule se edit ok decide solution so let's 1000 solution show will return map Race and MP3 that you power 9900 value filter power known from Google fennel to the power 99 from it spoon or fragrant liquid is reduced so is three to the power 90 is divisible by name ok Vidron in every individual can not Vidron true because people did not believe In them which will give 0 fall flexis disco dance yes it's getting chapter 10 minutes that gas so this is also getting submit should you can solve this problem ok n you can extend second solution 2nd power of prime number solidification more ok thank you for watching a
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
642
hey guys we are going to discuss a hard problem and this problem is basically an application of tries so the problem is known as design search autocomplete system the description of this problem is quite long i'm not going to go through all of this but i will explain you the main problem we can read the first few paragraphs and i will give you the explanation after then i will place this text in the description or the link to the lead code that you can later have a look at if you want to have a further look so we need to design a search autocomplete system for a search engine and users may input the sentence in at least one word and end with the special character which is hash and we are given a string array of sentences and an integer array of times and both have the same then if you see over here in the example so for we have here is the array of the sentences so we have different sentences like island iroman i love lead code and i love you then we have the times area which is 5 3 2 so this basically represents the frequency of each sentence so let's say the first sentence has a frequency of 5 let's say 5 minutes and then the second sentence has which is island takes let's say three minutes and so on and for each input character uh except for the hash we need to return the top three historical hot sentences that have the same prefix as part of the sentence is already typed okay let's see the example so first prefix is i we check that the first keyword is i so we need to check we need to return over here when the input is i then we have the search results would be everything which is starting from i right so we have four all four sentences are starting from i over here we saw that we have to return the top three historical hot sentences that have the same prefix as part of the sentence which is already typed okay top three we have to return so that and that would be based on the time the priority of the time as well as if and if in this case for example two of them have the same frequency so in this case what we gonna do is that we are going to take for example iron main and i love lead code have the same frequency right or the same time so we will see the next word after i which is r over here and the next word in i love lead code after i which is space over here and we know that space has the ascii character value of 32 and r has the ascii character value of 114 and because of that i love lead code will be higher priority because the time is the same for most of both of them so the first three sentences would be i love you i learned and i love lead code okay and that is shown over here in the example and then the next word we have i and space so everything which is starting from the space so space is basically the next extension so let's say you are typing it into the search engine first you type i so you have those three possibilities and now you type space so i in space your search results are reduced to i space love space u and then i space love lead code okay so we have two of these sentences because after i there is a space in two of the sentences right and then we have a so if we have a we do not have anything with i space a so that's why it will return empty list and then we have hash and they tell us over here that hash for each input character except for hash so when there is a hash then we have like it returns an empty array if c is equal to hash and stores the inputted sentence in the system okay so when there is a hash okay then whatever was the input sentence which was i space a this is this sentence you are going to store it into the system so this will become part of this list okay so now we will have five words and this would be i space a would be the next one so we need to implement this uh this logic we need to come up with this output when we are applying when we are when we have the input i when we have the input space and so on so i think you got the idea so let's start with the implementation so as a first step we need to initialize our data structures okay so we can take one let's say lookup table and we can say lookup and we can say that this we can define it as our dictionary right so this dictionary will basically contain the elements let's say that it will contain all the sentences along with their frequencies okay so we can say for let's say s in sentences so for each sentence we can store it into the dictionary along with its specified time right in order to keep the time over here we can say let's say i comma s and we can say enumerate of sentences and here now i can give times of i okay so this is the first step so now we have our for each sentence we have something we have its corresponding times okay so the next thing would be to define and let's say this self.lookup and let's say this self.lookup and let's say this self.lookup and we can say so this will be self.try so we can define self thought to try this is our try data structure and we will implement the class of try okay all right and now we must also define some function inside our class try our try must be filled with it must be initialized with all the elements in our sentences okay so we can once again call this loop and let's say for s in sentences and then we can say uh self.try dot insert self.try dot insert self.try dot insert and we will write our insert function and then insert of s okay so that would just insert for each sentence for each letter we are going to create our try data structure right so this would be something like so we have i then we have a space we have some space and then we have l and then we have po and then so on right so something like this it will the dry data structure will be formed right all right the next thing is our keywords okay so currently our keyword is empty and in our keyword we will keep these values like i or space or whatever the keywords the user types right so we have to have we need to have a variable for keyword okay so this is also something we are going to initialize okay great all right so now we are over here at our user function so that would be the user input and we can say that okay so now we have now we need to check over here so what is our c so first we also have a condition of hash if it's hash then we just need to return 0 and we need to store this element into dictionary right so we can just say we can just check over here that if c is equals to hash in that case we can say our lookup so the lookup of keyword so self.lookup keyword and this will be so self.lookup keyword and this will be so self.lookup keyword and this will be updated and we will say cell dot keyword self dot lookup dot get so we will say self dot keyword because we need to get its frequency first comma zero okay and then we will also update its frequency right so that's uh and if it doesn't exist we are just going to place one over there and if it exists then we are just going to increase its frequency right the second thing what we can do is we need to insert this element into 3a because uh because we talk about as the question says that if it's hash we need to save it into our system right so that would be cell.tree a dot insert cell.tree a dot insert cell.tree a dot insert and then we can say self.keyword and then we can say self.keyword and then we can say self.keyword right and then what we could do is that we can say self thought keyword so now we can empty this keyword okay so it's nothing like you can say uh we can say that this word this keyword is empty now and then we can return the empty list as it's mentioned in the question and what would be the else part so the else part would be that we can say self dot keyword and then this would be plus equals to c okay so we can just add into this one and then we can define a list right in this list basically we need to contain the sentences so whatever was the search results so our when we search some keyword so that would return us what sentences it would return okay so it will give us some sentences so when you say i then it gives us four of these and then we can it will give us four letters or four sentences which are starting with i and then we can cut down to three okay so that would be a list right so it would be a list of four words right so we can say that self.try right so we can say that self.try right so we can say that self.try dot search and then we can say or we can say self.keyword or we can say self.keyword or we can say self.keyword right and then we can say over here this list would be we can sort this list okay and how so this will be key is equals to lambda and that would be lambda x and we can say look up because we need to get the time for it so look up of x so for each element inside ts then we can say that we search for the lookup and then we can say comma this would be x right to order it by the descending time because five is the biggest one right it's not in ascending order so this will be minus okay what else we can then return our list and that would be the three elements so three so zero one and two okay and this would be self.lookup okay and this would be self.lookup okay and this would be self.lookup so now let's try to implement let's start implementing our 3a class okay so this will be class try i'm sorry for the wrong pronunciation it's try it's not 3a great so let's say defined our init function for initialization and that would be say self comma okay and here we can just uh we can just initialize let's say the root element or the dictionary so this will be our dictionary that will contain the elements of try and then define our insert function and this will be self and what else we are passing over here that would be let's say we have a sentence okay so this would be so we are passing into an insert we are passing a sentence over here right so this would be a sentence so okay so what we can do now so let's define a local variable over here which will be equal to self dot root right and then we can say for each word in sentence right so for each word in sentence like now we have i there is face then love then you so for each word in sentence or each character in sentence let's say we will say current of w and i think we can you can also call it as c but i'm also using c over here so i will call it w so this would be for each let's say letter okay let's say letter so this would be current of letter and this will be equivalent to a dictionary okay and we can also put a condition over here first so if l not in current then we can say current of l is equal to dictionary and then we can say current is equals to current of l okay so by this what we are going to define is that so we have something like this now let's say i and i have a dictionary initialized for it right so that's our idea and in the next one i have a space over here so i will place it inside this space and that would be space and i have another dictionary inside it like this and i'll create another for the other word which is l then i have another dictionary so this is basically nested dictionaries that i'm creating for o it will be another one and so on okay so it will continue something like this so this is how i'm implementing the tri data structure i can say now that current of hash because it will reach to the end of the sentence okay and when it will reach the end of the sentence what i'm gonna do is that in the end the hash so current hash so at the key hash i can store the whole sentence okay so i know that the sentence has ended over here okay so this is the insert function and now we can define our search function as well so the search function would be define search and we can say self and then we have also a prefix which is this i right so all the words that you are typing so that would be the prefix and then we can say current is equal to none over here initially and if let's say current because initially current is null over here so we can just say current is equals to self dot self.root dot self.root dot self.root okay great for every character in prefix so we can say that if c not in current then we can say we can return an empty list okay because it doesn't exist over there and if not then we can just say current of c so current will be equal to current of c all right we can define our list let's call it answer and here we are going to append the sentences that are starting with i for example so we started with the prefix i and now we can check like for okay so we can say for k in current so we can say if k equals to hash so in that case we can append to our list the sentence and otherwise answer plus equals to and we can recursively call this function self dot search and we can pass an empty string so for the first time you have i and when you are going to call the next time so we are going to pass the rest of the string so for example i is there and then the next one would be the space okay so we will pass this part of the string okay so we are going to recursively call so this will be current of k okay and then it will go nested until it reaches the hash and then it will return the sentence it will add the sentence into our answers and then we can return answer and i think that's it um let's try to run this code let's try to run this okay so we say it says that lookup is not defined so this so the problem is self.lookup so this so the problem is self.lookup so this so the problem is self.lookup here okay it seems to be accepted the solution is accepted let's try to submit this solution great so it works so i hope you guys understand this problem thank you very much for watching
Design Search Autocomplete System
design-search-autocomplete-system
Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character `'#'`). You are given a string array `sentences` and an integer array `times` both of length `n` where `sentences[i]` is a previously typed sentence and `times[i]` is the corresponding number of times the sentence was typed. For each input character except `'#'`, return the top `3` historical hot sentences that have the same prefix as the part of the sentence already typed. Here are the specific rules: * The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before. * The returned top `3` hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same hot degree, use ASCII-code order (smaller one appears first). * If less than `3` hot sentences exist, return as many as you can. * When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list. Implement the `AutocompleteSystem` class: * `AutocompleteSystem(String[] sentences, int[] times)` Initializes the object with the `sentences` and `times` arrays. * `List input(char c)` This indicates that the user typed the character `c`. * Returns an empty array `[]` if `c == '#'` and stores the inputted sentence in the system. * Returns the top `3` historical hot sentences that have the same prefix as the part of the sentence already typed. If there are fewer than `3` matches, return them all. **Example 1:** **Input** \[ "AutocompleteSystem ", "input ", "input ", "input ", "input "\] \[\[\[ "i love you ", "island ", "iroman ", "i love leetcode "\], \[5, 3, 2, 2\]\], \[ "i "\], \[ " "\], \[ "a "\], \[ "# "\]\] **Output** \[null, \[ "i love you ", "island ", "i love leetcode "\], \[ "i love you ", "i love leetcode "\], \[\], \[\]\] **Explanation** AutocompleteSystem obj = new AutocompleteSystem(\[ "i love you ", "island ", "iroman ", "i love leetcode "\], \[5, 3, 2, 2\]); obj.input( "i "); // return \[ "i love you ", "island ", "i love leetcode "\]. There are four sentences that have prefix "i ". Among them, "ironman " and "i love leetcode " have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode " should be in front of "ironman ". Also we only need to output top 3 hot sentences, so "ironman " will be ignored. obj.input( " "); // return \[ "i love you ", "i love leetcode "\]. There are only two sentences that have prefix "i ". obj.input( "a "); // return \[\]. There are no sentences that have prefix "i a ". obj.input( "# "); // return \[\]. The user finished the input, the sentence "i a " should be saved as a historical sentence in system. And the following input will be counted as a new search. **Constraints:** * `n == sentences.length` * `n == times.length` * `1 <= n <= 100` * `1 <= sentences[i].length <= 100` * `1 <= times[i] <= 50` * `c` is a lowercase English letter, a hash `'#'`, or space `' '`. * Each tested sentence will be a sequence of characters `c` that end with the character `'#'`. * Each tested sentence will have a length in the range `[1, 200]`. * The words in each input sentence are separated by single spaces. * At most `5000` calls will be made to `input`.
null
String,Design,Trie,Data Stream
Hard
208
1,698
very special to make that Jan and also not with the thing I screen the web both on the day before the leak chill the trip first be the tree sees the folding bike graphing yes malic acid and the number of the stinks and confused Marcus is vinkt substrings in clothing and piece of spring is your blubber the program sing the square okay then not modular long Brazil fewer problems I praise yes that is our country who the listing substrings soy in is under duress this was a means let's get it again sam policy ii baby zo lions in the substrings old town with i had my baby and in full mouth tim schmoyer is the goldie for assisting sat function next in order to pick everything already sphinx that city with whom the throne bibi of your neck and see all those also via the sting just as thick oh the substrings that start with ii sorry i and ii neck you are already quite big that looks like a baby oh yes well knowledge that is tim knol big as i lay low baby that is so negative that is already 10 such things which is the sun this is 10 samsung shirts and plus one my money taken this machine to put it yes I think ms upstream me so the thorium desk testing substrings is naughty but oh yes pull now harry will just oh my partner she can wash blood for sweden will so the pants Muslims weresepe what a scary kennel anyway was definitely state oil very effective bye oh yes then last index there is one thing the rich and poor definitely do next to do something which you alone sonia by picking dikkie dik so wrong with that I am really there the mystery and the economic mission beebe brakes euh who and baby who enter b&amp;b brakes euh who and baby who enter b&amp;b brakes euh who and baby who enter b&amp;b the IBM who they musically strikes the articles that and roy costs and I something looks of interest to me and I know a man look is that they news absolutely so I have to it is on those LEDsky substrings and those and try to get a lead on the station rai and coolest and meineszlaan dixons and look lets do because I s that article also sti-r plus s okay let's do this also sti-r plus s okay let's do this also sti-r plus s okay let's do this and the enormous can the listing franky effect mitch downs the so then I am in the set eliza and so only the 16 year now what we do the sportier code in Egypt and that the bird black bull the dog that of his friends sd by size with pin the is not dead size this would bring the number of the sting soft drinks it turned out to be true heaven just to solve it later of complex ones using a beagle and google plus oh no robic or and maybe there is baby and square healing so they have to start a war I am to reach and one is also in the spring the jumps like that and see there is a square in the lungs and we and is the number of elements in the set the wax is break in the pain complex which is just examples party of flashes that are already too sports glow blood led undefined index hi I sell I can from the Jean-Luc is hi I sell I can from the Jean-Luc is hi I sell I can from the Jean-Luc is from the you now finally deminor be your listing was quite a bit for the cherokee swimming o you now think it stinks photo substrings jquery arne sting generating see everything you will see me who we who at who am I am not work is also a old sap century to the stuc just see that is so crazy rising to the a minimum substring lent will be one to the max substring glenn 2be and the minimum sat freeland only look helmets that around station and the cheek and the market sometimes have absurd things and she undertook bridge healing and way to be that plan of the city frink's song name bridge something on a [ __ ] bridge something on a [ __ ] bridge something on a [ __ ] mix endless summer not included because without now mean such an area wiesel hug ribbon and so arena baby and at the physio okay remix absolutely since the committee is arrest lars as fix what you together linear effort rooms humorous advice with suddenly quest absolutely like imam and square substrings in the set such a square touchscreens in the set I want my Swiss quality and every substring and sap pi and we wandering I was then in the steaks blog myspace you always offer beagle puppies your family you always beagle trees with like Jim and who string in the self wants us on nothing wrong with and my goal the snow globe and audience and qbuzz antink the class xx also in Sweden linear nutrition bacon his child not lab pension pots it is not the case that I am not too hard so that is my IP and will therefore be a problem you see that is promising it was nothing so [ __ ] gardens [ __ ] gardens [ __ ] gardens I have a new swimming hardly myself spring hare in Brussels so this is the price if we are different with the problem in shock well I understand I shouted from the closet when you finished couple of strings line baby so instead in order to abbey and abby music by people of old and new book for spaceback you in advance for you along PSV offer your arm from earlier that warm air and write and for that reason your answers for price is for the statement mbh skin and other drivers and a set this is welcome preventive and beagle 2 so it can be turned out that or legal at foundation rescue they leek beer the specie use baby can be used by ebay and so not barbie I didn't know that fingers to prime me this is a blog mango and project so that we will be using place the chair-back the sensor space using place the chair-back the sensor space using place the chair-back the sensor space complex ones that are also in HD I understand costs furniture her eyes stations and foundation them a week and on and north and blood the reader space lab this is a cue other I finally say the glow computers and seemed to keep the distinct element slept her and claim from a simple plan and the import okay I think with about wheel sublimo the night to get started at if so if you I so articles scream and do really be taking everything a square well how do you know who all audio ghibli is roof jumping something is in the cinema and so I think that I am on the train and in inserter and vortex and there I think now cloud and you thought that is how I should do it literally now absolutely sammy baby bottle of whiskey and radio system and the six we are doing now the cuffs was who storms in the stem cells red so if I got the slot so wifi coverage so private friends baby bottle in a box like that touchscreens in google play they we learned so they still have energy they win the post like ring state oil that's it that's food without your 0 sorry point pins from mickey and clients from now st cia in so does sama you see that I still industry is not so aroma next before never amphibian baby so your voice not berlioz the lift a spray oil in surrey and created leave-in spray in foil and turn scoop in there leave-in spray in foil and turn scoop in there leave-in spray in foil and turn scoop in there will be no bioland and us soccer she could catch for this then next classic baby think so 0 in so expensive end googling raven's cry or I only miss in such losses who that I so 0 okay people and goods pinstripe the string is then peter now it's time the goal now one thing off biebels like a Turkish one more and those areas and we there's a for business at Vincent a nixons the closet hey this is Tim from a business English so full nothing license for you yes everything who Jesus your mechanical beasts the sander witjes in durbuy and ang something like that and thus reference price so next i did i know is a sorry to save my thread hi mom the greenhouse for who gets wet who you who I so no reason sorry and indeed a travel so and miceli long with if you only go to the tame or on such a weekend you have slightly older eyes hole sphinx that stands with who they who wins who is a sugar and beer who will sink brings so who your goal is number pico the guest frink's the city which i you will see the golden hole sphinx there with platy that is the yes noomi puzzle i already ritual lemmings people of flip level louise's with me nothing who those beers yes players oil is that butterfly is with amy never comes took the baby let's call the stallion ambi that who rests yes never from google are the ankle 3 with this can actually be done for plus one 5 the chairs service and there with a and b one side and the other one them in c is i am the juice profit is the thing sorry in bordeaux and ni zoë barrel i this team city frink's that it is a complex that i want harley day in you will be in such things now look at them like and see that a purchase slightly dim libido and square decision to live in such a thing for a long time and 3d the new house can do things in you so you do this is to offer that the stocking is not a piece biseswar before I see the internet you on my the pain complex that toe and square and the striker of flashes those ends plinius video for price you can not measured I was this I have a link could make everything price make sure that it 3 users to be with peace but that was choose you can see I quarrels that I do in the queries xps all Buddhist no that criticism old Russian no thick 20 but this is he knows that I have a bit of what your mustache is going to happen this week and I still have to climb that space lab I am I think the wheels in the switch are a top so do you want a clock okay like that or it's pretty cool so a typical signals like that engine the typing lesson plus cores bing do you on the line of the you chord is another kingdom straight out of the cooling so live in twice in the string articles s now require is I know where they left app download to a that the rod so that we can be your audience and so your goals they acted Klaas or emergency select the class or still and the symbolism what a trillion was ready to things so then I think water hole in place so week and just click in that doubling place but that's and those members are the that's not dead yet pool in flex oil in I never try I were witjes don't go check if I think that's how a ski character can be very gothic and his so rigorous well then on the left see is my family he knows his here in shock and new price his week in a church budget shelby chickens and north star never we are like a healing other articles dikes now in such the without evans needs and does will be the tenth ready in terms of and I was the next long side in nootdorp stargate know yes I see it and I combine I do through the left siege my energy and the things will survive about 100 public water glass and donk collection is justo kan so 10 substrings swiping type can the I orders that on yes and I a keymission room and that is already who is required a new the sole and saki within a new nut and roofing black end some see that acid and more dock size and then I in the score close to bike plus and I am right okay this is the thyme and I had a semi a note I hear the call for a moment it seemed like it took in the breed all the stops lecture by Jelle his own is by size g plus and that you can put them in the nucleus, the need is best Norton agree so private words and he wants me to find the northern point never one this so niro and I want okay and because again shorter and not giving a night product then I got x man I am so in that neck tube and yes you can do I and rather than the connection and that's how I learn can the bottle cheek wine glass from him that man once has can she can I want to see so obvious this is far from it can be plastic that are new others in shock and you so we can easily can the so 10 substrings that is teasing that his turn leek and yes do n't you do they are DVD shop Charles anti-glare or not actually is that you anti-glare or not actually is that you anti-glare or not actually is that you can put those clothes on them this is the they of the adults in chance or interviews I my pias is a child so upload and think willoughby smoothly hp she flows on your cheeks already cycle process wants that your welcome just in case your it takes place a little lagg the video and I now know that the shadow Facebook and the subscribe I have the chance to Google or and after xxxl oh [ __ ] is jeshua points day and xxxl oh [ __ ] is jeshua points day and xxxl oh [ __ ] is jeshua points day and the subscribe button well yes I had that and you are crazy dead so finance is digicore a week full will be in the description ethnic chic and apricot alarm people and using that and I look into the wielelei kenny things from sex stories icons on my spot then ideal their parents that they have stories of people using to services that you know those things that google microsoft and all those had the hairdresser the most then preece bless and check all the links we within discussion now check them out and yes peace cloth and sisters subscribing so this is the video lesson none of this but with that team yes first okay start killing you
Number of Distinct Substrings in a String
replace-all-s-to-avoid-consecutive-repeating-characters
Given a string `s`, return _the number of **distinct** substrings of_ `s`. A **substring** of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string. **Example 1:** **Input:** s = "aabbaba " **Output:** 21 **Explanation:** The set of distinct strings is \[ "a ", "b ", "aa ", "bb ", "ab ", "ba ", "aab ", "abb ", "bab ", "bba ", "aba ", "aabb ", "abba ", "bbab ", "baba ", "aabba ", "abbab ", "bbaba ", "aabbab ", "abbaba ", "aabbaba "\] **Example 2:** **Input:** s = "abcdefg " **Output:** 28 **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters. **Follow up:** Can you solve this problem in `O(n)` time complexity?
Processing string from left to right, whenever you get a ‘?’, check left character and right character, and select a character not equal to either of them Do take care to compare with replaced occurrence of ‘?’ when checking the left character.
String
Easy
null
80
hello today we'll be solving the problem number 80 of Lee code remove duplicates from sorted array to give it an integer array nums sorted in increasing order remove some duplicates in place such that each unique element appears at most twice the relative order of the elements should be kept the same since it is impossible to change the length of array in some languages you must instead have the result be placed in the first part of the array nums more formally if there are K elements after removing duplicates in the first K elements of nums should hold the final result it does not matter what you leave beyond the first K element return K after placing the final result in the first K Slots of num do not allocate extra space for another array you must do this by modifying the input array in place with o of constant time memory so to explain my solution I will use the example provided by the question the array one two three we'll solve this using a two pointer approach to start we'll move through all the elements of nums we'll keep track of the loop using I and we'll keep track of our second pointer under the name of index and we'll keep track of the number of times a number has appeared under the name count we'll begin the loop at the first index of the array and the second pointer at the beginning of the array count will also start with a value of 1 because we will always read in at least one number in this Loop we will compare the values found at num's I and nums f as noted here if the two values are equal then we will increase the count then we'll check if we have exceeded the number of duplicates if not then we increased the second pointer finally we'll replace nums f with nums I with nums F uh denoting num's fintex if a num's i does not equate to nums F then we will increase the second pointer and reset the count then we will substitute numbers f with nums I will continue doing this for the entire array and as you can see we end up with findex equals three as you can see it is lacking by one since we instantiated it with a value of zero so you will simply return this Value Plus 1. to begin coding this we'll first Define our counter and our pointer which will look like this to begin coding this then inside the loop we will make our comparison and check to see if there are more than two of the same elements and act accordingly finally we'll simply return the second pointer plus one as you can see in my code I also added a line that checks for an array with a size of two this line isn't really needed as the loop will still take care of arrays of this size but it does give some Assurance regarding an edge case for this problem so if we press submit
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int\[\] expectedNums = \[...\]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\] **Output:** 5, nums = \[1,1,2,2,3,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,0,1,1,1,1,2,3,3\] **Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\] **Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order.
null
Array,Two Pointers
Medium
26
69
in this video we'll be going over square root of x given a non-negative integer x root of x given a non-negative integer x root of x given a non-negative integer x compute and return the square root of x since the return type is integer the decimal digits are truncated and only the integer part of the result is returned so in our first example we have x is equal to four the square root of four is equal to two so we just return two and our second example we have x is equal to eight so output is two because the square root of eight is two point eighty two so we remove the decimal part um we should we can also think of this as we have two times two is equal to four and four is still less than eight but with the next number three we have three times three we get nine and nine is greater than eight so we cannot pick three so let's first go through a thought process the square root of x is in the range of 0 to x divided by two plus one since our range is sorted in ascending order we can implement a binary search approach to find the target value so for each of the mid value we will calculate the square of mid and square just means mid times mid so square let's go to mid times mid so if square is equal to x then we have found a target value then mid is our is the target value if square is less than x then square may or may not be the largest square that is less than x so we will need to search rightward with mid inclusive if square is greater than x then we will need to search leftward for example if you have three and then three times three is equal to nine is greater than x so we need to search leftward from mid minus one now let's go over the code issue the code so create two variables left the current left boundary initially zero and write the current right boundary initially x divided by two plus one and then while and then we're going to perform our binary search while left is less than right calculate the mid index so mid is equal to left plus right minus left divided by two and plus one the plus one just picks the upper mid value so example we have the current elements is one and two we will pick two instead of one so calculate the square squares go to mid times mid and then if square is equal to x then we can return mid else if square is less than x we will need to search right word with mid inclusive right here if square is less than x then square may or may not be a larger square that's less than x so when you search right so left is go to mid else we need to search leftward and then we can return left which will be the largest square that is which f times left will be the largest square that is less than x let's go do the time and space complexity so time complexity is equal to o of log of x where x is the input value minor search and our space complexity is load of one now let's go through the code bring our boundaries we're going to cast it to long to prevent overflow and while left is less than right calculate the mid calculate the square this is the part where we prevent our overflow because we're squaring a value mid so if square is equal to x then we can return our current mid value but cast it back to int then else if square is less than x and we search right word mid inclusive else research leftward and then we can return left but cast castle to end let me know if any questions in the comments section below you
Sqrt(x)
sqrtx
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well. You **must not use** any built-in exponent function or operator. * For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python. **Example 1:** **Input:** x = 4 **Output:** 2 **Explanation:** The square root of 4 is 2, so we return 2. **Example 2:** **Input:** x = 8 **Output:** 2 **Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. **Constraints:** * `0 <= x <= 231 - 1`
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
Math,Binary Search
Easy
50,367
237
hello there so today's legal challenge question is called a delete node in a linked list so we have a singly linked list and we have access to a node that we want to do a deletion we need to you know write a function to perform this operation so as an example we have a linked list for five one nine we've been given a pointer points to the node five so we want to achieve a go that the end result link list will look like for one night so think about this we are working with singly linked lists and we only have a pointer to pointer points to node 5 so since it's a single living list there's no way we can go back to the floor and ask a note force to point to node 1 instead of five - you know to node 1 instead of five - you know to node 1 instead of five - you know to perform the actual deletion of this particular node there's no way we can do that because it's a single linked list and we couldn't go back so to achieve the same effect what we will do is to copy the nodes value the next knows value you know change this file into one and have this next pointer instead of pointing to one it will points to nine so you will look like if the you know the original node file has been deleted from the linked list but in reality it just copies the next nodes value and short the next node instead of the node itself because there is just no way that we can physically delete this node that have been given to us you know unless we have a pointer that's - in the previous have a pointer that's - in the previous have a pointer that's - in the previous node since that this is singly linked list there is no way we can do that so I guess this is where the confusion comes into play when you look at that the description is called delete node but we're in fact in reality you couldn't really delete this object yeah I guess that's some question you can ask her to clarify do we really want to delete this physical object or want to achieve the goal as if it looks like this thing has been deleted yeah so with that the code is pretty simple we're just going to you know copy the next notes value and then have this note points to the next so this show work it's a void so it doesn't return anything all it does is still copy the next notes value and then Shore to the next note so that's the question for today all right
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
39
everyone in this video we will be solving a lead called medium level problem number 39 combination sum the problem statement is we are given an area of distinct integer candidates and a target integer target we need to return all the unique combinations of the candidates where the total of all of the numbers is equal to the target we can return the combination in any order in example number one the candidates are 2 3 v 6 and 7 and the target is 7. so based on these numbers we can build a total of two arrays or two combination of numbers which will give us the total seven one is two three and the other is just seven we are allowed to repeat the same number multiple times hoping that you understood this problem statement let's switch to whiteboard and talk about how this can be solved now thinking from the simple solution to solve this problem the first simplest approach is a brute force where you will start with a tree and try to add each number and see if the combination adds up to the total for example starting with an empty array because we have three combinations or three inputs given we will split it into three parts first is two three and five so with two we can either add two either at three either at five similarly at each layer you will keep on checking for all the possible combination that is given to us in the candidates array so let's try one example over here so starting with empty when we are at this first two my total is 2 then if i'm going to this leg i might new total will be 4 if i'm navigating it down to the next layer or the next leg my total will be 6. similarly i will continue the next leg and now i got my total eight because this matches to my target i will add these four or these legs to my result as you can imagine this iteration is going to be a lengthy one and we will definitely end up doing some duplicate calculations for example when i am at this 3 position my array contains 2 comma 3 because my path is starting from this 2 to this 2 and then this 3 if i go a different way so from this 2 let's say i'm going to this 3 so my array will have 2 comma 3 from this 2 i can go to 2 3 or 5. if i go to this leg with the value 2 my new array will have 2 comma 3 comma 2 which is same as what we have already iterated hence there are several duplicate combination that we will end up doing if we go by a traditional or a simple approach coming up with an algorithm that would run this brute force approach is simple the challenge is to identify the duplicates so let's think about how we can optimize the solution a bit better so that we can solve the problem efficiently the first solution to minimize the number of iterations is to order the input into ascending order let me give you an example to prove why this will be useful let's say while we are building an array this is the combination that we built 2 and 3 so the total is so the last element that we added to the array is 3 now because this is greater than the target we cannot add the solution but if i can say that my array is sorted so any number after phi is also going to give me a sum which is going to be greater than t so in that scenario i can completely break out of my loop and go to the next combination so instead of adding any more values to this place i can switch to the previous position and start updating that adding this logic to our solution is going to improve the solution and avoid unnecessary calculations one way to avoid the duplicates array we will set a rule of one flow will add the previous number to the sum to the array and the other approach or the other leg will be not to add it when i'm adding the previous number so my array will have array will be 2 comma 2 if i don't add the same number and instead add the next number my array will be 2 comma 3 similarly from this position if i break it into two sections i will have 2 comma 2 and from this position i will have 2 comma 3 and if i dive deeper from this position and break it into 2 legs i will have 2 comma 3 comma the last leg that i added is 3 and on the right hand side i will have 2 comma 3 comma phi so we are always going to increment our index or look at the number that is on the right we will never look back or look at the numbers to the left with this approach of having a rule to split the next leg into two parts we will not be running into the issue of having duplicate arrays because our parents are going to be different and we are only going to be looking to the right hand side of the array and also all of the numbers to the right of the current value on the current number is going to be greater because it is given in the problem statement that all numbers are unique or distinct hence we will not be having the same number again and the other cases we are doing ascending on our candidates array let's apply the same logic for 3 i just use this empty space over here so for 3 the first is going the left leg is going to be to add the same number so i will have 3 comma 3 and the right side will have three comma the next value which is five three comma three the total is six which is less than the current target so we can continue further so on the left hand side of three comma three i will have three because we are adding the same number again and on its right we will have three and five this total is nine this is greater than our target there's no point of continuing or moving forward so we will break the loop on the right leg the total is 11 again it is greater than t no point moving forward so we will break the loop similarly if you look at the right hand side we have 3 comma 5 the total is a which matches the target we will add this to our result so with this solution our time complexity is 2 raised to the power t where t is the target the reason for this 2 is we are splitting or we are having 2 legs after each calculation and the maximum depth of this tree is going to be equal to the value of t because we won't be going deeper than that i hope you are able to understand this explanation to solve the problem efficiently let me show you how we can implement the same logic using c sharp here is my c sharp solution in the main method i first organize or sort my array in the ascending order then i am initializing a result variable which will hold all of the array then i call this helper method if index is less than candidates.length if index is less than candidates.length if index is less than candidates.length only then we will go into this if condition then i am calculating this new sum or the temp sum by adding the sum that we have calculated so far the current position that index is pointing if the temp sum is greater than the target it means we cannot do anything we don't need to iterate forward so we will do nothing if the temporary sum is equal to the target then i am adding the number index is pointing to the temporary list adding the temporary list or array to my result and then removing it so i can use it later on this is the concept that we usually use in backtracking let's say my temporary value is less than target then we will go inside the else condition here's where we are splitting the flow into two sections the first one is we are adding the same number to the nums and continuing the calculation once this helper method execution is complete we will return the value that we have added and then i will call the helper method but this time i will not be adding the current number instead i will be incrementing my index to the next value once the helper method execution is complete i will have all of the arrays in this result variable and i'm returning it on line 9. thank you for watching this video i hope you are able to understand my explanation and this source code is available on my github repository i'll be adding the link to the description below feel free to check that out and i will see you in the next video till then stay tuned and keep 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
221
hello friends now that solves a maximum square problem as I expand this problem as a comparison and the maximum rectangle problem and you see before given to the binary matrix filled with zeros and ones find the largest square containing only ones and returnees area so what's the difference between the maximum Square and the maximum rectangle why we will use stack when we try to find the maximum root angle what's the difference when we try to find the max Moe maximum square well as in the square the case had being much simpler because the square has the same length always side which means they're their height and the width should be the same so we just needed to find the max length of its height and the width so we iterated this matrix if current of charge is 1 we will try to find the laughter and it's up and it's an empty dialog and they will kick as a minimal dance and +1 so we did use the idea dance and +1 so we did use the idea dance and +1 so we did use the idea of the dynamic programming because we want to cache the maximum length it can be in the same place so basically the idea you can use this address of the range some query QD immutable we also catch the since again an extra already so ali scheduie first to that educates check if the matrix equal to naught or the mass balance equal to 0 will return 0 then we get the rows which is the magic yes and the colors will be the matrix the zero tolerance so we will use a two TDP array as usual so what's the size it shouldn't be Rose that's one and the : that's one and the : that's one and the : why because you see even if we are at index zero we want you know it's left and it is up and anti dialogue see so if we let's the tip he has same side of the matrix in a will auto bounder so for simplicity we just lessen these metrics have one more Colin and one more Rose that's the reason so we just iterate it and it started from one and I will less or you go down the rows that process and the for J will start from 1 J and less oil hose end up : j plus J and less oil hose end up : j plus J and less oil hose end up : j plus so if the mattress I minus one because you see we let the this inj destiny is the index in the deep here ray so we shoulda less the I and the J minus 1 if it is equal to 1 we miniature calculate so to know okay we need that you save the max plan so if a coat you want we will the current DP IJ will be the minimum of the three values the one value will be the TP I minus 1 J minus 1 which means it anti dialogue which me this place maximum and minimum DP I minus 1 J and if he I J minus 1 in the plus 1 because current L is 1 we catch their minimum length like if all these are one we plus 1 the maximum less will beat you so every time we pair the mass and there's a pIJ so in the end though we returned their max chance max okay thank you for watching see you next time
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square 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:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
674
all right so this is 674 and it's called longest continuous increasing subsequence so it's an easy level question i would say it's a very easy question and here we're given a nums array along with an output that we need to return which is an integer and what we want to do is we want to iterate through this array and just find the longest kind of increasing subsequence so exactly what the title says and what that would be is this here so it goes from one to three and three is greater than one and then it increases to five and then it decreases to four and then increases to seven so the longest number of times that it was increasing in a sequence four is three so one two then three and then here it decreases so it kind of breaks that sequence and then here it only increases one so that would be one and well a sequence of three is longer than a sequence of one and so in this case it's just going to be one so we know that a one's kind of the default output that we would output so even if you have an array of size 1 we would want to output 1 in that case and so yes why don't we go ahead and implement that so what we would need for this question is a couple of integers so we would want the max which would set to zero we would want the previous value so we'll keep a pointer to the previous value that we visited and let's see a count and that would be set to zero so the count would be the current um number of times this sequence is increasing so with each iteration that's increasing we'll increment that count and if the count is greater than our max we'll set the max equal to our account okay so before all this we'll first just do a base check so it starts we don't have to assume we can assume that the length is at least one so if the length of our array is equal to one we're just going to return one and so we want to do that just because we're using this previous value and how i'm implementing the for loop we might get a index out of bounds error so this is just a quick check for that and so afterwards we'll actually set our previous equal to nums at zero so with the first iteration that means we'll set i equal to one and so forth so well i is less than the length of our array and we're just going to iterate by one of course and by the end of this as you might assume we're going to return our max as we want the max increasing subsequence or longest i guess and so yeah so let's go ahead and implement this what do we need here we want to say okay first if our max is less than our account of course our new max will be equal to our account and at the end of each iteration we also want to set our previous equal to our current so nums at i what else do we need we're iterating by one our account we have our max which we're setting here the count so if our current nums at i is greater than our previous then we'll want to set our count plus otherwise if our oh i spilled that wrong otherwise if our current number isn't greater than our previous therefore it's no longer so this would mean that it's increasing or i'll say still increasing then this means otherwise it's no longer increasing and so in that case we would just want to say our count is now equal to zero and then max is equal to count that our account is no longer increasing yeah let's go ahead and run that i think that's right wrong uh let's see all right so we want to set our count equal to one in this case and here because we want a minimum of at least one just like how we're returning one here let's go ahead and submit that and success so yeah so that error was just that because we want to return one no matter what we wanted to reset our account equal to one rather than zero so yeah i hope that helped i think it's very simple problem i think the main issue with this is just making sure that you don't get that index out of bounds error when you're using that previous pointer so great good luck with the rest your algorithms thank you
Longest Continuous Increasing Subsequence
longest-continuous-increasing-subsequence
Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing. A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]` and for each `l <= i < r`, `nums[i] < nums[i + 1]`. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 3 **Explanation:** The longest continuous increasing subsequence is \[1,3,5\] with length 3. Even though \[1,3,5,7\] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 4. **Example 2:** **Input:** nums = \[2,2,2,2,2\] **Output:** 1 **Explanation:** The longest continuous increasing subsequence is \[2\] with length 1. Note that it must be strictly increasing. **Constraints:** * `1 <= nums.length <= 104` * `-109 <= nums[i] <= 109`
null
Array
Easy
673,727
443
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this farm I'm gonna stop alive right about now 4:43 gonna stop alive right about now 4:43 gonna stop alive right about now 4:43 strain compression given in a way of strings compress it in place that's always a little bit weird I always hate in place things for reason that I could get didn't do the length after compression must always be smaller than or you go to the original way every element of their way should be a character that end of length one after you're done modifying to input away in place we turned a new length of their way could you solve it using only one extra space I thought that's what the employs would do okay let's see you give in some place and this is if you see okay does it have to be consecutive okay I guess it doesn't really actually say or the examples are not super clear on this one I mean something of a cheating it on an interview you know the thing to do it on an interview if you're having any questions just ask the interviewer right I can't do that incompatible whamming before it is because they will give you the answer I just want to see unless that I miss something obvious that what I do answers to fine you know move to a to the back for example like should do ace compressed together like is it next to each other that's what I want to know why is this returning in pins oh it's the size of their new away okay not just Oh I guess I don't tweak it okay let's just look at the expected okay their input/output it's a little bit weird for input/output it's a little bit weird for input/output it's a little bit weird for this problem that's why I'm having a little bit slow reading it but okay so it seems like it is only next to each other so okay so this is essentially a one length encoding which is a way common thing and there are a couple of ways to think about it but the idea in general is just use a 2.2 algorithm general is just use a 2.2 algorithm general is just use a 2.2 algorithm sorry not a to point out one but just kind of keep track of consecutive elements and then the old one extra space is a little bit we and even the in-place stuff is kind of weird to be in-place stuff is kind of weird to be in-place stuff is kind of weird to be honest because I don't know why you need to because that's just because I would say that in a software engineering sense way often you do not need to do things in place that's at best or and yeah at best like an optimization but your API if you change it the input that feels a little weird especially nowadays because that's where these two bugs and stuff like that but yeah okay but that's it so the one coat one length encoding and was a little bit tricky because we might I guess the compression always makes it shorter so it would necessarily be good okay I mean the way that I would check is just one character at a time so I was thinking about how to implement this maybe I would have used a little bit to some pythonic coding stuff but I think I'm just gonna make the code a lot of readable we make the code readable so let's just do something like n is you go to length of chars and then floor index in range of n and I may be off by one here sir so that's just for now let's stop one so then we can compare choice of index with choice of index of my minus one so what happens if they're the same right if they're the same that means that we extend the last index by one right so in that case we just have let's just have kept the increment by one and one is how do we start well they stopped of processing the first character because in that case the index minus one is well our bounds so let's just start f1 and then we put the last character use here's you go to choice of index oh sorry the first character so that and then yeah then else meaning if they're not equal that means that a string has ended with some choice of index as a new character so that means that okay now we have two so they're a couple of things I want to put two I don't want to skip ahead a little bit so I'm gonna put it not in place just to visualize it and then we'll do it in place and the reason why I do it this way is just for visualization because I think otherwise I'm doing like two things at the same time and it may be a little bit harder to follow but let's just have an answer away and then you know damn is that okay that choice of index is starting a new string or a new one length compression thing right so then let's put the answers so that you last count and then the count I'm just double checking whether we need to put the count as one okay so if there's only one character we do not need to put the cat okay yeah that's also coming with one length and coding so that's why I need to look for it but yeah if count is greater than 1 then we append the string version of the cow and now we just have to reset and start a new thing so we just said that and count as you go to 1 and now we're done except for at the very end right because the curse we don't because you could think about the last string as yeah like an ang drink so actually why I could also hear well what I would maybe sometimes do is add a CP do these if statements again but another way of doing it is actually hand doing this chores done a pen just like some end of string type thing and then now let's print out answer because we have to do it in place but you know and then we return the length of the answer and I know that this is wrong per se because we have to do it in place so we didn't put it out but I just wanna get to a place where we double check whether our answers are correct just for testing purposes yeah and it seems like this matches to expect it and put an output wait we just have to put it back into the in place kind of thing okay so now we want to do it in place which is somewhere that I don't like but that's another rent for another time but what are we doing with this answer away right and if this compression you know that the string that you're up you're creating will always be smaller than your original string and index that you're processing so do you think that knowledge let's just say we have another thing called answer index maybe some like that it secures and then here instead of doing and to that a pen that's character we just do choice of answer index is the code to last character enter index + + and then here character enter index + + and then here character enter index + + and then here again chose enter index is equal to string of care and then answer index 1 and now at the way and it's just the answer index is the number of items right cool yeah let's now test some cases with empty string someone say oh is it all lowercase no ask you while you do I think it is worth testing mixing casing I think that's like a something like that's one done yeah looks okay so that's submit oh no oh okay well that's crappy every element of each cow should be counted that end of length one okay I mean I guess I didn't read the problem precisely I wish that there's a test case for that wait David did I not copy the test oh that's okay I retract that statement for some reason I think I was used to order example cases being in there but a parent that is in one of the examples so I have no one to blame but myself I accept responsibility for this one but that is a because if I wear the code it would be you know I would have easily showed that is well obvious so I just have a blind spot and then put in the test case this time but that's fine so in this case and this is still a compression but because for this to be double digits it will be ten anyway like ten or more so you're already compressing a lot of things so you don't have to worry about it over overflowing your current one time thingy for that reason so that's just say string version of the cow and count string is he going to care for each digit in counts string we took this thing okay so now we're good well better I don't know if it's good we're some it again oh wow oh well that's unfortunate so what so you may ask why I'm getting a wrong answer just because I asked you I think I'm just too used to characters being alphanumeric that this time so that's why I just put in like a random string at the end right but this random string is part of a possible output so it basically made my output wall so I think that's actually a good that's a funny one that uh you know make sure you really read the constraints and so forth right but yeah and we can hack this budget we noticed that every input is one character I think that's in constraints as well in either case I think yeah so we can't just make this like something like that and that should be okay I think because then that would never match anything maybe you just want an imp why you that never matches anything right oops that's a funny one and it happens at the very end so that was a very unlucky but still incorrect are you deserving the unlucky but like what are the odds stand the test case isn't literally because there's no only trigger if in the test case there's literally a case where the dollar sign is at the very end but uh which I don't know how what are the odds fit uh but apparently it is none soon okay so yeah so this is - that the - silliness seems so this is - that the - silliness seems so this is - that the - silliness seems relatively straightforward in the sense that wanting one code and one length encoding is pretty standard so the way that I did it is kind of a little bit static yeah let's figure out the complexity so for you to count do we only look at it once so it's gonna be off n it how much space are we using we only keep track of the last character and answer index and the current running count so this is all of one extra space there is stuff about in place and space complexity that is worth its own video so I don't want to get into that I am NOT a fan of this way of counting space because conceptually you will return a separate and so away or something like then that's obviously off event space because you can't do better than that whoa k space for some K which is output sensitive but yeah oh for what I was just saying about I mean on interview I could see maybe without the in place but one thing for encoding is something that comes up all the time so I would recommend just practicing a little bit on competitive programming I think to be honest this is one of those things that well one is you should practice it own because it's fun it is very foundational for this problem and just like keeping track and making sure the states are in a good place and maybe even coming up with sento values but imply doesn't come up that much in competitive programming because this is quite too much on an easy side oh yeah but this is how I do it I think one thing that I just want to go over a little bit more is how I did it was a little bit hand wavy how we converted it from in a way to do it in place there are a couple of places where it was hand wavy so the number one is I hope that the conversion is straight for it basically we just start from the beginning and we just literally put it in place in the choice away one count at a time so I think if you had to code that we had earlier then you should be able to see that this is way this should be obvious in the conversion because we just want one to one so the question that you might have is well what if you overwrite something that you had need to process later right I think that's the part that maybe it's a little bit tricky to prove and I think in my head I knew that to be right but I didn't showed that correct but you know I'm gonna do that now way like so let's say you have some input so there are only a couple of cases right what one is if you have to count it as only one of them like that's a dis then this a is five itself so in this case and this is why we test one of the example is that if there's only one character we don't have to write the number which is which makes sense depending on their type yeah oh that's just a constraint of the problem right so in that case well at most you will have you know this match it if you want to consider them two pointed one point of being the index here which is the index or a pointer that points to what you're processing and then another pointer which is the answer index which points here well in this case do part after you process this so then you move the point for it then you overwrite this here then you move the pointer for it so because so in the case where so in the case that all the numbers or all the inputs are unique and by itself you're gonna move them one at a time in a step lock kind of way so that so you will never so the second point we're never over overtake the first point right now in the second case well what are the possible cases where other than one well the answer for someone like this is to go to over - what does 3 look like so from this you can also like dot this a little bit but from this you can see that you know if they we have given two A's or two of the same letter or input this will also give it to size answer so it's the same logic as before of the ones you just move to and it's a little bit delayed due process the top one at a time and then after two characters you're like okay this is different orders enter the current one and then you push out the output of two characters or two output at the same time right so in that case the output will never pass the input and then now the other cases are more easier to see and that well you have three or more then the output is even slower than then their input right soon so then you can never overpass it and that's kind of a pseudo proof by exhaustion and the only other thing was that we talked about and I had a little bit of a bug waa about is that we were doing like if this is you go to 10 or more misspent white dot and this is to go to ten right well in this case by definition you have ten of these here and it converts no two spaces way so that's still slower than your input it will always be faster than your output so that's that allows me to be very confident so I was thinking about this during solving was that this gives me a lot of confidence to be able to do this without worrying about like additional checks and stuff like this yeah and one thing to kind of go over is so another question is why drive this and know in the beginning right and the reason why I've descent know in the beginning is okay let's say we don't have this what happens is that if the last character of their way let's say Baptist CCC right let's say we're here so they say index is pointing here so index minus one is pointing here at the one next to it and then it just only does this increment count is to go to puzzle my she goes to one right but it doesn't output it to their way so what normally I mean not normally but another way you can handle it is okay now at the very end we check to see if count is greater than zero that means if K is greater than 0 then that means we end it on a run and then we do some processing this way which is basically copy and paste of disk look so you can do someone like that right but if you look at the way that this code is that well there is copy and pasting right and copy and pasting is not great it's not dry it's not you know pretty and also you recall we did have a bug where we had to change this at the very end right so like if you look at the first version of it I would have to change this T's code to this and then I have to go down here to change this code to that as well to this as well like so it's bad way dry it's not very great it's kind of ugly right so what I did instead was create a value where when I append this end of string character this basically it's a case where one is and will always process this number at the very end or just input at the wei-yin and also that this input at the wei-yin and also that this input at the wei-yin and also that this would never be true so that by default is a sentinel value which is that this will always execute at the very end and that means that this code will get executed at the very end no matter what it is to append the answer to the empresa way and that's why I have this at the beginning so that we can process it later you can also do it a little bit differently but that's how I handle the standard values but yeah that's what I have for this problem let me know what your Frank hit the like phone hit the subscribe button and I will see you next time
String Compression
string-compression
Given an array of characters `chars`, compress it using the following algorithm: Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: * If the group's length is `1`, append the character to `s`. * Otherwise, append the character followed by the group's length. The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. After you are done **modifying the input array,** return _the new length of the array_. You must write an algorithm that uses only constant extra space. **Example 1:** **Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\] **Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\] **Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ". **Example 2:** **Input:** chars = \[ "a "\] **Output:** Return 1, and the first character of the input array should be: \[ "a "\] **Explanation:** The only group is "a ", which remains uncompressed since it's a single character. **Example 3:** **Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\] **Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\]. **Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ". **Constraints:** * `1 <= chars.length <= 2000` * `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
How do you know if you are at the end of a consecutive group of characters?
Two Pointers,String
Medium
38,271,604,1241
1,048
hi guys welcome to algorithms made easy my name is khushpu and in this video we'll see the question longest string chain given a list of words each word consists of english lowercase letter let's say word1 is a predecessor of word two if and only if we can add exactly one letter anywhere in word one to make it equal to word two for example abc can be said to be a predecessor of abac because after adding a in this abc we can get the word to now a word chain is a sequence of words word one to word k with k greater than equal to one where word one is a predecessor of word two is a predecessor of word three and so on we need to return the longest possible length of a word chain with words chosen from the given list of words so here we are given an example wherein we are given these words and we need to find the longest word chain so the word chain can be either a b c a and b d c a or you can say a b d a and b d c a or you can also say b a b c a and b d c a and b a b d a and bdca so you can get four combinations and the longest length of that is four so the output over here is four in the second example all of these combined can form the longest chain because if you add a letter c to xb you will get xbc if you add a letter c to this one you will get cxbc and then if you add p to it you will get this and when you add f to it you get the last word which is this one so the longest chain that could be formed is of length five constraints given over here are related to the length of words and the length of each string in this word array another thing that is given to us is that it will only contain english lowercase letters now let's see how we can solve this question what are the intuitions that we can get in order to proceed further taking the first example that was given to us in the question we can say that we have these two combinations that are present and in these two combinations also we have different paths that are possible in order to form the word chain so if you look at this one you'll get a you add a b in that you get a b a in this ba you either add a c or a d and you get these words and in these words you can add one more letter and you get this word and so the length that can be for this path is 4 similarly if you start with b you can get the word chain of length 4 and the maximum over here is 4 so the answer would be 4. now what do you understand from this one of the things that we can get to know about this is that we can say we can start from the lowest letter and from there the length of the string that is being formed goes on increasing so the length goes from low to high if we start from the lowest one and so to get this in order we can do a sort on our input on the basis of length that is first we take the smallest one and then we go to the larger one the second thing that we can see over here is the branches that we are getting so over here you can see that you have multiple branches that are coming out from ba and so we can say that the result that we'll get at this particular point can be reused in all the branches that are going out of this word string and so we can perform memoization to reduce the time that we would need to recalculate the answer for a particular word string that is given to us so now we know we can do two things one is sort and second is use memoization so let's start using this now i have taken this particular path for my example so i have removed the b that was given to us in the question and just we are taking this path and we will apply sort so sorting is done based on the length and so this would be the result for the sort now for memoization we are going to use a map the map would store the string and the result for that particular string that is what is the maximum chain length that we could have for this particular string starting with the first one we add this string with the chain length of one because this is going to be a default that one word can at least occur in the chain so one would be our default length of the chain and now we'll start deleting the characters from this particular string to see whether the smaller string exists in our map or not if that exists we can use the result for that particular string instead of recalculating it so let's see how we can reuse the result too over here we take a and we start deleting a character so this arrow denotes the character that we are deleting from the string if we delete a we get a blank string and this string is not present in my map so i do nothing but i need to look for the other word in the array so in the array i go to the next position which is ba and over here i'll add this in the map with the default value of 1 and now i'll start deleting the characters if i delete b from here the string that is left with me is a and i already have a calculated result for this a which was 1 and so i can use that result to find the one for the current string that is ba and the result would be either the result for ba that is there in the map or the result for the smaller string that is this a plus 1 for the string ba that is the current string so it gives me max of value for ba or value for a plus 1 and that would give me 2 as a result for ba now again we will move forward to bca so we move over here and we add it in the map with a default value now we start deleting characters what happens when you delete b you get ca which is not there in the map so you do nothing but you try to delete another character so here i have taken the example of deleting c from this string if we delete this we get b a and b ba has already been calculated and its result is 2 so we can reuse this result and the answer for bca would be max of bca that is 1 or ba plus 1 that is 2 plus 1 and that gives me maximum of 3 and i store that in my map as a new result for bca next we go to bda and perform the similar checks again i have the smaller string ba in it and i do not have any other combination that is i do not have ba or bd so i only have ba and i am showing it for ba but in reality you will have to iterate and try to delete each and every character from this string so for this one also my answer would get updated to 3 going forward i take bdca now by deleting d from here i can get the string bca or by deleting c i can get the string bda so let's try to delete d we get bca and my result would become either the result for bdca or bca plus 1 and that comes out to be 4 now let's try to delete c and we'll get bda and the result for that is also 3 so my maximum would not change in this particular scenario and would remain 4 itself now we have come to the end and we have all the result in this map and over here this result comes out to be 4. so how do you store this result you can have a variable and you can update this variable whenever you are trying to update the value in the map and so at the end when you are done with the iteration you will also have your answer in this result so that's it for the theory part now let's go ahead and code this particular approach out and then we will see the time and space complexity for this particular problem as seen in our theory part we are going to sort on the length and so i'll do arrays dot sort onwards and i'll take length as a parameter so over here let's write the comparator logic and that would take length so this would do a sort on words and arrange my words in increasing length now i'll take a result variable that will initially be 0 and i'll take a map and this map will contain string and integer i'm keeping its name as memoization memo because this is used for memoization now we'll start iterating on the words and these words are in the increasing order of the length so i'll take for each loop and in here the first thing that i do is put the current word in map so i'll do memoization dot put the word that i'm having with the default value of one once i have this i'll iterate for each and every character in the map and try to delete it so i'll take in i equal to 0 i less than word dot length and i plus over here i want to delete the character so i'll take this word in a string builder and then perform the delete operation so i'm taking the word as a current word and then i'll create the next word out of it so this becomes the word after deleting the character at ith position now i need to check whether i have the answer for this word in my memoization map so i'll do if my map contains the key next i need to update the value in map with the maximum possible value and thus i'll write once i am done with this particular loop i need to update my result variable also and that would become maximum of either result or the answer that we have got for the current word finally return the result so that's it let's try to run this code and we are getting a perfect result let's try to submit this and it got submitted now let's see how we can calculate the time and space complexity for this particular problem considering n as the length of this words and l as the length over here that is the word dot length so for this sort we are going to require a time of n log n and this is going to be iterating for a time of n that is for the length of array now in here we are going to iterate in this loop for the length of board and one more thing that we have is this delete caret function and that uses the time complexity of length now we know the time complexity for all the pieces that we have so for this whole loop the time complexity would become length into length that is length for this multiplied by length for this secondly when we go over here this becomes multiplied by this whole so we write this and the total time complexity becomes n log n plus the time complexity for the loop that is n into length the space complexity is there for this map and so we can say that the space complexity is o of n and if you are trying to take the length into consideration 2 then you can multiply this with length that is the length of the word or else you can simply write o n if you want so that's it about this question guys i hope you like the video and i'll see you in another one so till then keep learning keep coding
Longest String Chain
clumsy-factorial
You are given an array of `words` where each word consists of lowercase English letters. `wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`. * For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`. A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`. Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`. **Example 1:** **Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\] **Output:** 4 **Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\]. **Example 2:** **Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\] **Output:** 5 **Explanation:** All the words can be put in a word chain \[ "xb ", "xbc ", "cxbc ", "pcxbc ", "pcxbcf "\]. **Example 3:** **Input:** words = \[ "abcd ", "dbqca "\] **Output:** 1 **Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains. \[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed. **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 16` * `words[i]` only consists of lowercase English letters.
null
Math,Stack,Simulation
Medium
null
480
in this video we're going to take a look at a legal problem called sliding window median so median is basically the middle value in an order integer list so the size of the list is even then there's no uh middle value so we gotta have to find the average of the two middle value so here you can see we have an example of two three four right so if we have two three four the medium is going to be three because the middle value is three because the list is all right so the size of the list is odd it's an odd number and if we have a size of this is even number like this 2 3 then the median is going to be 2 plus 3 divided by 2. okay so in this case we have 2.5 have 2.5 have 2.5 so given array of nums there is a sliding window of size k which is moving from left to right to left of the array to the right so uh you can only see the k numbers in the window so each time the slide in window moves right by one position your job is to output the medium of the window current the current window right where i say each window in the original array so for example if we have an array like this and k is three so in this case you can see the window are sliding now the median is one right because the middle value is one and in this case there could also be a situation where the median is negative one right in this case the median is negative one and the median here is going to or i just say the middle value is going to be three right and so we basically just store those median values into an array and then we are we're returning this array at the end so something that we have to watch out for is that we want to make sure k is always valid so k is always smaller than the input array size and the answer is within this number so of the actual value will be accepted as correct so let's say we have an example of 1 3 negative 1 and negative 3 5 3 6 7. so negative 3 5 3 and six seven right so in this case let's say k is equal to four then the median in this case is going to be uh the average of the two middle values so the two middle values gonna be negative one and one so the average between those two is gonna be zero right and uh if we were to slide our window from here right so one to the right then we have a middle value so two middle values are negative one and three right uh in this case the average between them uh in this case is gonna be two divided by two is one then we slide our window again right so then we slide our window and now it's here right including is three so the median is gonna be negative one plus three which is in this case it's going to be uh two and two divided by two is zero right so our medium or our uh median value is gonna be zero uh if we slide our window again negative three plus five plus three plus six so this one right here this window then we're going to have a medium which is gonna be negative uh hold on yeah it's gonna be three plus five right because those are two middle values so in this case we're getting eight divided by two is which is four so you get an idea right so if it's even if our window has the size of even number then we're just going to take the two middle value and then take the average of those two so in this case what we can do is we can use the two heap technique right that we just talked about on how we solve the find the median of the data stream problem which is very similar basically the idea is this we're going to have a heap right we're going to have our max keep and we're also going to have our mint heat the idea is that we're going to use our min heap and the max heap to keep track of the middle the two middle values or the middle value of our current window so usually what we're gonna do is we're gonna have our input data right so we're gonna have a max heat basically to keep track of the first half of our data and the maximum value be at the top right and uh we're also going to have min heap basically keep track of the second half of our data uh or our window and the middle value at the middle right where i just say the smallest element will be at the top of our min heap so the middle value is going to be those two the top element for our min and max heap so we can use those two elements to get our average value and uh or if we have a situation where one heap has a size that's bigger than the other one then we're just gonna return the top uh element of a heap and then that will be our median for our window right uh if our current size of our window is odd number so basically the idea is this we're gonna add those elements that we have within our window onto our heaps right so we have a min and max heap so in this case initially we have one so in this case the rule for min and max heap is that we want to make sure that every time when we're adding an element we want to make sure we balance the heaps so the rule is this we want to make sure the max heap the size is if it uh is actually equal to and keep so men keep that size or if we have situation where the min keep that size or sorry the max keep the size is actually equal to min heap the size plus once so we're allowed to have the max heap dot size to be bigger than men keep that size by one so in this case what we're going to do is we're going to first adding the first element onto our max heap so in this case because our max leave is empty so we have one here and then in this case we have a window size which is equal to k is equal to four so in this case we're just going to keep adding those elements up to k when the size of our window is equal to reach to k right so in this case our max is one and our currently our heaps are balanced so we're just gonna continue to add those elements so in this case one three is bigger than one so we're gonna add it on to our min heap so we have three here and negative one in this case is less than one so we're just gonna add it on to our min uh max heap so far we have our heaps are balanced so now we have negative three in this case is going to be less than one so we add it on to our max heap and in this case we have our heaps are unbalanced so in this case what we're going to do is we're going to remove the top element from our max heap and add it on to our min heap so in this case we're going to have negative one added on to our bin heap max heap and basically what we're gonna do is we're gonna have one here and three at the bottom right because we have a min heap so in this case three at the bottom and large element at the top so then we once we reach the window size which is equal to k then we're going to get the median so the median is basically a top elements average so negative one plus one in this case is zero divided by two is zero so once we um done getting the median we're gonna get our left pointer points one to the right so now we have three right so in this case to shift our left pointer or the or shrink our window in this case what we need to do is we need to take the top element in this case is negative one we see if the element that we want to remove which is in this case is one is actually inside this heap and to do that we check to see if one uh negative one is actually bigger than or equal to one in this case negative one is not bigger than or equal to one so therefore the element that we want to remove which is one in this case is not inside the max heap so we're just going to remove it from the min heap so we know that min heap we have one here so we're just going to remove that right so now we have three at the top here okay so then what we're going to do is we're going to basically shift our window one to the right and uh now we're going to expand our window now we add five so five in this case is actually bigger than negative one so in this case we're just going to add it on to our min key so in this case we have three at the bottom and five at the top or i should say sorry three at the top and five at the bottom because we have a min heap so the median is going to be negative one plus three uh which is gonna be two and two divided by two in this case it's gonna be zero uh one sorry so the medium is going to be one and then we're gonna slide our window again so we remove the top uh the left element in this case the left element is three so we know that three is actually bigger than the top element for our max heap so we're gonna delete it from our min heap so our min heap has a three so we're going to delete it here so you can see we have our five right so five at the top and once we delete it we still know that this current heaps are balanced so we're gonna expand our window again now we have um add three right this three right here onto our heaps because this three right here is actually bigger than uh negative one so we're going to add it on to our min heap so we're gonna have five at the bottom and three at the top and we know the medium in this case the median is going to be um yeah is basically going to be the top element from both heap um the average of those two elements right so in this case we have two divided by two which is one so you get an idea basically we're just going to slide our windows get our inserting elements get our median deleting the element the left element and then shifting the window one to the right so to do this in code basically what we're going to do is we're going to have our constructor that defines our min and max heap and the reason why we use a collection.reverse order here is because collection.reverse order here is because collection.reverse order here is because there could be a situation where we're adding a element that is equal to integer.max equal to integer.max equal to integer.max so if that's the case then we want to make sure we can just use collection.reverse order so we can't collection.reverse order so we can't collection.reverse order so we can't really use uh a b right so b minus a to get a descending order like that because we have can have a situation where integer is equal the element that we're adding is integer.max so that won't work integer.max so that won't work integer.max so that won't work so we need to use collection.reverse so we need to use collection.reverse so we need to use collection.reverse order and then we're going to have a method called add which this basically adds the element right it takes the element we check to see if the max heap is not empty sorry if the max heap is empty we're just gonna add it onto our max heap or if the max heap top element for our max ep is actually bigger than none then we also can be able to add it on to our max heap otherwise if we have a situation where the maxi does uh the top element for our max heap is actually less than or equal to or sorry yeah less than or equal to the number that we're adding then we're just going to add it on to our min heat and at the end we're going to balance our heat and then here you can see we have the removal method right basically we take the element and check to see if it's actually within our max heap if it is then we're just going to delete it in our max heap otherwise we're gonna you know delete it in our min heap and then we're going to balance it and inside this balance method you can see we first check to see if the maxi dot size is actually bigger than keep that size plus one if it is then we're just going to we know that we're going to take the top element from our backseat and add it on to our min heap and if we have a situation where the mini heap does size is actually bigger than the max heap of the size then we're going to take the element from the min heap and add it on to our max heap in this case that's how we balance our heaps so to find median in this case is the same thing we're just going to see if we have uh whoever has a heap that is larger in size we're just going to return that top element and you notice that here we are basically dividing the top element for each heaps top element by 2.0 the reason why is because there by 2.0 the reason why is because there by 2.0 the reason why is because there could be a situation where the element that we're adding is actually equal to integer.max equal to integer.max equal to integer.max so in this case we're dividing that by itself and adding them uh once we get the element right in this case we want to make sure we're returning a double and that's why we have 2.0 and that's why we have 2.0 and that's why we have 2.0 and then in this case we have a function called meetings median sliding window which takes the array and k and basically we're going to have a double array which called result basically this is going to be the size or number of times that we're going to slide our window it's going to be n minus k plus 1 right or number of elements that we have minus k plus 1 which is basically how many times we had to slide our window each time we slide our window we expend uh we basically record or add the median number onto the array and then we're just going to um continue to do that right so in this case what we're going to do is we're just going to start from zero right we have our start which is kind of like our left corner and our n is going to be our right pointer we're going to slide our window until we get to a point where the size current size of our window is actually equal k then we're going to record our median add it onto our result ray and then remove the left element and then we move the left pointer one to the right so then we're just going to continue to repeat the process until we get the end is actually uh bigger than or equal to num delay so in this case at the end we're just returning the result array so in this case let's try to run our code and let's try to submit and here you see we have our success so the time complexity in this case for this algorithm right is going to be big o of n log k and the reason why we have a log k here is because log k for removing and deleting uh removing or adding element right removing and adding elements will be log k for time complexity and uh for each iteration in or for each element in the array we have to make sure we do the same process so in this case we have a log k for time complexity and the space complexity in this case is going to be uh big o of n and the reason why is big o of n not big o of k is because we have um this right here right we're basically adding pretty much the elements that we have in all the elements that we have in our window right or each time we slide our window we're basically adding the median number onto the result and if we have situation where k is equal to one right then we want to make sure we're basically adding let's say n minus k plus 1 which is basically n elements onto the result so in this case we're getting um we're getting it right so the space complexity is going to be big of it
Sliding Window Median
sliding-window-median
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are given an integer array `nums` and an integer `k`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. Return _the median array for each window in the original array_. Answers within `10-5` of the actual value will be accepted. **Example 1:** **Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3 **Output:** \[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000\] **Explanation:** Window position Median --------------- ----- \[**1 3 -1**\] -3 5 3 6 7 1 1 \[**3 -1 -3**\] 5 3 6 7 -1 1 3 \[**\-1 -3 5**\] 3 6 7 -1 1 3 -1 \[**\-3 5 3**\] 6 7 3 1 3 -1 -3 \[**5 3 6**\] 7 5 1 3 -1 -3 5 \[**3 6 7**\] 6 **Example 2:** **Input:** nums = \[1,2,3,4,2,3,1,4,2\], k = 3 **Output:** \[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000\] **Constraints:** * `1 <= k <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array? Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done. The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?
Array,Hash Table,Sliding Window,Heap (Priority Queue)
Hard
295
520
hey guys welcome back to another video and today we're going to be solving the lead code question detect capital uh so i just want to mention two things before i get started so first i don't have a premium membership so i won't be able to solve these questions and second uh if there are any specific lead code questions that you want me to answer just let me know down in the comments and i'll try to get them answered for you okay so now let's just get started with the question so we're given a word and we need to judge whether the usage of capitals is right or not and it is correct or not based upon these three conditions so the first one is if we have all capital letters then in that case we're going to return true if we have all lowercase letters that is also going to be true and if we have only the first letter being uh upper case and everything else being a lower case then that's also going to be true so these three conditions are going to be true and so i'm going to give you two solutions to solve this one's going to be a more intuitive approach and one's gonna be a very pythonic way to solve this question okay so let's just get started with the first one so i'm just gonna write the three cases that we have okay so these are kind of the three uh different conditions that we have and let's just make these into three different if statements and return true if any of these three are true so if all caps so what we're gonna do is we're gonna take our word and we're gonna uppercase everything so if word dot upper so what this does is it's going to make everything into uppercase and if that is equal to our original word then in that case we're going to return true okay so that's one of our conditions and now we have this if all our if all are lowercase so else if so we're so say similar to word.upper we have word.lower word.upper we have word.lower word.upper we have word.lower so if we lowercase everything and that's equal to our word and in that case we also return true all right so we took care of three of the conditions and now we have the third one so if first letter is a capital and everything else is lowercase okay so what we're going to do is we're going to take the first letter so where it is at the zeroth index and we're going to use the dot upper function on that and if that is equal to word at the zeroth index and if everything after the zeroth index so word from the first index to the ending uh dot lower because uh only the first letter is uppercase and everything else is lowercase so if every so the first letter over here is uppercase and now we're checking if everything else is lowercase and if that is equal to word starting from one all the way to zero then in that case we also return true so these are all the three conditions that we need to account for and else if none of these are true then we're just going to return false so let's accept i mean sorry let's submit our solution and okay as you can see our solution did get accepted so now we're going to look at the more pythonic solution to this uh do not use this in an interview by any means i'm just showing it to you because i think it's pretty cool um and python has a lot of inbuilt functions like this so it's just gonna be a one-liner so it's just gonna be a one-liner so it's just gonna be a one-liner so return so word dot is upper so if everything is uppercase it's going to return true or word dot is lower so if everything is lowercase it's going to return true so we got take so we took care of two of our conditions already and there's also one more which is called word dot is title um yeah is a word dot is title and a title is basically the first letter is capitalized and everything else is lowercase so it's just going to return that and let's submit this and see what happens and this solution was also accepted and finally do let me know if you have a better solution to this or if you have any questions regarding this i'd love to help you and finally if there are any leak code questions that you want me to solve specifically just let me know down in the comments i'll get them solved for you alright thanks a lot for watching and do let me know what you thought about this video and don't forget to like and subscribe thank you
Detect Capital
detect-capital
We define the usage of capitals in a word to be right when one of the following cases holds: * All letters in this word are capitals, like `"USA "`. * All letters in this word are not capitals, like `"leetcode "`. * Only the first letter in this word is capital, like `"Google "`. Given a string `word`, return `true` if the usage of capitals in it is right. **Example 1:** **Input:** word = "USA" **Output:** true **Example 2:** **Input:** word = "FlaG" **Output:** false **Constraints:** * `1 <= word.length <= 100` * `word` consists of lowercase and uppercase English letters.
null
String
Easy
2235
1,304
hello so today we are doing problems for this contest weekly contest 169 the first problem is find and unique integers that sum up to 0 and so the problem says if we have an integer N and we want to return any array containing and unique integers such that they are such that these integers add up to 0 and so for example for n equal to 5 we can return these 5 numbers so it means it a number of number the number of integers that needs to be in the array but the additional constraint is that the sum of the array has to be equal to 0 for n equal to 3 you can just take - take equal to 3 you can just take - take equal to 3 you can just take - take minus 1 0 and + 1 right and so how can minus 1 0 and + 1 right and so how can minus 1 0 and + 1 right and so how can we approach this so the first we how can we approach this so the first there are actually three ways 3 different ways to look at this problem so the first thing that I can start with as well what we can do is a simple thing which is just you notice that for even numbers if n is even what we can just do something very simple just take the negative numbers take half of the N divided by 2 from 1 to n divided by 2 as positive number and the same numbers as negative and there some thicker will cancel each other out and so for example if I have let's say and equal to 2 what I can do is just sort from 1 to N divided by 2 which is 1 so just take minus 1 and take the same number but positive 2 cancel it out for n equal to 4 and divided by 2 is 2 so go from 1 to 2 which means 1 to 2 positive and do the same numbers negative now the only now when it's even then when it's odd then we can do I do something slightly different to just take the same number n minus 1 and then just add 0 so that because 0 wouldn't anything so the Sun would still be zero in the number of integers will be five right so the way to think about this basically as we just need to generate the numbers from 1 to n divided by 2 positive and append them to the negative values of the same range and just as 0 if n is odd and so pretty much what you can do here is just okay the clouds the final result here that we will return and then go for the range from basically 1 to n divided by 2 which is what we did here in the example so from 1 to N divided by 2 and so in Python that I need to be and divided by 2 plus 1 and then we need to append both minus I and the ice without it cancel each other out and if n is odd and so that would mean this is different than 0 we can just add 0 like this and that's pretty much it service on this okay goodbye segment okay so that works another way to check out using just binary operations is just doing which is a little bit faster but not that much so we can do it that way and this should pass okay so uh submit okay so that passes and another different method of so this is the first method another way we can do this is we can just generate the numbers from 1 to N minus 1 so basically all the numbers 1 2 &amp; top n minus 1 and now we have n 2 &amp; top n minus 1 and now we have n 2 &amp; top n minus 1 and now we have n minus 1 numbers right and then we could just to cancel all these out can just take the Sun so call this a the array a and just take the sum of a and put minus 1 so that it can cancel all of them out and so it would be just pretty much just a plus an array containing this and that way this would cancel out a so that the sum of the entire array is 0 and we'd have n elements because a is n minus 1 element and then we are adding one element so we'd have n elements and so that's pretty much would be taking a to be the range from 1 to n minus 1 and to reach n minus 1 we need to put M as the end and to get a list we need to do it like this and then we can just return that plus minus sum of a so that can cancel out and become 0 and the length can become n now we don't need to distinguish odd or even here because this number would be from 1 to n it would be an even number of elements if n was odd and then we'll add 1 and it will be odd and the similar thing 1 n is even right so that's pretty much it's all a fondest and submit it okay so that passes so another way to solve this problem is to think about AB just to generate all the different cases and see if we can find a pattern so for n equal to one we can just give 0 right the sum is 0 and the number of element is just 1 right for n equal to 0 we can just give the mpls right the length is 0 for n equal to 2 we can just have minus 1 and 1 right they cancel out to 0 and that length is 2 for n equal to 3 we can have minus 2 and we can have 0 and so the length is 0 or the length is 3 and the sum is 0 for n equal to 4 what we can do is take basically minus 3 take minus 1 0 1 &amp; 3 and that's sorry without 0 so 1 &amp; 3 and that's sorry without 0 so 1 &amp; 3 and that's sorry without 0 so that's four elements and the sum is 0 right for n equal to 5 we can do - 4 - 2 right for n equal to 5 we can do - 4 - 2 right for n equal to 5 we can do - 4 - 2 0 2 &amp; 4 and you can see this is 5 0 2 &amp; 4 and you can see this is 5 0 2 &amp; 4 and you can see this is 5 elements and can they cancel out to be some 0 so you can notice the pattern here is basically doing the range from minus n minus 1 right that's what we did for 5 we take which we took n minus 1 which is 4 and we did minus 4 same thing for 3 minus 3 here we did n minus 1 which is 3 and we did minus 3 and then we go all the way to n minus 1 but every time we increase by 2 because here if you look - - we start because here if you look - - we start because here if you look - - we start from n minus 1 minus n minus 1 which is minus 2 and to increase by 2 to get 0 then we increase by 2 to guess - he o then we increase by 2 to guess - he o then we increase by 2 to guess - he o start from n minus 1 which is 3 so minus 3 we are - who give we get minus 1 we 3 we are - who give we get minus 1 we 3 we are - who give we get minus 1 we had 2 we get one where 2 we get 3 here we start from n minus 1 which is 4 so minus 4 we add 2 we get minus 2 we had to get 0 we had another to get to add another - Lea 4 so you could see this is another - Lea 4 so you could see this is another - Lea 4 so you could see this is the idea of the solution right and so let's just implement that so in Python we have a function fringe that does exactly this for us so range we give it the start right and then we give it the end and we'll give it this step right and so the start here for us is just minus n minus 1 right and the end is well we want to stop at n minus 1 but we're gonna include it n minus 1 and so to include n minus 1 we need to stop at and here because it will start at just the previous value which is n minus 1 and then the step is - and that's pretty and then the step is - and that's pretty and then the step is - and that's pretty much it now just to make this a little bit easier to read we can enter the - bit easier to read we can enter the - bit easier to read we can enter the - and so we have plus 1 here and we can just put 1 here instead and we have from 1 minus n 2 N and increase every time by 2 and that's pretty much it I guess I'll submit okay so that's it pretty much so we saw there are three ways to solve this problem and all of them are over an essentially and yeah that's pretty much it so thanks
Find N Unique Integers Sum up to Zero
longest-happy-string
Given an integer `n`, return **any** array containing `n` **unique** integers such that they add up to `0`. **Example 1:** **Input:** n = 5 **Output:** \[-7,-1,1,3,4\] **Explanation:** These arrays also are accepted \[-5,-1,1,2,3\] , \[-3,-1,2,-2,4\]. **Example 2:** **Input:** n = 3 **Output:** \[-1,0,1\] **Example 3:** **Input:** n = 1 **Output:** \[0\] **Constraints:** * `1 <= n <= 1000`
Use a greedy approach. Use the letter with the maximum current limit that can be added without breaking the condition.
String,Greedy,Heap (Priority Queue)
Medium
778
674
yes it is or how to be going this video I'm going to take a look at six seven for an easy one longest continuous increasing subsequent given an unsorted array I also did array of integers find the length of longest continuous increasing subsequence sub array so 1 3 5 4 7 the longest would be 1 3 4 or 1 3 5 so get 3 well yeah I think this could be done just to just loop through the array and the fine if the number is bigger than the previous one if it is we passed one if not we reset it right yeah so that's the maximum would be 0 long case Oh maximum the minimum should be 1 right okay so we look through all the numbers the previous week we need to get the previous one so we use index okay we should start with the 1 actually if it is bigger than it then we plus 1 so let's current max equals parent in N equals 1 if it's bigger than it then we plus 1 if numbs eye is bigger than arms I'm a swan we current named aslan and max it was math max okay we don't need to hear actually we could just own it a point to meet some descending once right oh no I just do it here that's cool and then if you make something equal or smaller than it then this should be the map the Karina's should be set to 1 right it means like the fact we met we need 4 then 4 is the law and the current continuous increasing supply finally coming back sure we're right almost empty phenom cement equals zero we return for sure yeah cool so this set isn't it easy one I hope it helps see you next time
Longest Continuous Increasing Subsequence
longest-continuous-increasing-subsequence
Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing. A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]` and for each `l <= i < r`, `nums[i] < nums[i + 1]`. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 3 **Explanation:** The longest continuous increasing subsequence is \[1,3,5\] with length 3. Even though \[1,3,5,7\] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 4. **Example 2:** **Input:** nums = \[2,2,2,2,2\] **Output:** 1 **Explanation:** The longest continuous increasing subsequence is \[2\] with length 1. Note that it must be strictly increasing. **Constraints:** * `1 <= nums.length <= 104` * `-109 <= nums[i] <= 109`
null
Array
Easy
673,727
935
hello hi guys welcome back I hope that you guys are doing good and problem night dialers and again in this video we're going to see all three approaches to solve this problem and we'll code also simultaneously we'll modify the existing codes itself please make sure that you look onto all the approaches and how we progressively go on it and also for the folks who are very confused in recursion please make sure in the beginning you just follow me on how actually I get the hint of what and how the recursion can be built so I have seen many of our followers and folks and many students are actually confused on how to actually build the recursion the question itself tells you that so let's see that how we can actually build the recursion itself we will not we'll do nothing it's just that we will read the problem and we'll follow what he is saying which the problem is saying firstly let's have a quick look that it has been asked by Amazon in the last 6 months last 6 to one year and a lot of times asked by Bloomberg Facebook Google and tweo TW okay cool let's see uh the problem says that there's a chess Knight has a unique movement as you know uh in a chest a knight has a unique movement it may move two squares vertically and one square horizontally and two squares horizontally or one square vertically if you don't know a knight moves like this two and then one this is how a KN moves and this is how our movement needs to be there cool uh just it says the possible movement of the of a knight are shown in the diagram below so it is a POS movement so for you to just verify that how the Knight will actually move if you don't know that we have already seen some Knight problems where we know that if it is a IJ then what all coordinates needs to be these cool a chest Knight can move as indicated in the chess diagram below that is great now we have a knight okay that's just saying that we have a chess Knight and a phone PAD as shown below the Knight can only stand on the numeric cell that is a blue cell a knight will not stand here this is no more a place for the Knight can only stand on these cells now when I say a knight stand on these cells if let's say a knight is standing on this cell then he can move to and then this location so from a Knight can move to three which means if I say that I have my knight on a pad eight or a digit 8 it can move to a next digit as three that is very obvious that it he's saying that basically we are replicating that chest scenario on a phone pad on our simple Nokia phone pad and the same way it can go to this location from eight if I just move via the night ways it can go to a location of one that's great and there's no more location it can go because it has no more places to go to so what we actually can do is we can just make a map kind of stuff or vctor kind of stuff no worries that if it is actually required or not still I'm just showing you that we just want to replicate the movements so you can say okay from zero it can move 2 4 6 from 1 can move to 68 2 to 79 3 to 4 6 4 to 3 9 0 uh 5 to nothing uh 6 2 170 7 to 28 8 to 13 as we saw on above and 9 to 24 this is we can just manually write it down because it's very hectic to actually go and find I plus a so like we can just hardcode this stuff and no like not sure if it is used or not but yeah still we have just write it down because we know that we have to replicate this whole scenario on a phone part now comes the interesting part we have a chess Knight and a phone pad okay that is done and we have to just move on the cells now given an integer n return how many distinct phone numbers of length n can be dial again we are given an integer n so it is for sure for us that if I given integer N I have to find let's say the N is of four digits so I have to find how many such four n digits phone numbers I can dial again I have not done anything extra I'm just writing what the question is saying please make sure that you follow up and that will be the part how you get to know that what and how the recursions are done or how the states are being applied and all that stuff now you are allowed to place the Knight on any numeric cell initially okay so he was saying that I have to build a digit of n digits and initially I can place my night on any of the digits what digits I have 0 1 2 3 4 5 6 7 8 9 10 like nine only so I on the first place I can place 0 1 2 3 4 5 6 7 8 and 9 so on the first place I can place these digits oh that's great I can place these digits and I did nothing again uh and then you should perform n minus one jumps to the dial a number of length n okay because as you know that the length was n so I know that I have placed one digit any of these digits from 0 to 9 I have placed so now I will have to perform n-1 n-1 n-1 jumps because for sure I want the remaining n minus one digits and this is what the question was saying all jumps should be have valid night jumps okay which means all jumps should be a valid night jumps which means let's say if in the beginning because you know that okay we had four digits because my n was four in this example like I was taking okay n digits and let's say we have placed a small number ns4 now if I have placed a digit zero here and he's saying that all the jump should be a valid night jumps so I know that I will ultimately have to make n minus one jumps as the question was saying but the next jump should be a valid night jump so from zero I can only jump to four and six so I will use this jumps array to help me if existing I have a digit as zero so next jump can only be a four or a six and I should do a next jump of a four or a six and that is how greatly I can just figure out bro I know that myit is this my remaining I have to fill as n minus one digits and I know for sure the next digit I can place at a four or six and then I can simply going keep on going forward until so far I have did I have done nothing now as the answer can be pretty large return the answer with the module 9+ 7 because we answer with the module 9+ 7 because we answer with the module 9+ 7 because we have to find the number of ways so the answer he's saying can be prettyy large so just return it 9+ 7 that we make sure so just return it 9+ 7 that we make sure so just return it 9+ 7 that we make sure that we will do in the for sure like in the while solving the problem itself now coming on back we have solved majorly the part of the intuition itself that it is for sure in the beginning I will place I will have nine options to place and I will and I cannot say that I will blindly place these nine I one way of doing these problems is you like you just say that to place on the first location you have nine options and you just place that nine number here that okay for the first location I have nine options then what's the options for next location but here I cannot do that I have to actually Place one digit I have to place a zero because that zero will make sure that what should be my next jump so every digit will matter here so I will do one thing okay I know that my current digit is this and I also know that I have to figure out if I have placed I have to figure out for the next n minus one places Ms have to figure out and that's what the question and that's the question was saying so again I can just place a one as the first digit and I can again go and ask for the N minus one digit again I can place a two here as a first digit and I can again go and ask for the next n minus one digit now when you place a zero let's imagine you place a zero right so the next digit it can be a four or a six as we plotted as we saw right it should be valid night jump it can be a four or six so I can place a four or a six let's imagine we place a four or let's imagine we place a six so we can place both of them so for sure we will have two options again if we just copy this up so that with this we will see that we will have these two options and with these two options I can easily say that okay I can place either a four here or a six here oh if I place a four or a six okay then I have to go and find for next nus 2 locations again next nus 2 locations right again if for one again we'll go and check okay I can place a six or eight let's right now only place one thing six although we will place both of them but for Simplicity I'm just for explanation so showing if I place a six then again I'll go and find for n minus 2 locations oh bro that is same that you placed a digit now bro how is this same one was no bro I just want to do previous digit because this six will make sure what should be the next location this six will make sure what should the next location because I want the valid night jump from six so it is a same configuration saying from six I want a length of nus 2 What is the number what is the number of possible phone pad combinations from six if I do off length n minus 2 what is the number of valid phone pad combinations so ultim you figure out this needs to be your DP state that you like you can just write any which ways down that this is the remaining number of location and this is the current digit this current digit will help me make sure I need to find my next digit I can find my next digit by just iterating on this jumps array of the current digit that I can know what is the possible next digit location and that's how you got to know that it is a question of recursion because you know that for sure just will simply keep on replicating you know that it is having a repeating sub problem so for sure we will apply a memor or a DP so that is a second point you got to know what needs to be the state of your recursion or the DP so as to solve this question so ultimately we have reached to a conclusion that uh we just need one thing we need remaining and we need current digit so in the beginning I have the options to place all the nine digits so in the beginning I will place I'll just say in the beginning I'll place all the nine digits 0 1 2 3 4 5 6 7 8 and 9 and as I place on all the nine digits I know the remaining for all of them is nus one why nus one because the pro saying now nus one jumps for the remaining one so I know I have placed one I have to place in total n so the remaining is nus one for sure n minus1 nus1 n -1 nus1 and one for sure n minus1 nus1 n -1 nus1 and one for sure n minus1 nus1 n -1 nus1 and so on so forth and with this you will just pass this in your recursion you will know okay this is the remaining this is the digit you know for sure that from this digit you need to do some number of jumps so you will know that if I want to go to my next location I will just say bro jumps of this digit will give me the next digits that will be a simple these all next digits for me to jump to so that I will know that from this location I can jump to nus 2 because now the remaining digits will be nus 2 and now the current digit will be a zero for Zer it is a four or six so it will be a I will just call recursion for four and for the same thing I call recursion for six this will be our next recursive State and for sure I want the number of ways ultimately if it means okay from this you will see that if I place if let's say I had just two numbers so I place a zero here next I can place a four right next it will just say bro remaining now remaining let's say my total n was to itself so now the remaining is zero which means I have formed one valid combination when the remaining goes zero which means I don't need to place any digit now so my I have found a Val combination of Digit so just says that when you're remaining is just this number right remaining number of places to have to place the digit if the remaining is zero bro you have all you have formed the valid combination please return a one so this will return me a one because I have formed a valid combination ultimately and for sure you are having multiple options so please either because from zero you can either go on four or you can go on six so keep on adding the possible ways for every of those Childs which means four or six and that's how you can simply get this solved in the cursion and again the time complexity will actually be you will see that you are actually going on to just n and these digits n is nothing but the question itself which is given n and the digits can be zero to 9 which is 10 itself so the time will actually be o of n into 10 or you can also say that o of n itself and the space also you will keep track and do a memorization for that you will again need a space of O of n into 10 or you again say that o of n itself let's quickly see that how we can pute this up again I hope that you guys have got it uh for Simplicity I have just pasted the jumps array because we have to manually make it up uh now we know that we need to have a 2d Vector uh for this now I will as you know that we are doing modulo so uh let's take everything in long because it is much more easier for us to do a modulo and for sure uh we have to take a mod 1 2 3 4 5 6 7 8 9 + 7 now uh I'll just do 2 3 4 5 6 7 8 9 + 7 now uh I'll just do 2 3 4 5 6 7 8 9 + 7 now uh I'll just do uh my DP now I'll just resize my DP uh because it just feels like now we need the first is the remaining can be from 0 to n so I just take a size of n+ one now and the next part was a digit n+ one now and the next part was a digit n+ one now and the next part was a digit for us again um you can just swap both of them which means you can have the digit and your remaining or any which way you can have the remaining and the digits so here the digits will only be 10 from 0 to 9 so that's the reason we have just only done this now our main part comes when we actually have to call a solve function now the solve function if you had known that is just uh a simple function saying that just solve it's a DB function now I have the remaining I have the digit current digit which I am on why current digit I on because you know that for my final answer I have to initially start on and place every digit so I'll just try and place I'll I try and place every digit from 0 to 9 and then because you saw now in the first location I can place any digits so I'll just say I'll place every digits which means I'll place every digit so the remaining number will be n minus one and I have placed this digit as a first digit for me and ultimately I can just say return the um answer mod with this value so yeah also do a mod at every step because mod can be pretty dangerous now I can just simply go and have a solve function uh in the beginning I just showed you that if your remaining reaches zero uh which means bro you have found a valid combination so simply return a minus one now here I'll just ask him bro um for that if you have already found the value simple memor check then simply return DP of remaining and that digit it's a simple memor check which you already always do now as you saw that for the current digit I can go on next digits so I will have my answer now I for this current digit I'll go on to next digits so I'll go on to next digit for this current digit and what how I can go by the jumps array which I have made earlier so I'll go on to for this digit and I will just ask him bro um just add the answer whatsoever you have uh just go and solve it I know the remaining will actually decrease and become a remaining minus one because one digit I'm taking right now which is a digit and I'll go on to this next digit is my digit next digit is my next digit and for sure please keep on doing the modulo and ultimately return the answer but before returning please make sure that you memoize it and place that in your digit so that you can just use it later on also and simply answer and with this mod value now let's quick check it up if we have not done any errors uh Vector okay let's correct this and yeah uh if yeah and with this the time will actually be o of n into o of like space and time both are actually o of N and that's the code which you also saw now uh now comes that shall we optimize it but in memor you cannot think of any optimizations so for sure you have to convert the same thing into a bottom up so what I will do is the same code which we have written previously I'll just do one thing and try to see that how I can convert this code to a bottom of code same stuff uh we will use the same remaining end digits we will just do one thing okay uh you know that what was the base case was when the remaining is zero now our DP looks like remaining and then digit now my base case was that my remaining is zero so what I will do is I simply have a base case that okay my uh DP of DP of0 and for all the digits which is your 0 to 9 all the digits the value you should place as one itself for the base case because I trying to replicate the top down to a bottom up so I'm just manually seeing okay what how my bottom of code looks how my top down code looks like and with that I'm converting my code to a bottom up code I saw my base case remaining was Zero for every digit I'm returning a one so that is my base case for my bottom of DP then I will just start off with my actual DP itself and we go on to all the remaining from one up till the remaining is less than equal to n minus one because you saw now remaining will go to n minus one itself and then remaining Plus+ for that itself and then remaining Plus+ for that itself and then remaining Plus+ for that remaining I'll go on to all the digits of that remaining that is what you usually do you go on to all the digits from zero to actually less than 10 which means less than equal to 9 digit plus now again for every digit you will actually say now that okay uh for this current digit okay the remaining is one the I have the current digit what could be the my last jump or like what should be my next jump to be so I'll just say okay uh what is the next jump which I need to have and I'll just iterate on the jumps of this particular digit array and with this I can just say that I'm iterating on my remaining digits and the next jump and I'll just say that my DP or I can just say my DP of remaining and digit will be a summation of my DP of remaining minus one and next jumps and that's what we had been doing remaining minus one we would have already calculated because we are going in the disorder and remaining minus one will actually be a zero in the beginning so we are going in the order so for sure we would have already calculated the previous state which is remaining minus one and for sure the next jum will be the digits itself from 0 to 9 so we can we would have already computed that also so ultimately we will just do a summation and while doing summation please remember of the mod and stuff and that will be a simple bottom up DP how this bottom of DP will look like so we have to just simply modify this particular code and remove the above code let's quickly do the same thing again the time again if we just go back the time and the space are again same time is again o of N and space is again o of n then Arian why did you do that by why did you do that we will see because if you want to think of if let's say the interview ask you can you optimize this so firstly you will have to convert that code to a bottomup code again there are chances that there might not be any optimizations at all but still if there are then you will have to convert your code to a bottom up code you cannot optimize the code using a top down approach now uh we are back and we just don't need to solve function because we will act do a bottom up approach for us now uh for the bottom up we just initialize with the zero itself and as we saw also previously that for the first remaining as zero so I'll just go on to all of my digits uh starting from 0 less than 10 and digits uh digit ++ I just do one thing and just say that ++ I just do one thing and just say that ++ I just do one thing and just say that DP of zero when the remaining is zero as I should you it was a base case for our um top down approach uh for this corresponding digit the answer is one now uh comes the interesting part that I will actually go on and say okay remaining uh remaining is one remaining is less than equals to n minus1 and then remaining Plus+ now uh what I will do is I'll just Plus+ now uh what I will do is I'll just Plus+ now uh what I will do is I'll just go and say okay uh the digit is again equal to zero digit is less than 10 and digit Plus+ I just go and go for digit Plus+ I just go and go for digit Plus+ I just go and go for all of my next digits for the corresponding digit uh I just say bro what can be the next digit it can be the next digit uh in like again the jumps are will be useful for us for the corresponding digit I'm going on and I just say okay our brackets are yeah now I'll just say that I'll just update that in my answer now answer plus okay I not initialized the answer we'll initialize the answer itself now for every digit shall I initialize it yeah let's initialize it now the answer is zero I just say that answer will be for this corresponding digit which is the remaining minus one and for this next digit what was what had been the value for me and for sure do the mod at every step when this is done for all the next digits I would have known that for this remaining for the corresponding digit this would have been my answer and simply assign that to my answer and that I can do it for every of my remaining digit combination now when this part is done again I'll go on to my answer and we say and go on to all the digits and I'll just say that instead of this my final uh my final DP of n minus one would have me showing that for this corresponding digit next M1 what should have been there so simply do this and if the brackets are correct I don't think they are correct let's remove this bracket and yeah it should work now so it's just that we can converted digit at line 24 we just want one I and this is how we can actually do it so uh in this we just actually converted our code to just the uh bottom up code now comes the interesting part uh now we have converted this code to a bottom up code can we see something in this code what whatsoever code we have written can we see something here yeah we can see something uh what you'll see that for every DP of remaining you are only using DP of remaining minus one so it is just that you're only using a previous state which means you only need a DP array of this next side which is actually the number of digits actually 10 so you just need a DP AR of size 10 and say okay I will have a previous digits of size 10 and the next and the current DP let's say the previous DP of size 10 and the DP of size 10 this DP will be storing this DP of remaining end digits this previous DP will be storing the DP of remaining minus one end digits now with this I can simply keep on assigning my DP previous DP like previous DP so I would need only two lines only two rows so I won't be needing those n of my previous rows so because in this let's say for DP of 15 and let's say a digit of two a DP of I would need a DP of 14 right and a digit of two like whatsoever is the next digit but DP of 13 and DP of 12 and all that stuff would not be needed so I only need the previous DP state so that's the reason I can just reduce my o of n space entirely and I would only use 2 into 10 space which is actually o of 20 space which actually o of constant space so my time is still o of n although it was O of n into 10 but yeah 10 is constant so it is O of n but my space can be reduced to O of one because I will use only current DP and the previous DP let's quickly modify it that's not a big change for us so if we go now we would not need a 2d DP uh we would just need a simple DP which is I we will just say that a DP and for sure the size is 10 now this DP and for sure we also need a previous DP now previous DP uh what shall we initialize with we'll initialize with one why one because we know that in the beginning the previous DP has a value of one itself okay cool now I just simply go on to my remaining I'll go on to my digits my answer as this my next digits are this my DP of remaining minus one is actually my previous DP okay that is done and for the next dig I will go uh DP of remaining minus one is actually the current DP okay that is done when this part of entirely of for every digit is done please simply make sure that you assign the previous DP value to the DP because we want to go on and keep forward right and ultimately in the end I will go into all the digits uh for DP I'll just have the current state uh my previous DP will always contain the answer so I'll just have the previous DP why not DP itself because let's say I just have my remaining like let's say my n is one itself so it will never come in inside but previous DP will still have the answer because one is for sure possible right so it will still get the value so previous DP will always contain the value DP may or may not contain depending upon if I have just ran the loop once or like I have not ran the loop at all so DP might not contain the value itself so that's the reason previous DP will always contain the answer that's the reason we always use the previous DP itself let's quickly run this code uh it should work yeah and you will see now the space uses o n rather than o of sorry the space user o of one rather than space user O N I hope that you guys got it uh if yes can we please smash that like button this is It's So Mo motivation for me uh it takes time and thanks watching goodbye take care bye-bye
Knight Dialer
orderly-queue
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell). Given an integer `n`, return how many distinct phone numbers of length `n` we can dial. You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps. As the answer may be very large, **return the answer modulo** `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 10 **Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient. **Example 2:** **Input:** n = 2 **Output:** 20 **Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\] **Example 3:** **Input:** n = 3131 **Output:** 136006598 **Explanation:** Please take care of the mod. **Constraints:** * `1 <= n <= 5000`
null
Math,String,Sorting
Hard
null
463
hello everyone so today's question is from july lead coding challenge day 7 and it's called island perimeter we have a 2d matrix or a grid of zeros and ones zero represents water and one represents land grid cells are connected horizontally and vertically not diagonally so from any given cell you can only go up down right or left grid is surrounded by water so we can imagine that our grid is part of a very large grade of zeros there is exactly one island it means that all ones in the grid are connected to each other either directly or indirectly so we can never see any grid like these each cell of this grid is a square of side length one and the grid is rectangular where both width and height are not more than hundred we have to find the perimeter of this island for example we have a grid of all zeros and ones there is exactly one island which has been highlighted and we have to find the parameter of this island so it would be 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 and 16. now the question is how do we solve it let's say we have a grid which contains a single one and all other elements are zero so the total parameter of this square island would be four now what if there are more number of ones because the problem statement says there is exactly one island which means all ones are connected we could have a new one adjacent to the old one let us say the new one is on the right side of the old one so now the contribution of old one in the total parameter would decrease by one similarly if there are two more ones other than the old one the contribution of old one in the total parameter would decrease by two so can we say that for any one the contribution in the total parameter would be four minus number of ones directly adjacent to it sounds good let's verify this on an example so we have a grid of zeros and ones and we need to sum up the contribution of all the ones in the total parameter so for this one we need to check the number of ones in the cells which are directly adjacent to it so you see the number of ones which are directly adjacent to this cell is one so its contribution in total perimeter would be four minus one that is three now for this cell for this one the number of ones which are directly adjacent to it is two so its contribution would be four minus two that is two similarly for this one the contribution would be 4 minus 2 that is 2. now for this last one contribution would be 4 minus 1 that is 3. so the total parameter of this island would be 10 let us now frame these steps into an algorithm the main idea is we sum up the total contribution to the total parameter by each fund so we initialize total parameter to be 0 initially then we traverse the grid and whenever we see a one we increase the total parameter by four then we count the number of adjacent cells having one then we need to decrease the total parameter like this and at the end we just return the total parameter that is p that's it let us quickly write a code initially total parameter would be zero then we traverse the grid and whenever we see a one we first update our total parameter like this then we are going to visit each one of the four adjacent cell to update the value of total parameter again at the end we are just going to return the total parameter so far so that's it for today's video if you like this video please hit the like button and subscribe to my channel
Island Perimeter
island-perimeter
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. **Example 1:** **Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\] **Output:** 16 **Explanation:** The perimeter is the 16 yellow stripes in the image above. **Example 2:** **Input:** grid = \[\[1\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0\]\] **Output:** 4 **Constraints:** * `row == grid.length` * `col == grid[i].length` * `1 <= row, col <= 100` * `grid[i][j]` is `0` or `1`. * There is exactly one island in `grid`.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
695,733,1104